docstring_tokens
stringlengths 0
76.5k
| code_tokens
stringlengths 75
1.81M
| label_window
sequencelengths 4
2.12k
| html_url
stringlengths 74
116
| file_name
stringlengths 3
311
|
---|---|---|---|---|
func periodicallyRefreshFilters() {
for range time.Tick(time.Minute) {
refreshFiltersIfNeccessary(false)
} | <mask> fmt.Fprintf(w, "OK %d filters updated\n", updated)
<mask> }
<mask>
<mask> // Sets up a timer that will be checking for filters updates periodically
<mask> func runFiltersUpdatesTimer() {
<mask> go func() {
<mask> for range time.Tick(time.Minute) {
<mask> checkFiltersUpdates(false)
<mask> }
<mask> }()
<mask> }
<mask>
<mask> // Checks filters updates if necessary
<mask> // If force is true, it ignores the filter.LastUpdated field value
<mask> func checkFiltersUpdates(force bool) int {
</s> Restore Engrish function names to normal English. </s> remove func checkFiltersUpdates(force bool) int {
</s> add func refreshFiltersIfNeccessary(force bool) int { </s> remove updated := checkFiltersUpdates(force != "")
</s> add updated := refreshFiltersIfNeccessary(force != "") </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove runFiltersUpdatesTimer()
</s> add go periodicallyRefreshFilters() | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246 | control.go |
func refreshFiltersIfNeccessary(force bool) int { | <mask> }
<mask>
<mask> // Checks filters updates if necessary
<mask> // If force is true, it ignores the filter.LastUpdated field value
<mask> func checkFiltersUpdates(force bool) int {
<mask> config.Lock()
<mask>
<mask> // fetch URLs
<mask> updateCount := 0
<mask> for i := range config.Filters {
</s> Restore Engrish function names to normal English. </s> remove func runFiltersUpdatesTimer() {
go func() {
for range time.Tick(time.Minute) {
checkFiltersUpdates(false)
}
}()
</s> add func periodicallyRefreshFilters() {
for range time.Tick(time.Minute) {
refreshFiltersIfNeccessary(false)
} </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove updated := checkFiltersUpdates(force != "")
</s> add updated := refreshFiltersIfNeccessary(force != "") </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove runFiltersUpdatesTimer()
</s> add go periodicallyRefreshFilters() | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246 | control.go |
github.com/mdlayher/packet v1.0.0 | <mask> github.com/mdlayher/ethernet v0.0.0-20220221185849-529eae5b6118
<mask> github.com/mdlayher/netlink v1.6.0
<mask> // TODO(a.garipov): This package is deprecated; find a new one or use
<mask> // our own code for that.
<mask> github.com/mdlayher/raw v0.1.0 // indirect
<mask> github.com/miekg/dns v1.1.50
<mask> github.com/stretchr/testify v1.7.1
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.mod |
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e | <mask> go.etcd.io/bbolt v1.3.6
<mask> golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
<mask> golang.org/x/net v0.0.0-20220728211354-c7608f3a8462
<mask> golang.org/x/sys v0.0.0-20220731174439-a90be440212d
<mask> gopkg.in/natefinch/lumberjack.v2 v2.0.0
<mask> gopkg.in/yaml.v3 v3.0.1
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d h1:Sv5ogFZatcgIMMtBSTTAgMYsicp25MXBubjXNDKwm80=
golang.org/x/sys v0.0.0-20220731174439-a90be440212d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 h1:9vYwv7OjYaky/tlAeD7C4oC9EsPTlaFl1H2jS++V+ME=
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
</s> add gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.mod |
gopkg.in/yaml.v3 v3.0.1 | <mask> golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
<mask> golang.org/x/net v0.0.0-20220728211354-c7608f3a8462
<mask> golang.org/x/sys v0.0.0-20220731174439-a90be440212d
<mask> gopkg.in/natefinch/lumberjack.v2 v2.0.0
<mask> gopkg.in/yaml.v2 v2.4.0
<mask> howett.net/plist v1.0.0
<mask> )
<mask>
<mask> require (
<mask> github.com/mdlayher/packet v1.0.0
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
</s> add gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.mod |
<mask> gopkg.in/yaml.v2 v2.4.0
<mask> howett.net/plist v1.0.0
<mask> )
<mask>
<mask> require (
<mask> github.com/mdlayher/packet v1.0.0
<mask> golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
<mask> )
<mask>
<mask> require (
<mask> github.com/BurntSushi/toml v1.1.0 // indirect
<mask> github.com/aead/chacha20 v0.0.0-20180709150244-8b13a72661da // indirect
<mask> github.com/aead/poly1305 v0.0.0-20180717145839-3fee0db0b635 // indirect
<mask> github.com/ameshkov/dnsstamps v1.0.3 // indirect
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
</s> add gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.mod |
|
<mask> golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
<mask> golang.org/x/text v0.3.7 // indirect
<mask> golang.org/x/tools v0.1.12 // indirect
<mask> gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
<mask> gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
<mask> )
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove github.com/kisielk/errcheck v1.6.1
</s> add github.com/kisielk/errcheck v1.6.2 </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
</s> add gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.mod |
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | <mask> gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
<mask> gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
<mask> gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
<mask> gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
<mask> gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
<mask> gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
<mask> grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o=
<mask> honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
<mask> honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
<mask> honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
<mask> howett.net/plist v1.0.0 h1:7CrbWYbPPO/PyNy38b2EB/+gYbjCe2DXBxgtOOZbSQM=
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove github.com/kisielk/errcheck v1.6.1
</s> add github.com/kisielk/errcheck v1.6.2 </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | go.sum |
"bytes" | <mask> package home
<mask>
<mask> import (
<mask> "fmt"
<mask> "net"
<mask> "os"
<mask> "path/filepath"
<mask> "sync"
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
yaml "gopkg.in/yaml.v3" | <mask> "github.com/AdguardTeam/golibs/errors"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/AdguardTeam/golibs/timeutil"
<mask> "github.com/google/renameio/maybe"
<mask> yaml "gopkg.in/yaml.v2"
<mask> )
<mask>
<mask> const (
<mask> dataDir = "data" // data storage
<mask> filterDir = "filters" // cache location for downloaded filters, it's under DataDir
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
// logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. | <mask> dataDir = "data" // data storage
<mask> filterDir = "filters" // cache location for downloaded filters, it's under DataDir
<mask> )
<mask>
<mask> // logSettings
<mask> type logSettings struct {
<mask> LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
<mask> LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
<mask> LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
<mask> LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
</s> add // File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would </s> remove func (c *configuration) write() error {
</s> add func (c *configuration) write() (err error) { </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
// File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` | <mask> )
<mask>
<mask> // logSettings
<mask> type logSettings struct {
<mask> LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
<mask> LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
<mask> LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
<mask> LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
<mask> LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
<mask> LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
<mask> Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
<mask> }
<mask>
<mask> // osConfig contains OS-related configuration.
<mask> type osConfig struct {
<mask> // Group is the name of the group which AdGuard Home must switch to on
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove func (c *configuration) write() error {
</s> add func (c *configuration) write() (err error) { </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
Compress: false,
LocalTime: false,
MaxBackups: 0,
MaxSize: 100,
MaxAge: 3, | <mask> HostsFile: true,
<mask> },
<mask> },
<mask> logSettings: logSettings{
<mask> LogCompress: false,
<mask> LogLocalTime: false,
<mask> LogMaxBackups: 0,
<mask> LogMaxSize: 100,
<mask> LogMaxAge: 3,
<mask> },
<mask> OSConfig: &osConfig{},
<mask> SchemaVersion: currentSchemaVersion,
<mask> }
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove ls.LogFile = args.logFile
} else if config.LogFile != "" {
ls.LogFile = config.LogFile
</s> add ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove Compress: ls.LogCompress, // disabled by default
LocalTime: ls.LogLocalTime,
MaxBackups: ls.LogMaxBackups,
MaxSize: ls.LogMaxSize, // megabytes
MaxAge: ls.LogMaxAge, // days
</s> add Compress: ls.Compress, // disabled by default
LocalTime: ls.LocalTime,
MaxBackups: ls.MaxBackups,
MaxSize: ls.MaxSize, // megabytes
MaxAge: ls.MaxAge, // days </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
func (c *configuration) write() (err error) { | <mask> return os.ReadFile(name)
<mask> }
<mask>
<mask> // Saves configuration to the YAML file and also saves the user filter contents to a file
<mask> func (c *configuration) write() error {
<mask> c.Lock()
<mask> defer c.Unlock()
<mask>
<mask> if Context.auth != nil {
<mask> config.Users = Context.auth.GetUsers()
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
</s> add // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
</s> add // File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
log.Debug("writing config file %q", configFile) | <mask>
<mask> config.Clients.Persistent = Context.clients.forConfig()
<mask>
<mask> configFile := config.getConfigFilename()
<mask> log.Debug("Writing YAML file: %s", configFile)
<mask> yamlText, err := yaml.Marshal(&config)
<mask> if err != nil {
<mask> log.Error("Couldn't generate YAML file: %s", err)
<mask>
<mask> return err
<mask> }
<mask>
<mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) | <mask> yamlText, err := yaml.Marshal(&config)
<mask> if err != nil {
<mask> log.Error("Couldn't generate YAML file: %s", err)
<mask>
<mask> return err
<mask> }
<mask>
<mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %s", err)
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
err = enc.Encode(config) | <mask>
<mask> return err
<mask> }
<mask>
<mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %s", err)
<mask>
<mask> return err
<mask> }
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
return fmt.Errorf("generating config file: %w", err)
} | <mask> }
<mask>
<mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %s", err)
<mask>
<mask> return err
<mask> }
<mask>
<mask> return nil
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) | <mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %s", err)
<mask>
<mask> return err
<mask> }
<mask>
<mask> return nil
<mask> }
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/config.go |
yaml "gopkg.in/yaml.v3" | <mask> "github.com/AdguardTeam/golibs/errors"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/AdguardTeam/golibs/netutil"
<mask> "github.com/ameshkov/dnscrypt/v2"
<mask> yaml "gopkg.in/yaml.v2"
<mask> )
<mask>
<mask> // Default ports.
<mask> const (
<mask> defaultPortDNS = 53
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/dns.go |
ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File | <mask> if args.verbose || config.Verbose {
<mask> ls.Verbose = true
<mask> }
<mask> if args.logFile != "" {
<mask> ls.LogFile = args.logFile
<mask> } else if config.LogFile != "" {
<mask> ls.LogFile = config.LogFile
<mask> }
<mask>
<mask> // Handle default log settings overrides
<mask> ls.LogCompress = config.LogCompress
<mask> ls.LogLocalTime = config.LogLocalTime
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove ls.LogCompress = config.LogCompress
ls.LogLocalTime = config.LogLocalTime
ls.LogMaxBackups = config.LogMaxBackups
ls.LogMaxSize = config.LogMaxSize
ls.LogMaxAge = config.LogMaxAge
</s> add ls.Compress = config.Compress
ls.LocalTime = config.LocalTime
ls.MaxBackups = config.MaxBackups
ls.MaxSize = config.MaxSize
ls.MaxAge = config.MaxAge </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
ls.Compress = config.Compress
ls.LocalTime = config.LocalTime
ls.MaxBackups = config.MaxBackups
ls.MaxSize = config.MaxSize
ls.MaxAge = config.MaxAge | <mask> ls.LogFile = config.LogFile
<mask> }
<mask>
<mask> // Handle default log settings overrides
<mask> ls.LogCompress = config.LogCompress
<mask> ls.LogLocalTime = config.LogLocalTime
<mask> ls.LogMaxBackups = config.LogMaxBackups
<mask> ls.LogMaxSize = config.LogMaxSize
<mask> ls.LogMaxAge = config.LogMaxAge
<mask>
<mask> // log.SetLevel(log.INFO) - default
<mask> if ls.Verbose {
<mask> log.SetLevel(log.DEBUG)
<mask> }
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove ls.LogFile = args.logFile
} else if config.LogFile != "" {
ls.LogFile = config.LogFile
</s> add ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { | <mask> // Make sure that we see the microseconds in logs, as networking stuff can
<mask> // happen pretty quickly.
<mask> log.SetFlags(log.LstdFlags | log.Lmicroseconds)
<mask>
<mask> if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
<mask> // When running as a Windows service, use eventlog by default if nothing
<mask> // else is configured. Otherwise, we'll simply lose the log output.
<mask> ls.LogFile = configSyslog
<mask> }
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { </s> remove if ls.LogFile == configSyslog {
</s> add if ls.File == configSyslog { </s> remove ls.LogFile = args.logFile
} else if config.LogFile != "" {
ls.LogFile = config.LogFile
</s> add ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
ls.File = configSyslog | <mask>
<mask> if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
<mask> // When running as a Windows service, use eventlog by default if nothing
<mask> // else is configured. Otherwise, we'll simply lose the log output.
<mask> ls.LogFile = configSyslog
<mask> }
<mask>
<mask> // logs are written to stdout (default)
<mask> if ls.LogFile == "" {
<mask> return
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { </s> remove if ls.LogFile == configSyslog {
</s> add if ls.File == configSyslog { </s> remove ls.LogFile = args.logFile
} else if config.LogFile != "" {
ls.LogFile = config.LogFile
</s> add ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
if ls.File == "" { | <mask> ls.LogFile = configSyslog
<mask> }
<mask>
<mask> // logs are written to stdout (default)
<mask> if ls.LogFile == "" {
<mask> return
<mask> }
<mask>
<mask> if ls.LogFile == configSyslog {
<mask> // Use syslog where it is possible and eventlog on Windows
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove if ls.LogFile == configSyslog {
</s> add if ls.File == configSyslog { </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { </s> remove ls.LogFile = args.logFile
} else if config.LogFile != "" {
ls.LogFile = config.LogFile
</s> add ls.File = args.logFile
} else if config.File != "" {
ls.File = config.File </s> remove LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
</s> add // File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
if ls.File == configSyslog { | <mask> if ls.LogFile == "" {
<mask> return
<mask> }
<mask>
<mask> if ls.LogFile == configSyslog {
<mask> // Use syslog where it is possible and eventlog on Windows
<mask> err := aghos.ConfigureSyslog(serviceName)
<mask> if err != nil {
<mask> log.Fatalf("cannot initialize syslog: %s", err)
<mask> }
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { </s> remove logFilePath := filepath.Join(Context.workDir, ls.LogFile)
if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
</s> add logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { </s> remove body, err := yaml.Marshal(diskConf)
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
logFilePath := filepath.Join(Context.workDir, ls.File)
if filepath.IsAbs(ls.File) {
logFilePath = ls.File | <mask> if err != nil {
<mask> log.Fatalf("cannot initialize syslog: %s", err)
<mask> }
<mask> } else {
<mask> logFilePath := filepath.Join(Context.workDir, ls.LogFile)
<mask> if filepath.IsAbs(ls.LogFile) {
<mask> logFilePath = ls.LogFile
<mask> }
<mask>
<mask> _, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644)
<mask> if err != nil {
<mask> log.Fatalf("cannot create a log file: %s", err)
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove if ls.LogFile == configSyslog {
</s> add if ls.File == configSyslog { </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Debug("Writing YAML file: %s", configFile)
yamlText, err := yaml.Marshal(&config)
if err != nil {
log.Error("Couldn't generate YAML file: %s", err)
</s> add log.Debug("writing config file %q", configFile) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
Compress: ls.Compress, // disabled by default
LocalTime: ls.LocalTime,
MaxBackups: ls.MaxBackups,
MaxSize: ls.MaxSize, // megabytes
MaxAge: ls.MaxAge, // days | <mask> }
<mask>
<mask> log.SetOutput(&lumberjack.Logger{
<mask> Filename: logFilePath,
<mask> Compress: ls.LogCompress, // disabled by default
<mask> LocalTime: ls.LogLocalTime,
<mask> MaxBackups: ls.LogMaxBackups,
<mask> MaxSize: ls.LogMaxSize, // megabytes
<mask> MaxAge: ls.LogMaxAge, // days
<mask> })
<mask> }
<mask> }
<mask>
<mask> // cleanup stops and resets all the modules.
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove LogCompress: false,
LogLocalTime: false,
LogMaxBackups: 0,
LogMaxSize: 100,
LogMaxAge: 3,
</s> add Compress: false,
LocalTime: false,
MaxBackups: 0,
MaxSize: 100,
MaxAge: 3, </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove if args.runningAsService && ls.LogFile == "" && runtime.GOOS == "windows" {
</s> add if args.runningAsService && ls.File == "" && runtime.GOOS == "windows" { </s> remove func (c *configuration) write() error {
</s> add func (c *configuration) write() (err error) { </s> remove if ls.LogFile == "" {
</s> add if ls.File == "" { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/home.go |
"bytes" | <mask>
<mask> import (
<mask> "fmt"
<mask> "net/url"
<mask> "os"
<mask> "path"
<mask> "path/filepath"
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove github.com/kisielk/errcheck v1.6.1
</s> add github.com/kisielk/errcheck v1.6.2 | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
yaml "gopkg.in/yaml.v3" | <mask> "github.com/AdguardTeam/golibs/netutil"
<mask> "github.com/AdguardTeam/golibs/timeutil"
<mask> "github.com/google/renameio/maybe"
<mask> "golang.org/x/crypto/bcrypt"
<mask> yaml "gopkg.in/yaml.v2"
<mask> )
<mask>
<mask> // currentSchemaVersion is the current schema version.
<mask> const currentSchemaVersion = 14
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3" </s> remove LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
</s> add // File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove body, err := yaml.Marshal(diskConf)
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) | <mask> if n == 0 {
<mask> return fmt.Errorf("unknown configuration schema version %d", oldVersion)
<mask> }
<mask>
<mask> body, err := yaml.Marshal(diskConf)
<mask> if err != nil {
<mask> return fmt.Errorf("generating new config: %w", err)
<mask> }
<mask>
<mask> config.fileData = body
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() </s> remove return fmt.Errorf("saving new config: %w", err)
</s> add return fmt.Errorf("writing new config: %w", err) </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
config.fileData = buf.Bytes() | <mask> if err != nil {
<mask> return fmt.Errorf("generating new config: %w", err)
<mask> }
<mask>
<mask> config.fileData = body
<mask> confFile := config.getConfigFilename()
<mask> err = maybe.WriteFile(confFile, body, 0o644)
<mask> if err != nil {
<mask> return fmt.Errorf("saving new config: %w", err)
<mask> }
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove return fmt.Errorf("saving new config: %w", err)
</s> add return fmt.Errorf("writing new config: %w", err) </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644) </s> remove body, err := yaml.Marshal(diskConf)
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
err = maybe.WriteFile(confFile, config.fileData, 0o644) | <mask> }
<mask>
<mask> config.fileData = body
<mask> confFile := config.getConfigFilename()
<mask> err = maybe.WriteFile(confFile, body, 0o644)
<mask> if err != nil {
<mask> return fmt.Errorf("saving new config: %w", err)
<mask> }
<mask>
<mask> return nil
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove return fmt.Errorf("saving new config: %w", err)
</s> add return fmt.Errorf("writing new config: %w", err) </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() </s> remove body, err := yaml.Marshal(diskConf)
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
return fmt.Errorf("writing new config: %w", err) | <mask> config.fileData = body
<mask> confFile := config.getConfigFilename()
<mask> err = maybe.WriteFile(confFile, body, 0o644)
<mask> if err != nil {
<mask> return fmt.Errorf("saving new config: %w", err)
<mask> }
<mask>
<mask> return nil
<mask> }
<mask>
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644) </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes() </s> remove body, err := yaml.Marshal(diskConf)
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
err = enc.Encode(diskConf) </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err) </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade.go |
// testDNSConf creates a DNS config for test the way gopkg.in/yaml.v3 would | <mask>
<mask> return diskConf
<mask> }
<mask>
<mask> // testDNSConf creates a DNS config for test the way gopkg.in/yaml.v2 would
<mask> // unmarshal it. In YAML, keys aren't guaranteed to always only be strings.
<mask> func testDNSConf(schemaVersion int) (dnsConf yobj) {
<mask> dnsConf = yobj{
<mask> "port": 53,
<mask> "blocked_response_ttl": 10,
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove func (c *configuration) write() error {
</s> add func (c *configuration) write() (err error) { </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove LogCompress bool `yaml:"log_compress"` // Compress determines if the rotated log files should be compressed using gzip (default: false)
LogLocalTime bool `yaml:"log_localtime"` // If the time used for formatting the timestamps in is the computer's local time (default: false [UTC])
LogMaxBackups int `yaml:"log_max_backups"` // Maximum number of old log files to retain (MaxAge may still cause them to get deleted)
LogMaxSize int `yaml:"log_max_size"` // Maximum size in megabytes of the log file before it gets rotated (default 100 MB)
LogMaxAge int `yaml:"log_max_age"` // MaxAge is the maximum number of days to retain old log files
LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
</s> add // File is the path to the log file. If empty, logs are written to stdout.
// If "syslog", logs are written to syslog.
File string `yaml:"log_file"`
// MaxBackups is the maximum number of old log files to retain.
//
// NOTE: MaxAge may still cause them to get deleted.
MaxBackups int `yaml:"log_max_backups"`
// MaxSize is the maximum size of the log file before it gets rotated, in
// megabytes. The default value is 100 MB.
MaxSize int `yaml:"log_max_size"`
// MaxAge is the maximum duration for retaining old log files, in days.
MaxAge int `yaml:"log_max_age"`
// Compress determines, if the rotated log files should be compressed using
// gzip.
Compress bool `yaml:"log_compress"`
// LocalTime determines, if the time used for formatting the timestamps in
// is the computer's local time.
LocalTime bool `yaml:"log_localtime"`
// Verbose determines, if verbose (aka debug) logging is enabled.
Verbose bool `yaml:"verbose"` </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/home/upgrade_test.go |
github.com/kisielk/errcheck v1.6.2 | <mask> require (
<mask> github.com/fzipp/gocyclo v0.6.0
<mask> github.com/golangci/misspell v0.3.5
<mask> github.com/gordonklaus/ineffassign v0.0.0-20210914165742-4cc7213b9bc8
<mask> github.com/kisielk/errcheck v1.6.1
<mask> github.com/kyoh86/looppointer v0.1.7
<mask> github.com/securego/gosec/v2 v2.12.0
<mask> golang.org/x/tools v0.1.12
<mask> honnef.co/go/tools v0.3.3
<mask> mvdan.cc/gofumpt v0.3.1
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove github.com/kisielk/errcheck v1.6.1 h1:cErYo+J4SmEjdXZrVXGwLJCE2sB06s23LpkcyWNrT+s=
github.com/kisielk/errcheck v1.6.1/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw=
</s> add github.com/kisielk/errcheck v1.6.2 h1:uGQ9xI8/pgc9iOoCe7kWQgRE6SBTrCGmTSf0LrEtY7c=
github.com/kisielk/errcheck v1.6.2/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw= </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
</s> add gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/tools/go.mod |
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect | <mask> github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 // indirect
<mask> golang.org/x/exp/typeparams v0.0.0-20220722155223-a9213eeb770e // indirect
<mask> golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect
<mask> golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
<mask> golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
<mask> gopkg.in/yaml.v2 v2.4.0 // indirect
<mask> )
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/tools/go.mod |
github.com/kisielk/errcheck v1.6.2 h1:uGQ9xI8/pgc9iOoCe7kWQgRE6SBTrCGmTSf0LrEtY7c=
github.com/kisielk/errcheck v1.6.2/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw= | <mask> github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
<mask> github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88/go.mod h1:3w7q1U84EfirKl04SVQ/s7nPm1ZPhiXd34z40TNz36k=
<mask> github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
<mask> github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
<mask> github.com/kisielk/errcheck v1.6.1 h1:cErYo+J4SmEjdXZrVXGwLJCE2sB06s23LpkcyWNrT+s=
<mask> github.com/kisielk/errcheck v1.6.1/go.mod h1:nXw/i/MfnvRHqXa7XXmQMUB0oNFGuBrNI8d8NLy0LPw=
<mask> github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
<mask> github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
<mask> github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
<mask> github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
<mask> github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove github.com/kisielk/errcheck v1.6.1
</s> add github.com/kisielk/errcheck v1.6.2 </s> remove // logSettings
</s> add // logSettings are the logging settings part of the configuration file.
//
// TODO(a.garipov): Put them into a separate object. </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
} </s> remove err = maybe.WriteFile(configFile, yamlText, 0o644)
</s> add err = enc.Encode(config) </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/tools/go.sum |
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 h1:9vYwv7OjYaky/tlAeD7C4oC9EsPTlaFl1H2jS++V+ME=
golang.org/x/sys v0.0.0-20220804214406-8e32c043e418/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | <mask> golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
<mask> golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
<mask> golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
<mask> golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
<mask> golang.org/x/sys v0.0.0-20220731174439-a90be440212d h1:Sv5ogFZatcgIMMtBSTTAgMYsicp25MXBubjXNDKwm80=
<mask> golang.org/x/sys v0.0.0-20220731174439-a90be440212d/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
<mask> golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
<mask> golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
<mask> golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
<mask> golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
<mask> golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
</s> Pull request: upd-yaml
Merge in DNS/adguard-home from upd-yaml to master
Squashed commit of the following:
commit f0c3a1896e7eba73b1c8a02533637cdabc89909b
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:28:02 2022 +0300
home: restore indent lvl
commit b52c124d2e786e8575c58e75efa7d2cd2b70b67f
Author: Ainar Garipov <[email protected]>
Date: Mon Aug 8 15:06:41 2022 +0300
all: upd tools, yaml mod </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> remove gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
</s> add </s> remove LogCompress: false,
LogLocalTime: false,
LogMaxBackups: 0,
LogMaxSize: 100,
LogMaxAge: 3,
</s> add Compress: false,
LocalTime: false,
MaxBackups: 0,
MaxSize: 100,
MaxAge: 3, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c | internal/tools/go.sum |
<mask> const (
<mask> LeaseChangedAdded = iota
<mask> LeaseChangedAddedStatic
<mask> LeaseChangedRemovedStatic
<mask> LeaseChangedBlacklisted
<mask>
<mask> LeaseChangedDBStore
<mask> )
<mask>
<mask> // Server - the current state of the DHCP server
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> remove if !bytes.Equal([]byte(l.Hostname), hostname) {
s.leasesLock.Unlock()
log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
return nil, true
}
</s> add </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/dhcpd.go |
|
<mask> }
<mask>
<mask> s.conf.notify(LeaseChangedDBStore)
<mask>
<mask> // s.conf.notify(LeaseChangedBlacklisted)
<mask>
<mask> } else {
<mask> reqIP := req.Options.Get(dhcpv4.OptionRequestedIPAddress)
<mask> if len(reqIP) != 0 &&
<mask> !bytes.Equal(reqIP, lease.IP) {
<mask> log.Debug("DHCPv4: different RequestedIP: %v != %v", reqIP, lease.IP)
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> remove if !bytes.Equal([]byte(l.Hostname), hostname) {
s.leasesLock.Unlock()
log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
return nil, true
}
</s> add </s> remove LeaseChangedBlacklisted
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/v4.go |
|
<mask> log.Debug("DHCPv4: different RequestedIP: %v != %v", reqIP, lease.IP)
<mask> }
<mask> }
<mask>
<mask> hostname := req.Options.Get(dhcpv4.OptionHostName)
<mask> lease.Hostname = string(hostname)
<mask>
<mask> resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeOffer))
<mask> return lease
<mask> }
<mask>
<mask> // Process Request request and return lease
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add </s> remove if !bytes.Equal([]byte(l.Hostname), hostname) {
s.leasesLock.Unlock()
log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
return nil, true
}
</s> add </s> remove LeaseChangedBlacklisted
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/v4.go |
|
<mask> log.Debug("DHCPv4: Mismatched OptionRequestedIPAddress in Request message for %s", mac)
<mask> return nil, true
<mask> }
<mask>
<mask> if !bytes.Equal([]byte(l.Hostname), hostname) {
<mask> s.leasesLock.Unlock()
<mask> log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
<mask> return nil, true
<mask> }
<mask>
<mask> lease = l
<mask> break
<mask> }
<mask> }
<mask> s.leasesLock.Unlock()
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add </s> remove LeaseChangedBlacklisted
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/v4.go |
|
lease.Hostname = string(hostname) | <mask>
<mask> if lease.Expiry.Unix() != leaseExpireStatic {
<mask> s.commitLease(lease)
<mask> } else if len(lease.Hostname) != 0 {
<mask> o := &optFQDN{
<mask> name: string(lease.Hostname),
<mask> }
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add </s> remove if !bytes.Equal([]byte(l.Hostname), hostname) {
s.leasesLock.Unlock()
log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
return nil, true
}
</s> add </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> remove LeaseChangedBlacklisted
</s> add | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/v4.go |
} else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) | <mask>
<mask> if lease.Expiry.Unix() != leaseExpireStatic {
<mask> lease.Hostname = string(hostname)
<mask> s.commitLease(lease)
<mask> }
<mask>
<mask> resp.UpdateOption(dhcpv4.OptMessageType(dhcpv4.MessageTypeAck))
<mask> return lease, true
<mask> }
</s> * DHCP: don't replace the host name from static lease
When a static lease contains a host name
and client sends its own host name:
1. don't replace the host name from static lease with it
2. send option FQDN to the client in Ack response packet </s> remove if !bytes.Equal([]byte(l.Hostname), hostname) {
s.leasesLock.Unlock()
log.Debug("DHCPv4: Mismatched OptionHostName in Request message for %s", mac)
return nil, true
}
</s> add </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> remove LeaseChangedBlacklisted
</s> add | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31 | dhcpd/v4.go |
// FindMACbyIP - find a MAC address by IP address in the currently active DHCP leases
func (s *Server) FindMACbyIP(ip net.IP) net.HardwareAddr {
now := time.Now().Unix()
s.leasesLock.RLock()
defer s.leasesLock.RUnlock()
for _, l := range s.leases {
if l.Expiry.Unix() > now && l.IP.Equal(ip) {
return l.HWAddr
}
}
return nil
}
| <mask> }
<mask>
<mask> // Reset internal state
<mask> func (s *Server) reset() {
<mask> s.leasesLock.Lock()
<mask> s.leases = nil
<mask> s.IPpool = make(map[[4]byte]net.HardwareAddr)
<mask> s.leasesLock.Unlock()
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove func (clients *clientsContainer) Init() {
</s> add func (clients *clientsContainer) Init(objects []clientObject) { </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"} | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | dhcpd/dhcpd.go |
"bytes" | <mask> package home
<mask>
<mask> import (
<mask> "encoding/json"
<mask> "fmt"
<mask> "io/ioutil"
<mask> "net"
<mask> "net/http"
<mask> "os"
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove "net/http"
</s> add </s> remove type clientJSON struct {
IP string `json:"ip"`
MAC string `json:"mac"`
Name string `json:"name"`
UseGlobalSettings bool `json:"use_global_settings"`
FilteringEnabled bool `json:"filtering_enabled"`
ParentalEnabled bool `json:"parental_enabled"`
SafeSearchEnabled bool `json:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `json:"safesearch_enabled"`
WhoisInfo map[string]interface{} `json:"whois_info"`
UseGlobalBlockedServices bool `json:"use_global_blocked_services"`
BlockedServices []string `json:"blocked_services"`
}
</s> add </s> remove if ip == ipAddr.String() {
</s> add if bytes.Equal(hwAddr, macFound) { </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c | [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
<mask> "encoding/json"
<mask> "fmt"
<mask> "io/ioutil"
<mask> "net"
<mask> "net/http"
<mask> "os"
<mask> "os/exec"
<mask> "runtime"
<mask> "strings"
<mask> "sync"
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove "encoding/json"
</s> add "bytes" </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
|
IDs []string | <mask> )
<mask>
<mask> // Client information
<mask> type Client struct {
<mask> IP string
<mask> MAC string
<mask> Name string
<mask> UseOwnSettings bool // false: use global settings
<mask> FilteringEnabled bool
<mask> SafeSearchEnabled bool
<mask> SafeBrowsingEnabled bool
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove type clientJSON struct {
IP string `json:"ip"`
MAC string `json:"mac"`
Name string `json:"name"`
UseGlobalSettings bool `json:"use_global_settings"`
FilteringEnabled bool `json:"filtering_enabled"`
ParentalEnabled bool `json:"parental_enabled"`
SafeSearchEnabled bool `json:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `json:"safesearch_enabled"`
WhoisInfo map[string]interface{} `json:"whois_info"`
UseGlobalBlockedServices bool `json:"use_global_blocked_services"`
BlockedServices []string `json:"blocked_services"`
}
</s> add </s> remove type clientObject struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
MAC string `yaml:"mac"`
UseGlobalSettings bool `yaml:"use_global_settings"`
FilteringEnabled bool `yaml:"filtering_enabled"`
ParentalEnabled bool `yaml:"parental_enabled"`
SafeSearchEnabled bool `yaml:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `yaml:"safesearch_enabled"`
UseGlobalBlockedServices bool `yaml:"use_global_blocked_services"`
BlockedServices []string `yaml:"blocked_services"`
}
</s> add </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove ipIndex map[string]*Client // IP -> client
</s> add idIndex map[string]*Client // IP -> client | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
<mask> UseOwnBlockedServices bool // false: use global settings
<mask> BlockedServices []string
<mask> }
<mask>
<mask> type clientJSON struct {
<mask> IP string `json:"ip"`
<mask> MAC string `json:"mac"`
<mask> Name string `json:"name"`
<mask> UseGlobalSettings bool `json:"use_global_settings"`
<mask> FilteringEnabled bool `json:"filtering_enabled"`
<mask> ParentalEnabled bool `json:"parental_enabled"`
<mask> SafeSearchEnabled bool `json:"safebrowsing_enabled"`
<mask> SafeBrowsingEnabled bool `json:"safesearch_enabled"`
<mask>
<mask> WhoisInfo map[string]interface{} `json:"whois_info"`
<mask>
<mask> UseGlobalBlockedServices bool `json:"use_global_blocked_services"`
<mask> BlockedServices []string `json:"blocked_services"`
<mask> }
<mask>
<mask> type clientSource uint
<mask>
<mask> // Client sources
<mask> const (
<mask> // Priority: etc/hosts > DHCP > ARP > rDNS > WHOIS
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP string
MAC string
</s> add IDs []string </s> remove type clientObject struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
MAC string `yaml:"mac"`
UseGlobalSettings bool `yaml:"use_global_settings"`
FilteringEnabled bool `yaml:"filtering_enabled"`
ParentalEnabled bool `yaml:"parental_enabled"`
SafeSearchEnabled bool `yaml:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `yaml:"safesearch_enabled"`
UseGlobalBlockedServices bool `yaml:"use_global_blocked_services"`
BlockedServices []string `yaml:"blocked_services"`
}
</s> add </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
|
idIndex map[string]*Client // IP -> client | <mask> }
<mask>
<mask> type clientsContainer struct {
<mask> list map[string]*Client // name -> client
<mask> ipIndex map[string]*Client // IP -> client
<mask> ipHost map[string]*ClientHost // IP -> Hostname
<mask> lock sync.Mutex
<mask> }
<mask>
<mask> // Init initializes clients container
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove func (clients *clientsContainer) Init() {
</s> add func (clients *clientsContainer) Init(objects []clientObject) { </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) </s> remove type clientObject struct {
Name string `yaml:"name"`
IP string `yaml:"ip"`
MAC string `yaml:"mac"`
UseGlobalSettings bool `yaml:"use_global_settings"`
FilteringEnabled bool `yaml:"filtering_enabled"`
ParentalEnabled bool `yaml:"parental_enabled"`
SafeSearchEnabled bool `yaml:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `yaml:"safesearch_enabled"`
UseGlobalBlockedServices bool `yaml:"use_global_blocked_services"`
BlockedServices []string `yaml:"blocked_services"`
}
</s> add </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove IP string
MAC string
</s> add IDs []string | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
func (clients *clientsContainer) Init(objects []clientObject) { | <mask> }
<mask>
<mask> // Init initializes clients container
<mask> // Note: this function must be called only once
<mask> func (clients *clientsContainer) Init() {
<mask> if clients.list != nil {
<mask> log.Fatal("clients.list != nil")
<mask> }
<mask> clients.list = make(map[string]*Client)
<mask> clients.ipIndex = make(map[string]*Client)
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove clients.ipIndex = make(map[string]*Client)
</s> add clients.idIndex = make(map[string]*Client) </s> remove ipIndex map[string]*Client // IP -> client
</s> add idIndex map[string]*Client // IP -> client </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
clients.idIndex = make(map[string]*Client) | <mask> if clients.list != nil {
<mask> log.Fatal("clients.list != nil")
<mask> }
<mask> clients.list = make(map[string]*Client)
<mask> clients.ipIndex = make(map[string]*Client)
<mask> clients.ipHost = make(map[string]*ClientHost)
<mask>
<mask> go clients.periodicUpdate()
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove func (clients *clientsContainer) Init() {
</s> add func (clients *clientsContainer) Init(objects []clientObject) { </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
clients.addFromConfig(objects) | <mask> }
<mask> clients.list = make(map[string]*Client)
<mask> clients.idIndex = make(map[string]*Client)
<mask> clients.ipHost = make(map[string]*ClientHost)
<mask>
<mask> go clients.periodicUpdate()
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove clients.ipIndex = make(map[string]*Client)
</s> add clients.idIndex = make(map[string]*Client) </s> remove func (clients *clientsContainer) Init() {
</s> add func (clients *clientsContainer) Init(objects []clientObject) { </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"} </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
_, ok := clients.idIndex[ip] | <mask> func (clients *clientsContainer) Exists(ip string, source clientSource) bool {
<mask> clients.lock.Lock()
<mask> defer clients.lock.Unlock()
<mask>
<mask> _, ok := clients.ipIndex[ip]
<mask> if ok {
<mask> return true
<mask> }
<mask>
<mask> ch, ok := clients.ipHost[ip]
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, false
}
| <mask> // Find searches for a client by IP
<mask> func (clients *clientsContainer) Find(ip string) (Client, bool) {
<mask> clients.lock.Lock()
<mask> defer clients.lock.Unlock()
<mask>
<mask> c, ok := clients.idIndex[ip]
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
c, ok := clients.idIndex[ip] | <mask> func (clients *clientsContainer) Find(ip string) (Client, bool) {
<mask> clients.lock.Lock()
<mask> defer clients.lock.Unlock()
<mask>
<mask> c, ok := clients.ipIndex[ip]
<mask> if ok {
<mask> return *c, true
<mask> }
<mask>
<mask> for _, c = range clients.list {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) | <mask> return *c, true
<mask> }
<mask>
<mask> for _, c = range clients.list {
<mask> if len(c.MAC) != 0 {
<mask> mac, err := net.ParseMAC(c.MAC)
<mask> if err != nil {
<mask> continue
<mask> }
<mask> ipAddr := config.dhcpServer.FindIPbyMAC(mac)
<mask> if ipAddr == nil {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove if ip == ipAddr.String() {
</s> add if bytes.Equal(hwAddr, macFound) { </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { | <mask> mac, err := net.ParseMAC(c.MAC)
<mask> if err != nil {
<mask> continue
<mask> }
<mask> ipAddr := config.dhcpServer.FindIPbyMAC(mac)
<mask> if ipAddr == nil {
<mask> continue
<mask> }
<mask> if ip == ipAddr.String() {
<mask> return *c, true
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if ip == ipAddr.String() {
</s> add if bytes.Equal(hwAddr, macFound) { </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
if bytes.Equal(hwAddr, macFound) { | <mask> ipAddr := config.dhcpServer.FindIPbyMAC(mac)
<mask> if ipAddr == nil {
<mask> continue
<mask> }
<mask> if ip == ipAddr.String() {
<mask> return *c, true
<mask> }
<mask> }
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
if len(c.IDs) == 0 {
return fmt.Errorf("ID required") | <mask> if len(c.Name) == 0 {
<mask> return fmt.Errorf("Invalid Name")
<mask> }
<mask>
<mask> if (len(c.IP) == 0 && len(c.MAC) == 0) ||
<mask> (len(c.IP) != 0 && len(c.MAC) != 0) {
<mask> return fmt.Errorf("IP or MAC required")
<mask> }
<mask>
<mask> if len(c.IP) != 0 {
<mask> ip := net.ParseIP(c.IP)
<mask> if ip == nil {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove if ip == ipAddr.String() {
</s> add if bytes.Equal(hwAddr, macFound) { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | <mask> (len(c.IP) != 0 && len(c.MAC) != 0) {
<mask> return fmt.Errorf("IP or MAC required")
<mask> }
<mask>
<mask> if len(c.IP) != 0 {
<mask> ip := net.ParseIP(c.IP)
<mask> if ip == nil {
<mask> return fmt.Errorf("Invalid IP")
<mask> }
<mask> c.IP = ip.String()
<mask> } else {
<mask> _, err := net.ParseMAC(c.MAC)
<mask> if err != nil {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if (len(c.IP) == 0 && len(c.MAC) == 0) ||
(len(c.IP) != 0 && len(c.MAC) != 0) {
return fmt.Errorf("IP or MAC required")
</s> add if len(c.IDs) == 0 {
return fmt.Errorf("ID required") </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
_, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue | <mask> ip := net.ParseIP(c.IP)
<mask> if ip == nil {
<mask> return fmt.Errorf("Invalid IP")
<mask> }
<mask> c.IP = ip.String()
<mask> } else {
<mask> _, err := net.ParseMAC(c.MAC)
<mask> if err != nil {
<mask> return fmt.Errorf("Invalid MAC: %s", err)
<mask> }
<mask> }
<mask> return nil
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove for _, cy := range config.Clients {
cli := Client{
Name: cy.Name,
IP: cy.IP,
MAC: cy.MAC,
UseOwnSettings: !cy.UseGlobalSettings,
FilteringEnabled: cy.FilteringEnabled,
ParentalEnabled: cy.ParentalEnabled,
SafeSearchEnabled: cy.SafeSearchEnabled,
SafeBrowsingEnabled: cy.SafeBrowsingEnabled,
UseOwnBlockedServices: !cy.UseGlobalBlockedServices,
BlockedServices: cy.BlockedServices,
}
_, err = config.clients.Add(cli)
if err != nil {
log.Tracef("clientAdd: %s", err)
}
}
config.Clients = nil
</s> add </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
return fmt.Errorf("Invalid ID: %s", id) | <mask> _, err = net.ParseMAC(id)
<mask> if err == nil {
<mask> continue
<mask> }
<mask> }
<mask> return nil
<mask> }
<mask>
<mask> // Add a new client object
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] | <mask> if ok {
<mask> return false, nil
<mask> }
<mask>
<mask> // check IP index
<mask> if len(c.IP) != 0 {
<mask> c2, ok := clients.ipIndex[c.IP]
<mask> if ok {
<mask> return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
<mask> }
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) | <mask> // check IP index
<mask> if len(c.IP) != 0 {
<mask> c2, ok := clients.ipIndex[c.IP]
<mask> if ok {
<mask> return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
<mask> }
<mask> }
<mask>
<mask> ch, ok := clients.ipHost[c.IP]
<mask> if ok {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} | <mask> return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
<mask> }
<mask> }
<mask>
<mask> ch, ok := clients.ipHost[c.IP]
<mask> if ok {
<mask> c.WhoisInfo = ch.WhoisInfo
<mask> delete(clients.ipHost, c.IP)
<mask> }
<mask>
<mask> clients.list[c.Name] = &c
<mask> if len(c.IP) != 0 {
<mask> clients.ipIndex[c.IP] = &c
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// update Name index | <mask> }
<mask>
<mask> clients.list[c.Name] = &c
<mask>
<mask> // update ID index
<mask> for _, id := range c.IDs {
<mask> clients.idIndex[id] = &c
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c | <mask> delete(clients.ipHost, c.IP)
<mask> }
<mask>
<mask> clients.list[c.Name] = &c
<mask> if len(c.IP) != 0 {
<mask> clients.ipIndex[c.IP] = &c
<mask> }
<mask>
<mask> log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
<mask> return true, nil
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) | <mask> if len(c.IP) != 0 {
<mask> clients.ipIndex[c.IP] = &c
<mask> }
<mask>
<mask> log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
<mask> return true, nil
<mask> }
<mask>
<mask> // Del removes a client
<mask> func (clients *clientsContainer) Del(name string) bool {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// update Name index | <mask> return false
<mask> }
<mask>
<mask> delete(clients.list, name)
<mask>
<mask> // update ID index
<mask> for _, id := range c.IDs {
<mask> delete(clients.idIndex, id)
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove delete(clients.ipIndex, c.IP)
</s> add // update ID index
for _, id := range c.IDs {
delete(clients.idIndex, id)
}
return true
}
// Return TRUE if arrays are equal
func arraysEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i != len(a); i++ {
if a[i] != b[i] {
return false
}
} </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] | [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
// update ID index
for _, id := range c.IDs {
delete(clients.idIndex, id)
}
return true
}
// Return TRUE if arrays are equal
func arraysEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i != len(a); i++ {
if a[i] != b[i] {
return false
}
} | <mask> return false
<mask> }
<mask>
<mask> delete(clients.list, name)
<mask> delete(clients.ipIndex, c.IP)
<mask> return true
<mask> }
<mask>
<mask> // Update a client
<mask> func (clients *clientsContainer) Update(name string, c Client) error {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old | <mask> }
<mask> }
<mask>
<mask> // check IP index
<mask> if old.IP != c.IP && len(c.IP) != 0 {
<mask> c2, ok := clients.ipIndex[c.IP]
<mask> if ok {
<mask> return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
<mask> }
<mask> }
<mask>
<mask> // update Name index
<mask> if old.Name != c.Name {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
clients.list[c.Name] = old | <mask>
<mask> // update Name index
<mask> if old.Name != c.Name {
<mask> delete(clients.list, old.Name)
<mask> }
<mask> clients.list[c.Name] = &c
<mask>
<mask> // update IP index
<mask> if old.IP != c.IP {
<mask> delete(clients.ipIndex, old.IP)
<mask> }
<mask> if len(c.IP) != 0 {
<mask> clients.ipIndex[c.IP] = &c
<mask> }
<mask>
<mask> return nil
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add // update ID index
for _, id := range c.IDs {
clients.idIndex[id] = &c </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
*old = c | <mask> delete(clients.list, old.Name)
<mask> clients.list[c.Name] = old
<mask> }
<mask>
<mask> return nil
<mask> }
<mask>
<mask> // SetWhoisInfo - associate WHOIS information with a client
<mask> func (clients *clientsContainer) SetWhoisInfo(ip string, info [][]string) {
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove }
clients.list[c.Name] = &c
// update IP index
if old.IP != c.IP {
delete(clients.ipIndex, old.IP)
}
if len(c.IP) != 0 {
clients.ipIndex[c.IP] = &c
</s> add clients.list[c.Name] = old </s> remove delete(clients.ipIndex, c.IP)
</s> add // update ID index
for _, id := range c.IDs {
delete(clients.idIndex, id)
}
return true
}
// Return TRUE if arrays are equal
func arraysEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i != len(a); i++ {
if a[i] != b[i] {
return false
}
} </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
c, ok := clients.idIndex[ip] | <mask> func (clients *clientsContainer) SetWhoisInfo(ip string, info [][]string) {
<mask> clients.lock.Lock()
<mask> defer clients.lock.Unlock()
<mask>
<mask> c, ok := clients.ipIndex[ip]
<mask> if ok {
<mask> c.WhoisInfo = info
<mask> log.Debug("Clients: set WHOIS info for client %s: %v", c.Name, c.WhoisInfo)
<mask> return
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
_, ok := clients.idIndex[ip] | <mask> clients.lock.Lock()
<mask> defer clients.lock.Unlock()
<mask>
<mask> // check index
<mask> _, ok := clients.ipIndex[ip]
<mask> if ok {
<mask> return false, nil
<mask> }
<mask>
<mask> // check auto-clients index
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove // check IP index
if len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
</s> add // check ID index
for _, id := range c.IDs {
c2, ok := clients.idIndex[id] </s> remove return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) </s> remove _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip] </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
<mask> }
<mask> }
<mask> log.Debug("Added %d client aliases from DHCP", n)
<mask> }
<mask>
<mask> type clientHostJSON struct {
<mask> IP string `json:"ip"`
<mask> Name string `json:"name"`
<mask> Source string `json:"source"`
<mask>
<mask> WhoisInfo map[string]interface{} `json:"whois_info"`
<mask> }
<mask>
<mask> type clientListJSON struct {
<mask> Clients []clientJSON `json:"clients"`
<mask> AutoClients []clientHostJSON `json:"auto_clients"`
<mask> }
<mask>
<mask> // respond with information about configured clients
<mask> func handleGetClients(w http.ResponseWriter, r *http.Request) {
<mask> data := clientListJSON{}
<mask>
<mask> config.clients.lock.Lock()
<mask> for _, c := range config.clients.list {
<mask> cj := clientJSON{
<mask> IP: c.IP,
<mask> MAC: c.MAC,
<mask> Name: c.Name,
<mask> UseGlobalSettings: !c.UseOwnSettings,
<mask> FilteringEnabled: c.FilteringEnabled,
<mask> ParentalEnabled: c.ParentalEnabled,
<mask> SafeSearchEnabled: c.SafeSearchEnabled,
<mask> SafeBrowsingEnabled: c.SafeBrowsingEnabled,
<mask>
<mask> UseGlobalBlockedServices: !c.UseOwnBlockedServices,
<mask> BlockedServices: c.BlockedServices,
<mask> }
<mask>
<mask> if len(c.MAC) != 0 {
<mask> hwAddr, _ := net.ParseMAC(c.MAC)
<mask> ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
<mask> if ipAddr != nil {
<mask> cj.IP = ipAddr.String()
<mask> }
<mask> }
<mask>
<mask> cj.WhoisInfo = make(map[string]interface{})
<mask> for _, wi := range c.WhoisInfo {
<mask> cj.WhoisInfo[wi[0]] = wi[1]
<mask> }
<mask>
<mask> data.Clients = append(data.Clients, cj)
<mask> }
<mask> for ip, ch := range config.clients.ipHost {
<mask> cj := clientHostJSON{
<mask> IP: ip,
<mask> Name: ch.Host,
<mask> }
<mask>
<mask> cj.Source = "etc/hosts"
<mask> switch ch.Source {
<mask> case ClientSourceDHCP:
<mask> cj.Source = "DHCP"
<mask> case ClientSourceRDNS:
<mask> cj.Source = "rDNS"
<mask> case ClientSourceARP:
<mask> cj.Source = "ARP"
<mask> case ClientSourceWHOIS:
<mask> cj.Source = "WHOIS"
<mask> }
<mask>
<mask> cj.WhoisInfo = make(map[string]interface{})
<mask> for _, wi := range ch.WhoisInfo {
<mask> cj.WhoisInfo[wi[0]] = wi[1]
<mask> }
<mask>
<mask> data.AutoClients = append(data.AutoClients, cj)
<mask> }
<mask> config.clients.lock.Unlock()
<mask>
<mask> w.Header().Set("Content-Type", "application/json")
<mask> e := json.NewEncoder(w).Encode(data)
<mask> if e != nil {
<mask> httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
<mask> return
<mask> }
<mask> }
<mask>
<mask> // Convert JSON object to Client object
<mask> func jsonToClient(cj clientJSON) (*Client, error) {
<mask> c := Client{
<mask> IP: cj.IP,
<mask> MAC: cj.MAC,
<mask> Name: cj.Name,
<mask> UseOwnSettings: !cj.UseGlobalSettings,
<mask> FilteringEnabled: cj.FilteringEnabled,
<mask> ParentalEnabled: cj.ParentalEnabled,
<mask> SafeSearchEnabled: cj.SafeSearchEnabled,
<mask> SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
<mask>
<mask> UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
<mask> BlockedServices: cj.BlockedServices,
<mask> }
<mask> return &c, nil
<mask> }
<mask>
<mask> // Add a new client
<mask> func handleAddClient(w http.ResponseWriter, r *http.Request) {
<mask> body, err := ioutil.ReadAll(r.Body)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
<mask> return
<mask> }
<mask>
<mask> cj := clientJSON{}
<mask> err = json.Unmarshal(body, &cj)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
<mask> return
<mask> }
<mask>
<mask> c, err := jsonToClient(cj)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "%s", err)
<mask> return
<mask> }
<mask> ok, err := config.clients.Add(*c)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "%s", err)
<mask> return
<mask> }
<mask> if !ok {
<mask> httpError(w, http.StatusBadRequest, "Client already exists")
<mask> return
<mask> }
<mask>
<mask> _ = writeAllConfigsAndReloadDNS()
<mask> returnOK(w)
<mask> }
<mask>
<mask> // Remove client
<mask> func handleDelClient(w http.ResponseWriter, r *http.Request) {
<mask> body, err := ioutil.ReadAll(r.Body)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
<mask> return
<mask> }
<mask>
<mask> cj := clientJSON{}
<mask> err = json.Unmarshal(body, &cj)
<mask> if err != nil || len(cj.Name) == 0 {
<mask> httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
<mask> return
<mask> }
<mask>
<mask> if !config.clients.Del(cj.Name) {
<mask> httpError(w, http.StatusBadRequest, "Client not found")
<mask> return
<mask> }
<mask>
<mask> _ = writeAllConfigsAndReloadDNS()
<mask> returnOK(w)
<mask> }
<mask>
<mask> type updateJSON struct {
<mask> Name string `json:"name"`
<mask> Data clientJSON `json:"data"`
<mask> }
<mask>
<mask> // Update client's properties
<mask> func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
<mask> body, err := ioutil.ReadAll(r.Body)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
<mask> return
<mask> }
<mask>
<mask> var dj updateJSON
<mask> err = json.Unmarshal(body, &dj)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
<mask> return
<mask> }
<mask> if len(dj.Name) == 0 {
<mask> httpError(w, http.StatusBadRequest, "Invalid request")
<mask> return
<mask> }
<mask>
<mask> c, err := jsonToClient(dj.Data)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "%s", err)
<mask> return
<mask> }
<mask>
<mask> err = config.clients.Update(dj.Name, *c)
<mask> if err != nil {
<mask> httpError(w, http.StatusBadRequest, "%s", err)
<mask> return
<mask> }
<mask>
<mask> _ = writeAllConfigsAndReloadDNS()
<mask> returnOK(w)
<mask> }
<mask>
<mask> // RegisterClientsHandlers registers HTTP handlers
<mask> func RegisterClientsHandlers() {
<mask> httpRegister(http.MethodGet, "/control/clients", handleGetClients)
<mask> httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
<mask> httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
<mask> httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove for _, cy := range config.Clients {
cli := Client{
Name: cy.Name,
IP: cy.IP,
MAC: cy.MAC,
UseOwnSettings: !cy.UseGlobalSettings,
FilteringEnabled: cy.FilteringEnabled,
ParentalEnabled: cy.ParentalEnabled,
SafeSearchEnabled: cy.SafeSearchEnabled,
SafeBrowsingEnabled: cy.SafeBrowsingEnabled,
UseOwnBlockedServices: !cy.UseGlobalBlockedServices,
BlockedServices: cy.BlockedServices,
}
_, err = config.clients.Add(cli)
if err != nil {
log.Tracef("clientAdd: %s", err)
}
}
config.Clients = nil
</s> add </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients.go |
|
clients.Init(nil) | <mask> var e error
<mask> var b bool
<mask> clients := clientsContainer{}
<mask>
<mask> clients.Init()
<mask>
<mask> // add
<mask> c = Client{
<mask> IP: "1.1.1.1",
<mask> Name: "client1",
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, | <mask> clients.Init()
<mask>
<mask> // add
<mask> c = Client{
<mask> IP: "1.1.1.1",
<mask> Name: "client1",
<mask> }
<mask> b, e = clients.Add(c)
<mask> if !b || e != nil {
<mask> t.Fatalf("Add #1")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove assert.True(t, !(!clients.Del("client1") || clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !(!clients.Del("client1-renamed") || clients.Exists("1.1.1.2", ClientSourceHostsFile))) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
IDs: []string{"2.2.2.2"}, | <mask> }
<mask>
<mask> // add #2
<mask> c = Client{
<mask> IP: "2.2.2.2",
<mask> Name: "client2",
<mask> }
<mask> b, e = clients.Add(c)
<mask> if !b || e != nil {
<mask> t.Fatalf("Add #2")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove assert.True(t, !(!clients.Del("client1") || clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !(!clients.Del("client1-renamed") || clients.Exists("1.1.1.2", ClientSourceHostsFile))) </s> remove clients.Init()
</s> add clients.Init(nil) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
IDs: []string{"1.2.3.5"}, | <mask> }
<mask>
<mask> // failed add - name in use
<mask> c = Client{
<mask> IP: "1.2.3.5",
<mask> Name: "client1",
<mask> }
<mask> b, _ = clients.Add(c)
<mask> if b {
<mask> t.Fatalf("Add - name in use")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
IDs: []string{"2.2.2.2"}, | <mask> }
<mask>
<mask> // failed add - ip in use
<mask> c = Client{
<mask> IP: "2.2.2.2",
<mask> Name: "client3",
<mask> }
<mask> b, e = clients.Add(c)
<mask> if b || e == nil {
<mask> t.Fatalf("Add - ip in use")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
c.IDs = []string{"1.2.3.0"} | <mask> assert.True(t, clients.Exists("1.1.1.1", ClientSourceHostsFile))
<mask> assert.True(t, clients.Exists("2.2.2.2", ClientSourceHostsFile))
<mask>
<mask> // failed update - no such name
<mask> c.IP = "1.2.3.0"
<mask> c.Name = "client3"
<mask> if clients.Update("client3", c) == nil {
<mask> t.Fatalf("Update")
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove assert.True(t, !(clients.Exists("1.1.1.1", ClientSourceHostsFile) || !clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !clients.Exists("1.1.1.1", ClientSourceHostsFile))
assert.True(t, clients.Exists("1.1.1.2", ClientSourceHostsFile))
// update - rename
c.IDs = []string{"1.1.1.2"}
c.Name = "client1-renamed"
c.UseOwnSettings = true
assert.True(t, clients.Update("client1", c) == nil)
c = Client{}
c, b = clients.Find("1.1.1.2")
assert.True(t, b && c.Name == "client1-renamed" && c.IDs[0] == "1.1.1.2" && c.UseOwnSettings) </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"} </s> remove assert.True(t, !(!clients.Del("client1") || clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !(!clients.Del("client1-renamed") || clients.Exists("1.1.1.2", ClientSourceHostsFile))) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
c.IDs = []string{"1.2.3.0"} | <mask> t.Fatalf("Update")
<mask> }
<mask>
<mask> // failed update - name in use
<mask> c.IP = "1.2.3.0"
<mask> c.Name = "client2"
<mask> if clients.Update("client1", c) == nil {
<mask> t.Fatalf("Update - name in use")
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"} </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
c.IDs = []string{"2.2.2.2"} | <mask> t.Fatalf("Update - name in use")
<mask> }
<mask>
<mask> // failed update - ip in use
<mask> c.IP = "2.2.2.2"
<mask> c.Name = "client1"
<mask> if clients.Update("client1", c) == nil {
<mask> t.Fatalf("Update - ip in use")
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"} </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
c.IDs = []string{"1.1.1.2"} | <mask> t.Fatalf("Update - ip in use")
<mask> }
<mask>
<mask> // update
<mask> c.IP = "1.1.1.2"
<mask> c.Name = "client1"
<mask> if clients.Update("client1", c) != nil {
<mask> t.Fatalf("Update")
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove assert.True(t, !(clients.Exists("1.1.1.1", ClientSourceHostsFile) || !clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !clients.Exists("1.1.1.1", ClientSourceHostsFile))
assert.True(t, clients.Exists("1.1.1.2", ClientSourceHostsFile))
// update - rename
c.IDs = []string{"1.1.1.2"}
c.Name = "client1-renamed"
c.UseOwnSettings = true
assert.True(t, clients.Update("client1", c) == nil)
c = Client{}
c, b = clients.Find("1.1.1.2")
assert.True(t, b && c.Name == "client1-renamed" && c.IDs[0] == "1.1.1.2" && c.UseOwnSettings) </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
assert.True(t, !clients.Exists("1.1.1.1", ClientSourceHostsFile))
assert.True(t, clients.Exists("1.1.1.2", ClientSourceHostsFile))
// update - rename
c.IDs = []string{"1.1.1.2"}
c.Name = "client1-renamed"
c.UseOwnSettings = true
assert.True(t, clients.Update("client1", c) == nil)
c = Client{}
c, b = clients.Find("1.1.1.2")
assert.True(t, b && c.Name == "client1-renamed" && c.IDs[0] == "1.1.1.2" && c.UseOwnSettings) | <mask> t.Fatalf("Update")
<mask> }
<mask>
<mask> // get after update
<mask> assert.True(t, !(clients.Exists("1.1.1.1", ClientSourceHostsFile) || !clients.Exists("1.1.1.2", ClientSourceHostsFile)))
<mask>
<mask> // failed remove - no such name
<mask> if clients.Del("client3") {
<mask> t.Fatalf("Del - no such name")
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove assert.True(t, !(!clients.Del("client1") || clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !(!clients.Del("client1-renamed") || clients.Exists("1.1.1.2", ClientSourceHostsFile))) </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} </s> remove c.IP = "2.2.2.2"
</s> add c.IDs = []string{"2.2.2.2"} </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
assert.True(t, !(!clients.Del("client1-renamed") || clients.Exists("1.1.1.2", ClientSourceHostsFile))) | <mask> t.Fatalf("Del - no such name")
<mask> }
<mask>
<mask> // remove
<mask> assert.True(t, !(!clients.Del("client1") || clients.Exists("1.1.1.2", ClientSourceHostsFile)))
<mask>
<mask> // add host client
<mask> b, e = clients.AddHost("1.1.1.1", "host", ClientSourceARP)
<mask> if !b || e != nil {
<mask> t.Fatalf("clientAddHost")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove assert.True(t, !(clients.Exists("1.1.1.1", ClientSourceHostsFile) || !clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !clients.Exists("1.1.1.1", ClientSourceHostsFile))
assert.True(t, clients.Exists("1.1.1.2", ClientSourceHostsFile))
// update - rename
c.IDs = []string{"1.1.1.2"}
c.Name = "client1-renamed"
c.UseOwnSettings = true
assert.True(t, clients.Update("client1", c) == nil)
c = Client{}
c, b = clients.Find("1.1.1.2")
assert.True(t, b && c.Name == "client1-renamed" && c.IDs[0] == "1.1.1.2" && c.UseOwnSettings) </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"} | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
clients.Init(nil) | <mask>
<mask> func TestClientsWhois(t *testing.T) {
<mask> var c Client
<mask> clients := clientsContainer{}
<mask> clients.Init()
<mask>
<mask> whois := [][]string{{"orgname", "orgname-val"}, {"country", "country-val"}}
<mask> // set whois info on new client
<mask> clients.SetWhoisInfo("1.1.1.255", whois)
<mask> assert.True(t, clients.ipHost["1.1.1.255"].WhoisInfo[0][1] == "orgname-val")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "1.1.1.2",
</s> add IDs: []string{"1.1.1.2"}, </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove assert.True(t, clients.ipIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val")
</s> add assert.True(t, clients.idIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val") </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
IDs: []string{"1.1.1.2"}, | <mask> assert.True(t, clients.ipHost["1.1.1.1"].WhoisInfo[0][1] == "orgname-val")
<mask>
<mask> // set whois info on existing client
<mask> c = Client{
<mask> IP: "1.1.1.2",
<mask> Name: "client1",
<mask> }
<mask> _, _ = clients.Add(c)
<mask> clients.SetWhoisInfo("1.1.1.2", whois)
<mask> assert.True(t, clients.ipIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val")
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove assert.True(t, clients.ipIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val")
</s> add assert.True(t, clients.idIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val") </s> remove clients.Init()
</s> add clients.Init(nil) </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
assert.True(t, clients.idIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val") | <mask> Name: "client1",
<mask> }
<mask> _, _ = clients.Add(c)
<mask> clients.SetWhoisInfo("1.1.1.2", whois)
<mask> assert.True(t, clients.ipIndex["1.1.1.2"].WhoisInfo[0][1] == "orgname-val")
<mask> _ = clients.Del("client1")
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove IP: "1.1.1.2",
</s> add IDs: []string{"1.1.1.2"}, </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"}, </s> remove IP: "1.1.1.1",
</s> add IDs: []string{"1.1.1.1", "aa:aa:aa:aa:aa:aa"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"}, | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/clients_test.go |
<mask> LogFile string `yaml:"log_file"` // Path to the log file. If empty, write to stdout. If "syslog", writes to syslog
<mask> Verbose bool `yaml:"verbose"` // If true, verbose logging is enabled
<mask> }
<mask>
<mask> type clientObject struct {
<mask> Name string `yaml:"name"`
<mask> IP string `yaml:"ip"`
<mask> MAC string `yaml:"mac"`
<mask> UseGlobalSettings bool `yaml:"use_global_settings"`
<mask> FilteringEnabled bool `yaml:"filtering_enabled"`
<mask> ParentalEnabled bool `yaml:"parental_enabled"`
<mask> SafeSearchEnabled bool `yaml:"safebrowsing_enabled"`
<mask> SafeBrowsingEnabled bool `yaml:"safesearch_enabled"`
<mask>
<mask> UseGlobalBlockedServices bool `yaml:"use_global_blocked_services"`
<mask> BlockedServices []string `yaml:"blocked_services"`
<mask> }
<mask>
<mask> type HTTPSServer struct {
<mask> server *http.Server
<mask> cond *sync.Cond // reacts to config.TLS.Enabled, PortHTTPS, CertificateChain and PrivateKey
<mask> sync.Mutex // protects config.TLS
<mask> shutdown bool // if TRUE, don't restart the server
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove type clientJSON struct {
IP string `json:"ip"`
MAC string `json:"mac"`
Name string `json:"name"`
UseGlobalSettings bool `json:"use_global_settings"`
FilteringEnabled bool `json:"filtering_enabled"`
ParentalEnabled bool `json:"parental_enabled"`
SafeSearchEnabled bool `json:"safebrowsing_enabled"`
SafeBrowsingEnabled bool `json:"safesearch_enabled"`
WhoisInfo map[string]interface{} `json:"whois_info"`
UseGlobalBlockedServices bool `json:"use_global_blocked_services"`
BlockedServices []string `json:"blocked_services"`
}
</s> add </s> remove IP string
MAC string
</s> add IDs []string </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove log.Tracef("'%s': '%s' | '%s' -> [%d]", c.Name, c.IP, c.MAC, len(clients.list))
</s> add log.Tracef("'%s': ID:%v [%d]", c.Name, c.IDs, len(clients.list)) </s> remove ipIndex map[string]*Client // IP -> client
</s> add idIndex map[string]*Client // IP -> client | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/config.go |
|
<mask> if !checkFiltersUpdateIntervalHours(config.DNS.FiltersUpdateIntervalHours) {
<mask> config.DNS.FiltersUpdateIntervalHours = 24
<mask> }
<mask>
<mask> for _, cy := range config.Clients {
<mask> cli := Client{
<mask> Name: cy.Name,
<mask> IP: cy.IP,
<mask> MAC: cy.MAC,
<mask> UseOwnSettings: !cy.UseGlobalSettings,
<mask> FilteringEnabled: cy.FilteringEnabled,
<mask> ParentalEnabled: cy.ParentalEnabled,
<mask> SafeSearchEnabled: cy.SafeSearchEnabled,
<mask> SafeBrowsingEnabled: cy.SafeBrowsingEnabled,
<mask>
<mask> UseOwnBlockedServices: !cy.UseGlobalBlockedServices,
<mask> BlockedServices: cy.BlockedServices,
<mask> }
<mask> _, err = config.clients.Add(cli)
<mask> if err != nil {
<mask> log.Tracef("clientAdd: %s", err)
<mask> }
<mask> }
<mask> config.Clients = nil
<mask>
<mask> status := tlsConfigStatus{}
<mask> if !tlsLoadConfig(&config.TLS, &status) {
<mask> log.Error("%s", status.WarningValidation)
<mask> return err
<mask> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove clientsList := config.clients.GetList()
for _, cli := range clientsList {
ip := cli.IP
if len(cli.MAC) != 0 {
ip = ""
}
cy := clientObject{
Name: cli.Name,
IP: ip,
MAC: cli.MAC,
UseGlobalSettings: !cli.UseOwnSettings,
FilteringEnabled: cli.FilteringEnabled,
ParentalEnabled: cli.ParentalEnabled,
SafeSearchEnabled: cli.SafeSearchEnabled,
SafeBrowsingEnabled: cli.SafeBrowsingEnabled,
UseGlobalBlockedServices: !cli.UseOwnBlockedServices,
BlockedServices: cli.BlockedServices,
}
config.Clients = append(config.Clients, cy)
}
</s> add config.clients.WriteDiskConfig(&config.Clients) </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/config.go |
|
config.clients.WriteDiskConfig(&config.Clients) | <mask> func (c *configuration) write() error {
<mask> c.Lock()
<mask> defer c.Unlock()
<mask>
<mask> clientsList := config.clients.GetList()
<mask> for _, cli := range clientsList {
<mask> ip := cli.IP
<mask> if len(cli.MAC) != 0 {
<mask> ip = ""
<mask> }
<mask> cy := clientObject{
<mask> Name: cli.Name,
<mask> IP: ip,
<mask> MAC: cli.MAC,
<mask> UseGlobalSettings: !cli.UseOwnSettings,
<mask> FilteringEnabled: cli.FilteringEnabled,
<mask> ParentalEnabled: cli.ParentalEnabled,
<mask> SafeSearchEnabled: cli.SafeSearchEnabled,
<mask> SafeBrowsingEnabled: cli.SafeBrowsingEnabled,
<mask>
<mask> UseGlobalBlockedServices: !cli.UseOwnBlockedServices,
<mask> BlockedServices: cli.BlockedServices,
<mask> }
<mask> config.Clients = append(config.Clients, cy)
<mask> }
<mask>
<mask> if config.auth != nil {
<mask> config.Users = config.auth.GetUsers()
<mask> }
<mask>
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove for _, cy := range config.Clients {
cli := Client{
Name: cy.Name,
IP: cy.IP,
MAC: cy.MAC,
UseOwnSettings: !cy.UseGlobalSettings,
FilteringEnabled: cy.FilteringEnabled,
ParentalEnabled: cy.ParentalEnabled,
SafeSearchEnabled: cy.SafeSearchEnabled,
SafeBrowsingEnabled: cy.SafeBrowsingEnabled,
UseOwnBlockedServices: !cy.UseGlobalBlockedServices,
BlockedServices: cy.BlockedServices,
}
_, err = config.clients.Add(cli)
if err != nil {
log.Tracef("clientAdd: %s", err)
}
}
config.Clients = nil
</s> add </s> remove
type clientHostJSON struct {
IP string `json:"ip"`
Name string `json:"name"`
Source string `json:"source"`
WhoisInfo map[string]interface{} `json:"whois_info"`
}
type clientListJSON struct {
Clients []clientJSON `json:"clients"`
AutoClients []clientHostJSON `json:"auto_clients"`
}
// respond with information about configured clients
func handleGetClients(w http.ResponseWriter, r *http.Request) {
data := clientListJSON{}
config.clients.lock.Lock()
for _, c := range config.clients.list {
cj := clientJSON{
IP: c.IP,
MAC: c.MAC,
Name: c.Name,
UseGlobalSettings: !c.UseOwnSettings,
FilteringEnabled: c.FilteringEnabled,
ParentalEnabled: c.ParentalEnabled,
SafeSearchEnabled: c.SafeSearchEnabled,
SafeBrowsingEnabled: c.SafeBrowsingEnabled,
UseGlobalBlockedServices: !c.UseOwnBlockedServices,
BlockedServices: c.BlockedServices,
}
if len(c.MAC) != 0 {
hwAddr, _ := net.ParseMAC(c.MAC)
ipAddr := config.dhcpServer.FindIPbyMAC(hwAddr)
if ipAddr != nil {
cj.IP = ipAddr.String()
}
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range c.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.Clients = append(data.Clients, cj)
}
for ip, ch := range config.clients.ipHost {
cj := clientHostJSON{
IP: ip,
Name: ch.Host,
}
cj.Source = "etc/hosts"
switch ch.Source {
case ClientSourceDHCP:
cj.Source = "DHCP"
case ClientSourceRDNS:
cj.Source = "rDNS"
case ClientSourceARP:
cj.Source = "ARP"
case ClientSourceWHOIS:
cj.Source = "WHOIS"
}
cj.WhoisInfo = make(map[string]interface{})
for _, wi := range ch.WhoisInfo {
cj.WhoisInfo[wi[0]] = wi[1]
}
data.AutoClients = append(data.AutoClients, cj)
}
config.clients.lock.Unlock()
w.Header().Set("Content-Type", "application/json")
e := json.NewEncoder(w).Encode(data)
if e != nil {
httpError(w, http.StatusInternalServerError, "Failed to encode to json: %v", e)
return
}
}
// Convert JSON object to Client object
func jsonToClient(cj clientJSON) (*Client, error) {
c := Client{
IP: cj.IP,
MAC: cj.MAC,
Name: cj.Name,
UseOwnSettings: !cj.UseGlobalSettings,
FilteringEnabled: cj.FilteringEnabled,
ParentalEnabled: cj.ParentalEnabled,
SafeSearchEnabled: cj.SafeSearchEnabled,
SafeBrowsingEnabled: cj.SafeBrowsingEnabled,
UseOwnBlockedServices: !cj.UseGlobalBlockedServices,
BlockedServices: cj.BlockedServices,
}
return &c, nil
}
// Add a new client
func handleAddClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
c, err := jsonToClient(cj)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
ok, err := config.clients.Add(*c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
if !ok {
httpError(w, http.StatusBadRequest, "Client already exists")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// Remove client
func handleDelClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
cj := clientJSON{}
err = json.Unmarshal(body, &cj)
if err != nil || len(cj.Name) == 0 {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if !config.clients.Del(cj.Name) {
httpError(w, http.StatusBadRequest, "Client not found")
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
type updateJSON struct {
Name string `json:"name"`
Data clientJSON `json:"data"`
}
// Update client's properties
func handleUpdateClient(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
httpError(w, http.StatusBadRequest, "failed to read request body: %s", err)
return
}
var dj updateJSON
err = json.Unmarshal(body, &dj)
if err != nil {
httpError(w, http.StatusBadRequest, "JSON parse: %s", err)
return
}
if len(dj.Name) == 0 {
httpError(w, http.StatusBadRequest, "Invalid request")
return
}
c, err := jsonToClient(dj.Data)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
err = config.clients.Update(dj.Name, *c)
if err != nil {
httpError(w, http.StatusBadRequest, "%s", err)
return
}
_ = writeAllConfigsAndReloadDNS()
returnOK(w)
}
// RegisterClientsHandlers registers HTTP handlers
func RegisterClientsHandlers() {
httpRegister(http.MethodGet, "/control/clients", handleGetClients)
httpRegister(http.MethodPost, "/control/clients/add", handleAddClient)
httpRegister(http.MethodPost, "/control/clients/delete", handleDelClient)
httpRegister(http.MethodPost, "/control/clients/update", handleUpdateClient)
}
</s> add </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { | [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/config.go |
<mask> os.Exit(0)
<mask> }()
<mask>
<mask> initConfig()
<mask> config.clients.Init()
<mask> initServices()
<mask>
<mask> if !config.firstRun {
<mask> // Do the upgrade if necessary
<mask> err := upgradeConfig()
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove c.IP = ip.String()
} else {
_, err := net.ParseMAC(c.MAC)
if err != nil {
return fmt.Errorf("Invalid MAC: %s", err)
</s> add _, _, err := net.ParseCIDR(id)
if err == nil {
continue
}
_, err = net.ParseMAC(id)
if err == nil {
continue </s> remove ipAddr := config.dhcpServer.FindIPbyMAC(mac)
if ipAddr == nil {
</s> add if ipnet.Contains(ipAddr) {
return *c, true
}
}
}
macFound := config.dhcpServer.FindMACbyIP(ipAddr)
if macFound == nil {
return Client{}, false
}
for _, c = range clients.list {
for _, id := range c.IDs {
hwAddr, err := net.ParseMAC(id)
if err != nil { </s> remove return false, fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add return false, fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name) </s> remove if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id) </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/home.go |
|
config.clients.Init(config.Clients)
config.Clients = nil
| <mask> }
<mask>
<mask> if (runtime.GOOS == "linux" || runtime.GOOS == "darwin") &&
<mask> config.RlimitNoFile != 0 {
<mask> setRlimit(config.RlimitNoFile)
<mask> }
<mask>
<mask> // override bind host/port from the console
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> remove if (len(c.IP) == 0 && len(c.MAC) == 0) ||
(len(c.IP) != 0 && len(c.MAC) != 0) {
return fmt.Errorf("IP or MAC required")
</s> add if len(c.IDs) == 0 {
return fmt.Errorf("ID required") </s> remove if old.IP != c.IP && len(c.IP) != 0 {
c2, ok := clients.ipIndex[c.IP]
if ok {
return fmt.Errorf("Another client uses the same IP address: %s", c2.Name)
</s> add if !arraysEqual(old.IDs, c.IDs) {
for _, id := range c.IDs {
c2, ok := clients.idIndex[id]
if ok && c2 != old {
return fmt.Errorf("Another client uses the same ID (%s): %s", id, c2.Name)
}
}
// update ID index
for _, id := range old.IDs {
delete(clients.idIndex, id)
}
for _, id := range c.IDs {
clients.idIndex[id] = old </s> remove ch, ok := clients.ipHost[c.IP]
if ok {
c.WhoisInfo = ch.WhoisInfo
delete(clients.ipHost, c.IP)
</s> add // remove auto-clients with the same IP address, keeping WHOIS info if possible
for _, id := range c.IDs {
ch, ok := clients.ipHost[id]
if ok {
if len(c.WhoisInfo) == 0 {
c.WhoisInfo = ch.WhoisInfo
}
delete(clients.ipHost, id)
} </s> remove assert.True(t, !(clients.Exists("1.1.1.1", ClientSourceHostsFile) || !clients.Exists("1.1.1.2", ClientSourceHostsFile)))
</s> add assert.True(t, !clients.Exists("1.1.1.1", ClientSourceHostsFile))
assert.True(t, clients.Exists("1.1.1.2", ClientSourceHostsFile))
// update - rename
c.IDs = []string{"1.1.1.2"}
c.Name = "client1-renamed"
c.UseOwnSettings = true
assert.True(t, clients.Update("client1", c) == nil)
c = Client{}
c, b = clients.Find("1.1.1.2")
assert.True(t, b && c.Name == "client1-renamed" && c.IDs[0] == "1.1.1.2" && c.UseOwnSettings) </s> remove if len(c.IP) != 0 {
ip := net.ParseIP(c.IP)
if ip == nil {
return fmt.Errorf("Invalid IP")
</s> add for i, id := range c.IDs {
ip := net.ParseIP(id)
if ip != nil {
c.IDs[i] = ip.String() // normalize IP address
continue | [
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55 | home/home.go |
for _, ip := range Context.stats.TopClientsIP(topClientsNumber) { | <mask> Context.stats.Start()
<mask> Context.queryLog.Start()
<mask>
<mask> const topClientsNumber = 100 // the number of clients to get
<mask> for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
<mask> if ip == nil {
<mask> continue
<mask> }
<mask>
<mask> srcs := config.Clients.Sources
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove
func (s *StatsCtx) GetTopClientsIP(maxCount uint) []net.IP {
if !s.isEnabled() {
return nil
}
units, _ := s.loadUnits(atomic.LoadUint32(&s.limitHours))
if units == nil {
return nil
}
// top clients
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
d := []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
d = append(d, ip)
}
}
return d
}
</s> add </s> remove // Flush the current unit to DB and delete an old unit when a new hour is started
// If a unit must be flushed:
// . lock DB
// . atomically set a new empty unit as the current one and get the old unit
// This is important to do it inside DB lock, so the reader won't get inconsistent results.
// . write the unit to DB
// . remove the stale unit from DB
// . unlock DB
func (s *StatsCtx) periodicFlush() {
for ptr := s.ongoing(); ptr != nil; ptr = s.ongoing() {
id := s.unitIDGen()
// Access the unit's ID with atomic to avoid locking the whole unit.
if !s.isEnabled() || atomic.LoadUint32(&ptr.id) == id {
time.Sleep(time.Second)
continue
}
tx := beginTxn(s.database(), true)
nu := newUnit(id)
u := s.swapCurrent(nu)
udb := u.serialize()
if tx == nil {
continue
}
flushOK := flushUnitToDB(tx, u.id, udb)
delOK := s.deleteUnit(tx, id-atomic.LoadUint32(&s.limitHours))
if flushOK || delOK {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
</s> add func convertMapToSlice(m map[string]uint64, max int) (s []countPair) {
s = make([]countPair, 0, len(m))
for k, v := range m {
s = append(s, countPair{Name: k, Count: v}) </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove maxDomains = 100 // max number of top domains to store in file or return via Get()
maxClients = 100 // max number of top clients to store in file or return via Get()
</s> add // maxDomains is the max number of top domains to return.
maxDomains = 100
// maxClients is the max number of top clients to return.
maxClients = 100 | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/home/dns.go |
err := Context.stats.Close()
if err != nil {
log.Debug("closing stats: %s", err)
}
// TODO(e.burkov): Find out if it's safe. | <mask> Context.dnsFilter = nil
<mask> }
<mask>
<mask> if Context.stats != nil {
<mask> Context.stats.Close()
<mask> Context.stats = nil
<mask> }
<mask>
<mask> if Context.queryLog != nil {
<mask> Context.queryLog.Close()
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
s.clear()
}
log.Debug("stats: set limit: %d days", limitDays)
}
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
func (s *StatsCtx) Close() {
u := s.swapCurrent(nil)
db := s.database()
if tx := beginTxn(db, true); tx != nil {
udb := u.serialize()
if flushUnitToDB(tx, u.id, udb) {
s.commitTxn(tx)
} else {
_ = tx.Rollback()
}
}
if db != nil {
log.Tracef("db.Close...")
_ = db.Close()
log.Tracef("db.Close")
}
log.Debug("stats: closed")
}
// Reset counters and clear database
func (s *StatsCtx) clear() {
db := s.database()
tx := beginTxn(db, true)
if tx != nil {
_ = s.swapDatabase(nil)
_ = tx.Rollback()
// the active transactions can continue using database,
// but no new transactions will be opened
_ = db.Close()
log.Tracef("db.Close")
// all active transactions are now closed
}
u := newUnit(s.unitIDGen())
_ = s.swapCurrent(u)
err := os.Remove(s.filename)
if err != nil {
log.Error("os.Remove: %s", err)
}
_ = s.dbOpen()
log.Debug("stats: cleared")
}
func (s *StatsCtx) Update(e Entry) {
if !s.isEnabled() {
return
}
if e.Result == 0 ||
e.Result >= resultLast ||
e.Domain == "" ||
e.Client == "" {
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
u := s.ongoing()
if u == nil {
return
}
u.mu.Lock()
defer u.mu.Unlock()
u.nResult[e.Result]++
if e.Result == RNotFiltered {
u.domains[e.Domain]++
} else {
u.blockedDomains[e.Domain]++
}
u.clients[clientID]++
u.timeSum += uint64(e.Time)
u.nTotal++
}
func (s *StatsCtx) loadUnits(limit uint32) ([]*unitDB, uint32) {
tx := beginTxn(s.database(), false)
if tx == nil {
return nil, 0
}
cur := s.ongoing()
var curID uint32
if cur != nil {
curID = atomic.LoadUint32(&cur.id)
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units := []*unitDB{}
firstID := curID - limit + 1
for i := firstID; i != curID; i++ {
u := s.loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{}
u.NResult = make([]uint64, resultLast)
}
units = append(units, u)
}
_ = tx.Rollback()
if cur != nil {
units = append(units, cur.serialize())
}
if len(units) != int(limit) {
log.Fatalf("len(units) != limit: %d %d", len(units), limit)
}
return units, firstID
}
</s> add </s> remove // Entry is a statistics data entry.
type Entry struct {
// Clients is the client's primary ID.
//
// TODO(a.garipov): Make this a {net.IP, string} enum?
Client string
</s> add // httpRegister is used to set HTTP handlers.
httpRegister aghhttp.RegisterFunc
// configModified is called whenever the configuration is modified via web
// interface.
configModified func()
// filename is the name of database file.
filename string
}
var _ Interface = &StatsCtx{}
// New creates s from conf and properly initializes it. Don't use s before
// calling it's Start method.
func New(conf Config) (s *StatsCtx, err error) {
defer withRecovered(&err)
s = &StatsCtx{
currMu: &sync.RWMutex{},
dbMu: &sync.Mutex{},
filename: conf.Filename,
configModified: conf.ConfigModified,
httpRegister: conf.HTTPRegister,
}
if s.limitHours = conf.LimitDays * 24; !checkInterval(conf.LimitDays) {
s.limitHours = 24
}
if s.unitIDGen = newUnitID; conf.UnitID != nil {
s.unitIDGen = conf.UnitID
}
// TODO(e.burkov): Move the code below to the Start method.
err = s.openDB()
if err != nil {
return nil, fmt.Errorf("opening database: %w", err)
}
var udb *unitDB
id := s.unitIDGen()
tx, err := s.db.Begin(true)
if err != nil {
return nil, fmt.Errorf("stats: opening a transaction: %w", err)
}
deleted := deleteOldUnits(tx, id-s.limitHours-1)
udb = loadUnitFromDB(tx, id)
err = finishTxn(tx, deleted > 0)
if err != nil {
log.Error("stats: %s", err)
}
s.curr = newUnit(id)
s.curr.deserialize(udb)
log.Debug("stats: initialized")
return s, nil
}
// withRecovered turns the value recovered from panic if any into an error and
// combines it with the one pointed by orig. orig must be non-nil.
func withRecovered(orig *error) {
p := recover()
if p == nil {
return
}
var err error
switch p := p.(type) {
case error:
err = fmt.Errorf("panic: %w", p)
default:
err = fmt.Errorf("panic: recovered value of type %[1]T: %[1]v", p)
}
*orig = errors.WithDeferred(*orig, err)
}
// Start implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Start() {
s.initWeb()
go s.periodicFlush()
}
// Close implements the io.Closer interface for *StatsCtx.
func (s *StatsCtx) Close() (err error) {
defer func() { err = errors.Annotate(err, "stats: closing: %w") }()
db := s.swapDatabase(nil)
if db == nil {
return nil
}
defer func() {
cerr := db.Close()
if cerr == nil {
log.Debug("stats: database closed")
}
err = errors.WithDeferred(err, cerr)
}()
tx, err := db.Begin(true)
if err != nil {
return fmt.Errorf("opening transaction: %w", err)
}
defer func() { err = errors.WithDeferred(err, finishTxn(tx, err == nil)) }()
s.currMu.RLock()
defer s.currMu.RUnlock()
udb := s.curr.serialize()
return udb.flushUnitToDB(tx, s.curr.id)
}
// Update implements the Interface interface for *StatsCtx.
func (s *StatsCtx) Update(e Entry) {
if atomic.LoadUint32(&s.limitHours) == 0 {
return
}
if e.Result == 0 || e.Result >= resultLast || e.Domain == "" || e.Client == "" {
log.Debug("stats: malformed entry")
return
}
s.currMu.Lock()
defer s.currMu.Unlock()
if s.curr == nil {
log.Error("stats: current unit is nil")
return
}
clientID := e.Client
if ip := net.ParseIP(clientID); ip != nil {
clientID = ip.String()
}
s.curr.add(e.Result, e.Domain, clientID, uint64(e.Time))
}
// WriteDiskConfig implements the Interface interface for *StatsCtx.
func (s *StatsCtx) WriteDiskConfig(dc *DiskConfig) {
dc.Interval = atomic.LoadUint32(&s.limitHours) / 24
}
// TopClientsIP implements the Interface interface for *StatsCtx.
func (s *StatsCtx) TopClientsIP(maxCount uint) (ips []net.IP) {
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 {
return nil
}
units, _ := s.loadUnits(limit)
if units == nil {
return nil
}
// Collect data for all the clients to sort and crop it afterwards.
m := map[string]uint64{}
for _, u := range units {
for _, it := range u.Clients {
m[it.Name] += it.Count
}
}
a := convertMapToSlice(m, int(maxCount))
ips = []net.IP{}
for _, it := range a {
ip := net.ParseIP(it.Name)
if ip != nil {
ips = append(ips, ip)
}
}
return ips
}
// database returns the database if it's opened. It's safe for concurrent use.
func (s *StatsCtx) database() (db *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
return s.db
}
// swapDatabase swaps the database with another one and returns it. It's safe
// for concurrent use.
func (s *StatsCtx) swapDatabase(with *bbolt.DB) (old *bbolt.DB) {
s.dbMu.Lock()
defer s.dbMu.Unlock()
old, s.db = s.db, with
return old
}
// deleteOldUnits walks the buckets available to tx and deletes old units. It
// returns the number of deletions performed.
func deleteOldUnits(tx *bbolt.Tx, firstID uint32) (deleted int) {
log.Debug("stats: deleting old units until id %d", firstID)
// TODO(a.garipov): See if this is actually necessary. Looks like a rather
// bizarre solution.
const errStop errors.Error = "stop iteration"
walk := func(name []byte, _ *bbolt.Bucket) (err error) {
nameID, ok := unitNameToID(name)
if ok && nameID >= firstID {
return errStop
}
err = tx.DeleteBucket(name)
if err != nil {
log.Debug("stats: deleting bucket: %s", err)
return nil
}
log.Debug("stats: deleted unit %d (name %x)", nameID, name)
deleted++
return nil
}
err := tx.ForEach(walk)
if err != nil && !errors.Is(err, errStop) {
log.Debug("stats: deleting units: %s", err)
}
return deleted
}
// openDB returns an error if the database can't be opened from the specified
// file. It's safe for concurrent use.
func (s *StatsCtx) openDB() (err error) {
log.Debug("stats: opening database")
var db *bbolt.DB
db, err = bbolt.Open(s.filename, 0o644, nil)
if err != nil {
if err.Error() == "invalid argument" {
log.Error("AdGuard Home cannot be initialized due to an incompatible file system.\nPlease read the explanation here: https://github.com/AdguardTeam/AdGuardHome/wiki/Getting-Started#limitations")
}
return err
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: database opened")
s.dbMu.Lock()
defer s.dbMu.Unlock()
s.db = db
return nil
}
func (s *StatsCtx) flush() (cont bool, sleepFor time.Duration) {
id := s.unitIDGen()
s.currMu.Lock()
defer s.currMu.Unlock()
ptr := s.curr
if ptr == nil {
return false, 0
}
limit := atomic.LoadUint32(&s.limitHours)
if limit == 0 || ptr.id == id {
return true, time.Second
}
db := s.database()
if db == nil {
return true, 0
}
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return true, 0
}
s.curr = newUnit(id)
isCommitable := true
ferr := ptr.serialize().flushUnitToDB(tx, ptr.id)
if ferr != nil {
log.Error("stats: flushing unit: %s", ferr)
isCommitable = false
}
derr := tx.DeleteBucket(idToUnitName(id - limit))
if derr != nil {
log.Error("stats: deleting unit: %s", derr)
if !errors.Is(derr, bbolt.ErrBucketNotFound) {
isCommitable = false
}
}
err = finishTxn(tx, isCommitable)
if err != nil {
log.Error("stats: %s", err)
}
return true, 0
}
// periodicFlush checks and flushes the unit to the database if the freshly
// generated unit ID differs from the current's ID. Flushing process includes:
// - swapping the current unit with the new empty one;
// - writing the current unit to the database;
// - removing the stale unit from the database.
func (s *StatsCtx) periodicFlush() {
for cont, sleepFor := true, time.Duration(0); cont; time.Sleep(sleepFor) {
cont, sleepFor = s.flush()
}
log.Debug("periodic flushing finished")
}
func (s *StatsCtx) setLimit(limitDays int) {
atomic.StoreUint32(&s.limitHours, uint32(24*limitDays))
if limitDays == 0 {
if err := s.clear(); err != nil {
log.Error("stats: %s", err)
}
}
log.Debug("stats: set limit: %d days", limitDays)
}
// Reset counters and clear database
func (s *StatsCtx) clear() (err error) {
defer func() { err = errors.Annotate(err, "clearing: %w") }()
db := s.swapDatabase(nil)
if db != nil {
var tx *bbolt.Tx
tx, err = db.Begin(true)
if err != nil {
log.Error("stats: opening a transaction: %s", err)
} else if err = finishTxn(tx, false); err != nil {
// Don't wrap the error since it's informative enough as is.
return err
}
// Active transactions will continue using database, but new ones won't
// be created.
err = db.Close()
if err != nil {
return fmt.Errorf("closing database: %w", err)
}
// All active transactions are now closed.
log.Debug("stats: database closed")
}
err = os.Remove(s.filename)
if err != nil {
log.Error("stats: %s", err)
}
err = s.openDB()
if err != nil {
log.Error("stats: opening database: %s", err)
}
// Use defer to unlock the mutex as soon as possible.
defer log.Debug("stats: cleared")
s.currMu.Lock()
defer s.currMu.Unlock()
s.curr = newUnit(s.unitIDGen())
return nil
}
func (s *StatsCtx) loadUnits(limit uint32) (units []*unitDB, firstID uint32) {
db := s.database()
if db == nil {
return nil, 0
}
// Use writable transaction to ensure any ongoing writable transaction is
// taken into account.
tx, err := db.Begin(true)
if err != nil {
log.Error("stats: opening transaction: %s", err)
return nil, 0
}
s.currMu.RLock()
defer s.currMu.RUnlock()
cur := s.curr
var curID uint32
if cur != nil {
curID = cur.id
} else {
curID = s.unitIDGen()
}
// Per-hour units.
units = make([]*unitDB, 0, limit)
firstID = curID - limit + 1
for i := firstID; i != curID; i++ {
u := loadUnitFromDB(tx, i)
if u == nil {
u = &unitDB{NResult: make([]uint64, resultLast)}
}
units = append(units, u)
}
err = finishTxn(tx, false)
if err != nil {
log.Error("stats: %s", err)
} </s> remove // log.Tracef("Loading unit %d", id)
var buf bytes.Buffer
buf.Write(bkt.Get([]byte{0}))
dec := gob.NewDecoder(&buf)
udb := unitDB{}
err := dec.Decode(&udb)
if err != nil {
log.Error("gob Decode: %s", err)
return nil
}
return &udb
</s> add return nil </s> remove log.Error("gob.Encode: %s", err)
return false
</s> add return fmt.Errorf("encoding unit: %w", err) </s> remove return
}
</s> add | [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/home/dns.go |
"sync/atomic" | <mask>
<mask> import (
<mask> "encoding/json"
<mask> "net/http"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> )
<mask>
</s> Pull request: 4358 stats races
Merge in DNS/adguard-home from 4358-stats-races to master
Updates #4358
Squashed commit of the following:
commit 162d17b04d95adad21fb9b3c5a6fb64df2e037ec
Merge: 17732cfa d4c3a43b
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 14:04:20 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 17732cfa0f3b2589bf2c252697eee1d6b358a66c
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 17 13:53:42 2022 +0300
stats: imp docs, locking
commit 4ee090869af0fa2b777c12027c3b77d5acd6e4de
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:26:19 2022 +0300
stats: revert const
commit a7681a1b882cef04511fcd5d569f5abe2f955239
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 20:23:00 2022 +0300
stats: imp concurrency
commit a6c6c1a0572e4201cd24644fd3f86f51fc27f633
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 19:51:30 2022 +0300
stats: imp code, tests, docs
commit 954196b49f5ad91d91f445ff656e63c318e4124c
Merge: 281e00da 6e63757f
Author: Eugene Burkov <[email protected]>
Date: Tue Aug 16 13:07:32 2022 +0300
Merge branch 'master' into 4358-stats-races
commit 281e00daf781d045269584ce0158eed1d77918df
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:22:18 2022 +0300
stats: imp closing
commit ed036d9aa7e25498869edfb866b6e923538970eb
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 16:11:12 2022 +0300
stats: imp tests more
commit f848a12487ecd2afc8416e800510090cc1be7330
Author: Eugene Burkov <[email protected]>
Date: Fri Aug 12 13:54:19 2022 +0300
stats: imp tests, code
commit 60e11f042d51ec68850143129e61c701c5e4f3a4
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 16:36:07 2022 +0300
stats: fix test
commit 6d97f1db093b5ce0d37984ff96a9ef6f4e02dba1
Author: Eugene Burkov <[email protected]>
Date: Thu Aug 11 14:53:21 2022 +0300
stats: imp code, docs
commit 20c70c2847b0de6c7f9271a8d9a831175ed0c499
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 20:53:36 2022 +0300
stats: imp shared memory safety
commit 8b3945670a190bab070171e6b4976edab1e3e2a2
Author: Eugene Burkov <[email protected]>
Date: Wed Aug 10 17:22:55 2022 +0300
stats: imp code </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add </s> remove "sync"
"sync/atomic"
</s> add </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" | [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep",
"keep"
] | https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86 | internal/stats/http.go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.