docstring_tokens
stringlengths 18
16.9k
| code_tokens
stringlengths 75
1.81M
| html_url
stringlengths 74
116
| file_name
stringlengths 3
311
|
---|---|---|---|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> // prepareTLS - prepares TLS configuration for the DNS proxy
<mask> func (s *Server) prepareTLS(proxyConfig *proxy.Config) error {
<mask> if s.conf.TLSListenAddr != nil && len(s.conf.CertificateChainData) != 0 && len(s.conf.PrivateKeyData) != 0 {
<mask> proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
<mask> var err error
<mask> s.conf.cert, err = tls.X509KeyPair(s.conf.CertificateChainData, s.conf.PrivateKeyData)
<mask> if err != nil {
<mask> return errorx.Decorate(err, "Failed to parse TLS keypair")
<mask> }
</s> * SB/PC: use 4-character hash in request
* use hash prefix as the cache key
Squashed commit of the following:
commit d719a84ee9b9cf43aaab4f53d07451645ea836db
Merge: d9d6d443 97df1989
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:41:28 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit d9d6d44376c44959f2216b08e577d8e5c5f65bff
Merge: 0a8b2483 de92c852
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:23:14 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0a8b24839683683a9d327ecf57a7d182b3996b1d
Merge: 0255a24a 9b9902f0
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 20:21:22 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0255a24a191efd2e4ef23d6a00a7a9fed8831730
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:16:57 2020 +0300
- TestServerCustomClientUpstream(): fix
commit d2311902f887be9621a9d9312c73f899dd269440
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:07:12 2020 +0300
* SB/PC: hard-code Family server IP addresses to prevent from requesting them at runtime
commit ee340108f11f98d49a7af2a7e8a228c25ab1537a
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:05:57 2020 +0300
* dnsproxy v0.30.1
commit f5f53ba7116ad525204d00b80352202eee88b78c
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 14:53:23 2020 +0300
minor
commit fb4631e2cd570b0fd5ae26ec2b1890361275a5a8
Author: Simon Zolin <[email protected]>
Date: Mon Aug 10 20:07:27 2020 +0300
* SB/PC: implement new cache
commit f9f58461a6efbcfacd798f7640a4645cf1971cb2
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 19:31:05 2020 +0300
doc
commit ed69626a6c119ab1a3b187f5afbd4cef708c3159
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 18:25:57 2020 +0300
* SB/PC: use hostname prefix for cache
commit afa8040c8c0836c7e59e6fb9aaf1caccd132ea8f
Author: Simon Zolin <[email protected]>
Date: Fri Jul 31 11:19:49 2020 +0300
* SB/PC: use 4-character hash in request </s> remove err := s.Start()
if err != nil {
t.Fatalf("Failed to start server: %s", err)
}
</s> add </s> remove UDPListenAddr: s.conf.UDPListenAddr,
TCPListenAddr: s.conf.TCPListenAddr,
</s> add UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr}, </s> remove func TestSafeBrowsingHash(t *testing.T) {
q, hashes := hostnameToHashParam("1.2.3.4.5.6")
assert.Equal(t, "0132d0fa.b5413b4e.5fa067c1.e7f6c011.", q)
assert.Equal(t, 4, len(hashes))
}
</s> add </s> remove c.SafeBrowsingCacheSize = 1000
</s> add c.SafeBrowsingCacheSize = 10000
c.ParentalCacheSize = 10000 </s> remove c.ParentalCacheSize = 1000
</s> add </s> add assert.Nil(t, s.Start())
|
https://github.com/AdguardTeam/AdGuardHome/commit/705a9d909dfb37bb759ca1525af4d3748444f5f4
|
dnsforward/config.go
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<mask> }
<mask>
<mask> func TestServerCustomClientUpstream(t *testing.T) {
<mask> s := createTestServer(t)
<mask> err := s.Start()
<mask> if err != nil {
<mask> t.Fatalf("Failed to start server: %s", err)
<mask> }
<mask> s.conf.GetCustomUpstreamByClient = func(clientAddr string) *proxy.UpstreamConfig {
<mask> uc := &proxy.UpstreamConfig{}
<mask> u := &testUpstream{}
<mask> u.ipv4 = map[string][]net.IP{}
<mask> u.ipv4["host."] = []net.IP{net.ParseIP("192.168.0.1")}
</s> * SB/PC: use 4-character hash in request
* use hash prefix as the cache key
Squashed commit of the following:
commit d719a84ee9b9cf43aaab4f53d07451645ea836db
Merge: d9d6d443 97df1989
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:41:28 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit d9d6d44376c44959f2216b08e577d8e5c5f65bff
Merge: 0a8b2483 de92c852
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:23:14 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0a8b24839683683a9d327ecf57a7d182b3996b1d
Merge: 0255a24a 9b9902f0
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 20:21:22 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0255a24a191efd2e4ef23d6a00a7a9fed8831730
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:16:57 2020 +0300
- TestServerCustomClientUpstream(): fix
commit d2311902f887be9621a9d9312c73f899dd269440
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:07:12 2020 +0300
* SB/PC: hard-code Family server IP addresses to prevent from requesting them at runtime
commit ee340108f11f98d49a7af2a7e8a228c25ab1537a
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:05:57 2020 +0300
* dnsproxy v0.30.1
commit f5f53ba7116ad525204d00b80352202eee88b78c
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 14:53:23 2020 +0300
minor
commit fb4631e2cd570b0fd5ae26ec2b1890361275a5a8
Author: Simon Zolin <[email protected]>
Date: Mon Aug 10 20:07:27 2020 +0300
* SB/PC: implement new cache
commit f9f58461a6efbcfacd798f7640a4645cf1971cb2
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 19:31:05 2020 +0300
doc
commit ed69626a6c119ab1a3b187f5afbd4cef708c3159
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 18:25:57 2020 +0300
* SB/PC: use hostname prefix for cache
commit afa8040c8c0836c7e59e6fb9aaf1caccd132ea8f
Author: Simon Zolin <[email protected]>
Date: Fri Jul 31 11:19:49 2020 +0300
* SB/PC: use 4-character hash in request </s> remove proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
</s> add proxyConfig.TLSListenAddr = []*net.TCPAddr{s.conf.TLSListenAddr} </s> remove func TestSafeBrowsingHash(t *testing.T) {
q, hashes := hostnameToHashParam("1.2.3.4.5.6")
assert.Equal(t, "0132d0fa.b5413b4e.5fa067c1.e7f6c011.", q)
assert.Equal(t, 4, len(hashes))
}
</s> add </s> remove c.ParentalCacheSize = 1000
</s> add </s> add assert.Nil(t, s.Start())
</s> remove c.SafeBrowsingCacheSize = 1000
</s> add c.SafeBrowsingCacheSize = 10000
c.ParentalCacheSize = 10000 </s> remove UDPListenAddr: s.conf.UDPListenAddr,
TCPListenAddr: s.conf.TCPListenAddr,
</s> add UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr},
|
https://github.com/AdguardTeam/AdGuardHome/commit/705a9d909dfb37bb759ca1525af4d3748444f5f4
|
dnsforward/dnsforward_test.go
|
keep keep add keep keep keep keep
|
<mask> uc.Upstreams = append(uc.Upstreams, u)
<mask> return uc
<mask> }
<mask> addr := s.dnsProxy.Addr(proxy.ProtoUDP)
<mask>
<mask> // Send test request
<mask> req := dns.Msg{}
</s> * SB/PC: use 4-character hash in request
* use hash prefix as the cache key
Squashed commit of the following:
commit d719a84ee9b9cf43aaab4f53d07451645ea836db
Merge: d9d6d443 97df1989
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:41:28 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit d9d6d44376c44959f2216b08e577d8e5c5f65bff
Merge: 0a8b2483 de92c852
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:23:14 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0a8b24839683683a9d327ecf57a7d182b3996b1d
Merge: 0255a24a 9b9902f0
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 20:21:22 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0255a24a191efd2e4ef23d6a00a7a9fed8831730
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:16:57 2020 +0300
- TestServerCustomClientUpstream(): fix
commit d2311902f887be9621a9d9312c73f899dd269440
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:07:12 2020 +0300
* SB/PC: hard-code Family server IP addresses to prevent from requesting them at runtime
commit ee340108f11f98d49a7af2a7e8a228c25ab1537a
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:05:57 2020 +0300
* dnsproxy v0.30.1
commit f5f53ba7116ad525204d00b80352202eee88b78c
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 14:53:23 2020 +0300
minor
commit fb4631e2cd570b0fd5ae26ec2b1890361275a5a8
Author: Simon Zolin <[email protected]>
Date: Mon Aug 10 20:07:27 2020 +0300
* SB/PC: implement new cache
commit f9f58461a6efbcfacd798f7640a4645cf1971cb2
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 19:31:05 2020 +0300
doc
commit ed69626a6c119ab1a3b187f5afbd4cef708c3159
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 18:25:57 2020 +0300
* SB/PC: use hostname prefix for cache
commit afa8040c8c0836c7e59e6fb9aaf1caccd132ea8f
Author: Simon Zolin <[email protected]>
Date: Fri Jul 31 11:19:49 2020 +0300
* SB/PC: use 4-character hash in request </s> remove err := s.Start()
if err != nil {
t.Fatalf("Failed to start server: %s", err)
}
</s> add </s> remove proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
</s> add proxyConfig.TLSListenAddr = []*net.TCPAddr{s.conf.TLSListenAddr} </s> remove func TestSafeBrowsingHash(t *testing.T) {
q, hashes := hostnameToHashParam("1.2.3.4.5.6")
assert.Equal(t, "0132d0fa.b5413b4e.5fa067c1.e7f6c011.", q)
assert.Equal(t, 4, len(hashes))
}
</s> add </s> remove c.ParentalCacheSize = 1000
</s> add </s> remove c.SafeBrowsingCacheSize = 1000
</s> add c.SafeBrowsingCacheSize = 10000
c.ParentalCacheSize = 10000 </s> remove UDPListenAddr: s.conf.UDPListenAddr,
TCPListenAddr: s.conf.TCPListenAddr,
</s> add UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr},
|
https://github.com/AdguardTeam/AdGuardHome/commit/705a9d909dfb37bb759ca1525af4d3748444f5f4
|
dnsforward/dnsforward_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> go 1.14
<mask>
<mask> require (
<mask> github.com/AdguardTeam/dnsproxy v0.29.1
<mask> github.com/AdguardTeam/golibs v0.4.2
<mask> github.com/AdguardTeam/urlfilter v0.11.2
<mask> github.com/NYTimes/gziphandler v1.1.1
<mask> github.com/fsnotify/fsnotify v1.4.7
<mask> github.com/gobuffalo/packr v1.30.1
</s> * SB/PC: use 4-character hash in request
* use hash prefix as the cache key
Squashed commit of the following:
commit d719a84ee9b9cf43aaab4f53d07451645ea836db
Merge: d9d6d443 97df1989
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:41:28 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit d9d6d44376c44959f2216b08e577d8e5c5f65bff
Merge: 0a8b2483 de92c852
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:23:14 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0a8b24839683683a9d327ecf57a7d182b3996b1d
Merge: 0255a24a 9b9902f0
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 20:21:22 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0255a24a191efd2e4ef23d6a00a7a9fed8831730
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:16:57 2020 +0300
- TestServerCustomClientUpstream(): fix
commit d2311902f887be9621a9d9312c73f899dd269440
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:07:12 2020 +0300
* SB/PC: hard-code Family server IP addresses to prevent from requesting them at runtime
commit ee340108f11f98d49a7af2a7e8a228c25ab1537a
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:05:57 2020 +0300
* dnsproxy v0.30.1
commit f5f53ba7116ad525204d00b80352202eee88b78c
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 14:53:23 2020 +0300
minor
commit fb4631e2cd570b0fd5ae26ec2b1890361275a5a8
Author: Simon Zolin <[email protected]>
Date: Mon Aug 10 20:07:27 2020 +0300
* SB/PC: implement new cache
commit f9f58461a6efbcfacd798f7640a4645cf1971cb2
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 19:31:05 2020 +0300
doc
commit ed69626a6c119ab1a3b187f5afbd4cef708c3159
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 18:25:57 2020 +0300
* SB/PC: use hostname prefix for cache
commit afa8040c8c0836c7e59e6fb9aaf1caccd132ea8f
Author: Simon Zolin <[email protected]>
Date: Fri Jul 31 11:19:49 2020 +0300
* SB/PC: use 4-character hash in request </s> remove github.com/AdguardTeam/dnsproxy v0.29.1 h1:Stc+JLh67C9K38vbrH2920+3FnbXKkFzYQqRiu5auUo=
github.com/AdguardTeam/dnsproxy v0.29.1/go.mod h1:hOYFV9TW+pd5XKYz7KZf2FFD8SvSPqjyGTxUae86s58=
</s> add github.com/AdguardTeam/dnsproxy v0.30.1 h1:SnsL5kM/eFTrtLLdww1EePOhVDZTWzMkse+5tadGhvc=
github.com/AdguardTeam/dnsproxy v0.30.1/go.mod h1:hOYFV9TW+pd5XKYz7KZf2FFD8SvSPqjyGTxUae86s58= </s> add assert.Nil(t, s.Start())
</s> remove err := s.Start()
if err != nil {
t.Fatalf("Failed to start server: %s", err)
}
</s> add </s> remove proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
</s> add proxyConfig.TLSListenAddr = []*net.TCPAddr{s.conf.TLSListenAddr} </s> remove UDPListenAddr: s.conf.UDPListenAddr,
TCPListenAddr: s.conf.TCPListenAddr,
</s> add UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr}, </s> remove func TestSafeBrowsingHash(t *testing.T) {
q, hashes := hostnameToHashParam("1.2.3.4.5.6")
assert.Equal(t, "0132d0fa.b5413b4e.5fa067c1.e7f6c011.", q)
assert.Equal(t, 4, len(hashes))
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/705a9d909dfb37bb759ca1525af4d3748444f5f4
|
go.mod
|
replace replace keep keep keep keep keep
|
<mask> github.com/AdguardTeam/dnsproxy v0.29.1 h1:Stc+JLh67C9K38vbrH2920+3FnbXKkFzYQqRiu5auUo=
<mask> github.com/AdguardTeam/dnsproxy v0.29.1/go.mod h1:hOYFV9TW+pd5XKYz7KZf2FFD8SvSPqjyGTxUae86s58=
<mask> github.com/AdguardTeam/golibs v0.4.0/go.mod h1:skKsDKIBB7kkFflLJBpfGX+G8QFTx0WKUzB6TIgtUj4=
<mask> github.com/AdguardTeam/golibs v0.4.2 h1:7M28oTZFoFwNmp8eGPb3ImmYbxGaJLyQXeIFVHjME0o=
<mask> github.com/AdguardTeam/golibs v0.4.2/go.mod h1:skKsDKIBB7kkFflLJBpfGX+G8QFTx0WKUzB6TIgtUj4=
<mask> github.com/AdguardTeam/gomitmproxy v0.2.0/go.mod h1:Qdv0Mktnzer5zpdpi5rAwixNJzW2FN91LjKJCkVbYGU=
<mask> github.com/AdguardTeam/urlfilter v0.11.2 h1:gCrWGh63Yqw3z4yi9pgikfsbshIEyvAu/KYV3MvTBlc=
</s> * SB/PC: use 4-character hash in request
* use hash prefix as the cache key
Squashed commit of the following:
commit d719a84ee9b9cf43aaab4f53d07451645ea836db
Merge: d9d6d443 97df1989
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:41:28 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit d9d6d44376c44959f2216b08e577d8e5c5f65bff
Merge: 0a8b2483 de92c852
Author: Simon Zolin <[email protected]>
Date: Thu Aug 13 11:23:14 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0a8b24839683683a9d327ecf57a7d182b3996b1d
Merge: 0255a24a 9b9902f0
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 20:21:22 2020 +0300
Merge remote-tracking branch 'origin/master' into sbpc
commit 0255a24a191efd2e4ef23d6a00a7a9fed8831730
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:16:57 2020 +0300
- TestServerCustomClientUpstream(): fix
commit d2311902f887be9621a9d9312c73f899dd269440
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:07:12 2020 +0300
* SB/PC: hard-code Family server IP addresses to prevent from requesting them at runtime
commit ee340108f11f98d49a7af2a7e8a228c25ab1537a
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 17:05:57 2020 +0300
* dnsproxy v0.30.1
commit f5f53ba7116ad525204d00b80352202eee88b78c
Author: Simon Zolin <[email protected]>
Date: Wed Aug 12 14:53:23 2020 +0300
minor
commit fb4631e2cd570b0fd5ae26ec2b1890361275a5a8
Author: Simon Zolin <[email protected]>
Date: Mon Aug 10 20:07:27 2020 +0300
* SB/PC: implement new cache
commit f9f58461a6efbcfacd798f7640a4645cf1971cb2
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 19:31:05 2020 +0300
doc
commit ed69626a6c119ab1a3b187f5afbd4cef708c3159
Author: Simon Zolin <[email protected]>
Date: Fri Aug 7 18:25:57 2020 +0300
* SB/PC: use hostname prefix for cache
commit afa8040c8c0836c7e59e6fb9aaf1caccd132ea8f
Author: Simon Zolin <[email protected]>
Date: Fri Jul 31 11:19:49 2020 +0300
* SB/PC: use 4-character hash in request </s> remove github.com/AdguardTeam/dnsproxy v0.29.1
</s> add github.com/AdguardTeam/dnsproxy v0.30.1 </s> add assert.Nil(t, s.Start())
</s> remove err := s.Start()
if err != nil {
t.Fatalf("Failed to start server: %s", err)
}
</s> add </s> remove proxyConfig.TLSListenAddr = s.conf.TLSListenAddr
</s> add proxyConfig.TLSListenAddr = []*net.TCPAddr{s.conf.TLSListenAddr} </s> remove UDPListenAddr: s.conf.UDPListenAddr,
TCPListenAddr: s.conf.TCPListenAddr,
</s> add UDPListenAddr: []*net.UDPAddr{s.conf.UDPListenAddr},
TCPListenAddr: []*net.TCPAddr{s.conf.TCPListenAddr}, </s> remove func TestSafeBrowsingHash(t *testing.T) {
q, hashes := hostnameToHashParam("1.2.3.4.5.6")
assert.Equal(t, "0132d0fa.b5413b4e.5fa067c1.e7f6c011.", q)
assert.Equal(t, 4, len(hashes))
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/705a9d909dfb37bb759ca1525af4d3748444f5f4
|
go.sum
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> log.Fatalf("cannot initialize syslog: %s", err)
<mask> }
<mask> } else {
<mask> logFilePath := filepath.Join(config.ourWorkingDir, ls.LogFile)
<mask> file, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
<mask> if err != nil {
<mask> log.Fatalf("cannot create a log file: %s", err)
<mask> }
<mask> log.SetOutput(file)
<mask> }
</s> + app, config: add symlink support, allow to specify absolute path in log_file </s> remove configFile = filepath.Join(config.ourWorkingDir, config.ourConfigFilename)
</s> add configFile = filepath.Join(config.ourWorkingDir, configFile) </s> remove configFile := config.ourConfigFilename
</s> add configFile, err := filepath.EvalSymlinks(config.ourConfigFilename)
if err != nil {
if !os.IsNotExist(err) {
log.Error("unexpected error while config file path evaluation: %s", err)
}
configFile = config.ourConfigFilename
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c56f7a180e1113c289574e69dd148bc76db511
|
app.go
|
keep keep keep replace keep replace keep
|
<mask>
<mask> // getConfigFilename returns path to the current config file
<mask> func (c *configuration) getConfigFilename() string {
<mask> configFile := config.ourConfigFilename
<mask> if !filepath.IsAbs(configFile) {
<mask> configFile = filepath.Join(config.ourWorkingDir, config.ourConfigFilename)
<mask> }
</s> + app, config: add symlink support, allow to specify absolute path in log_file </s> remove file, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0755)
</s> add if filepath.IsAbs(ls.LogFile) {
logFilePath = ls.LogFile
}
file, err := os.OpenFile(logFilePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c56f7a180e1113c289574e69dd148bc76db511
|
config.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> }
<mask>
<mask> // Update filters we've just loaded right away, don't wait for periodic update timer
<mask> go func() {
<mask> checkFiltersUpdates(false)
<mask> // Save the updated config
<mask> err := writeConfig()
<mask> if err != nil {
<mask> log.Fatal(err)
<mask> }
</s> Restore Engrish function names to normal English. </s> remove updated := checkFiltersUpdates(force != "")
</s> add updated := refreshFiltersIfNeccessary(force != "") </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 func checkFiltersUpdates(force bool) int {
</s> add func refreshFiltersIfNeccessary(force bool) int { </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove runFiltersUpdatesTimer()
</s> add go periodicallyRefreshFilters()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246
|
app.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> }
<mask>
<mask> address := net.JoinHostPort(config.BindHost, strconv.Itoa(config.BindPort))
<mask>
<mask> runFiltersUpdatesTimer()
<mask>
<mask> http.Handle("/", optionalAuthHandler(http.FileServer(box)))
<mask> registerControlHandlers()
<mask>
<mask> err = startDNSServer()
</s> Restore Engrish function names to normal English. </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 func checkFiltersUpdates(force bool) int {
</s> add func refreshFiltersIfNeccessary(force bool) int { </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)
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246
|
app.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> return
<mask> }
<mask>
<mask> // kick off refresh of rules from new URLs
<mask> checkFiltersUpdates(false)
<mask> httpUpdateConfigReloadDNSReturnOK(w, r)
<mask> }
<mask>
<mask> func handleFilteringDisableURL(w http.ResponseWriter, r *http.Request) {
<mask> parameters, err := parseParametersFromBody(r.Body)
</s> Restore Engrish function names to normal English. </s> remove updated := checkFiltersUpdates(force != "")
</s> add updated := refreshFiltersIfNeccessary(force != "") </s> remove func checkFiltersUpdates(force bool) int {
</s> add func refreshFiltersIfNeccessary(force bool) int { </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 runFiltersUpdatesTimer()
</s> add go periodicallyRefreshFilters()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246
|
control.go
|
keep replace keep keep keep keep replace replace replace replace replace replace keep
|
<mask> force := r.URL.Query().Get("force")
<mask> updated := checkFiltersUpdates(force != "")
<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> }
</s> Restore Engrish function names to normal English. </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove func checkFiltersUpdates(force bool) int {
</s> add func refreshFiltersIfNeccessary(force bool) int { </s> remove checkFiltersUpdates(false)
</s> add refreshFiltersIfNeccessary(false) </s> remove runFiltersUpdatesTimer()
</s> add go periodicallyRefreshFilters()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246
|
control.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70c5afd6a5065ad827b038954dba1ade503a5246
|
control.go
|
keep add keep keep keep keep keep
|
<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 </s> remove require (
github.com/mdlayher/packet v1.0.0
golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
)
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
go.mod
|
keep add keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
go.mod
|
keep keep keep replace keep keep keep replace replace replace replace replace keep keep
|
<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
<mask> golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e
<mask> )
<mask>
<mask> require (
<mask> github.com/BurntSushi/toml v1.1.0 // 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> add golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e </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 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> add github.com/mdlayher/packet v1.0.0 </s> remove github.com/kisielk/errcheck v1.6.1
</s> add github.com/kisielk/errcheck v1.6.2
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
go.mod
|
keep keep keep keep replace keep
|
<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> add github.com/mdlayher/packet v1.0.0 </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= </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=
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
go.mod
|
keep keep keep keep replace replace keep keep keep keep keep
|
<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 </s> remove golang.org/x/sys v0.0.0-20220731174439-a90be440212d // indirect
</s> add golang.org/x/sys v0.0.0-20220804214406-8e32c043e418 // indirect
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
go.sum
|
keep keep add keep keep keep keep keep keep
|
<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> add "bytes" </s> add github.com/mdlayher/packet v1.0.0 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep replace keep replace replace replace replace replace replace replace keep keep
|
<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)
<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>
</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 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" {
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
|
<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 </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 == "" { </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace replace replace replace keep replace replace keep keep keep keep
|
<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)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %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 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 </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep replace keep keep keep keep keep keep keep keep replace
|
<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> }
<mask>
<mask> err = maybe.WriteFile(configFile, yamlText, 0o644)
<mask> if err != nil {
<mask> log.Error("Couldn't save YAML config: %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 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() </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace keep keep keep keep
|
<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() </s> remove err = maybe.WriteFile(confFile, body, 0o644)
</s> add err = maybe.WriteFile(confFile, config.fileData, 0o644)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/config.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </s> add "bytes" </s> add "bytes"
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/dns.go
|
keep keep replace replace replace keep keep keep replace replace replace replace replace keep keep keep keep
|
<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
<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)
</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 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 == configSyslog {
</s> add if ls.File == configSyslog {
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/home.go
|
keep keep keep replace keep keep keep keep keep keep keep keep replace keep keep keep keep
|
<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>
<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 == "" {
</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 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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/home.go
|
keep keep replace keep keep keep replace keep keep
|
<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
<mask> err := aghos.ConfigureSyslog(serviceName)
</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 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) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/home.go
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<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)
} </s> remove config.fileData = body
</s> add config.fileData = buf.Bytes()
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/home.go
|
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
|
<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 == "" { </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/home.go
|
keep add keep keep keep keep keep
|
<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> add "bytes" </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 </s> remove yaml "gopkg.in/yaml.v2"
</s> add yaml "gopkg.in/yaml.v3"
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/upgrade.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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) </s> remove ls.LogFile = configSyslog
</s> add ls.File = configSyslog
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/upgrade.go
|
keep keep keep keep replace keep keep keep keep replace keep
|
<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
<mask> confFile := config.getConfigFilename()
</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 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 return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/upgrade.go
|
keep replace keep replace keep keep
|
<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>
</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 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)
} </s> remove return err
}
</s> add buf := &bytes.Buffer{}
enc := yaml.NewEncoder(buf)
enc.SetIndent(2)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/upgrade.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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)
} </s> remove return err
</s> add err = maybe.WriteFile(configFile, buf.Bytes(), 0o644)
if err != nil {
return fmt.Errorf("writing config file: %w", err)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/home/upgrade_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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= </s> add "bytes"
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/tools/go.mod
|
keep keep keep keep replace keep keep
|
<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> add github.com/mdlayher/packet v1.0.0 </s> remove gopkg.in/yaml.v2 v2.4.0
</s> add gopkg.in/yaml.v3 v3.0.1 </s> add golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e </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=
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/tools/go.mod
|
keep keep keep keep replace replace keep keep keep keep keep
|
<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) </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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/tools/go.sum
|
keep keep keep keep replace replace keep keep keep keep keep
|
<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> add golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e </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, </s> remove log.Error("Couldn't save YAML config: %s", err)
</s> add return fmt.Errorf("generating config file: %w", err)
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/70f85fca210aee4d2f43f26bba9743a300d19e1c
|
internal/tools/go.sum
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add lease.Hostname = string(hostname) </s> remove hostname := req.Options.Get(dhcpv4.OptionHostName)
lease.Hostname = string(hostname)
</s> add </s> add } else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/dhcpd.go
|
keep keep keep keep replace replace keep keep keep keep keep
|
<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> add lease.Hostname = string(hostname) </s> add } else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/v4.go
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<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> add } else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) </s> add lease.Hostname = string(hostname) </s> remove LeaseChangedBlacklisted
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/v4.go
|
keep keep keep keep replace replace replace replace replace replace keep keep keep keep keep
|
<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> add } else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) </s> add lease.Hostname = string(hostname) </s> remove // s.conf.notify(LeaseChangedBlacklisted)
</s> add </s> remove LeaseChangedBlacklisted
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/v4.go
|
keep add keep keep keep keep keep
|
<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> add } else if len(lease.Hostname) != 0 {
o := &optFQDN{
name: string(lease.Hostname),
}
fqdn := dhcpv4.Option{
Code: dhcpv4.OptionFQDN,
Value: o,
}
resp.UpdateOption(fqdn) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/v4.go
|
keep keep keep add keep keep keep keep keep
|
<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> add lease.Hostname = string(hostname) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/719ef16b93e149d18558401aa87a7544b2b1cd31
|
dhcpd/v4.go
|
keep add keep keep keep keep keep keep
|
<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> add *old = c </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"} </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))
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
dhcpd/dhcpd.go
|
keep keep keep replace keep keep keep replace keep
|
<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 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> add config.clients.Init(config.Clients)
config.Clients = nil
</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 </s> add // update Name index
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace keep keep keep keep keep
|
<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 </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))
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
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
|
<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> add // 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
}
</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)) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep replace keep keep keep keep replace keep
|
<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)
<mask> clients.ipHost = make(map[string]*ClientHost)
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </s> add clients.addFromConfig(objects) </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip] </s> add *old = c </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 if len(c.MAC) != 0 {
mac, err := net.ParseMAC(c.MAC)
</s> add for _, id := range c.IDs {
_, ipnet, err := net.ParseCIDR(id)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep add keep keep keep keep
|
<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] </s> remove c.IP = "1.2.3.0"
</s> add c.IDs = []string{"1.2.3.0"}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, 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 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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep add keep keep keep keep
|
<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)) </s> add // 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
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, false
}
</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 { </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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep replace replace keep keep keep replace replace keep keep keep
|
<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 {
<mask> continue
<mask> }
<mask> if ip == ipAddr.String() {
</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 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 </s> add return fmt.Errorf("Invalid ID: %s", id)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, false
}
</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 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")
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep replace replace replace keep keep replace replace replace replace keep keep keep keep
|
<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 {
<mask> return fmt.Errorf("Invalid IP")
<mask> }
<mask> c.IP = ip.String()
<mask> } else {
<mask> _, err := net.ParseMAC(c.MAC)
</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 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> add config.clients.Init(config.Clients)
config.Clients = nil
</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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace replace replace replace keep keep keep keep keep
|
<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> add return fmt.Errorf("Invalid ID: %s", 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 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 && 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")
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep add keep keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace replace keep replace keep
|
<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> }
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </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 </s> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, false
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<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 </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))
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep add keep keep keep keep keep keep
|
<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)
} </s> add // update Name index </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]
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep replace replace keep keep replace
|
<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))
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </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> add // update Name index </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 // 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]
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep add keep keep keep keep keep
|
<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> add // update Name index </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] </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add *old = c </s> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, false
}
</s> add // update Name index </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)) </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip]
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<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] </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace replace replace replace replace replace replace replace replace keep keep keep keep keep
|
<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> add // update Name index </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] </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep add keep keep keep keep keep
|
<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)) </s> remove func (clients *clientsContainer) Init() {
</s> add func (clients *clientsContainer) Init(objects []clientObject) {
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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> add *old = c </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> add ipAddr := net.ParseIP(ip)
if ipAddr == nil {
return Client{}, 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 _, ok := clients.ipIndex[ip]
</s> add _, ok := clients.idIndex[ip]
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </s> remove c, ok := clients.ipIndex[ip]
</s> add c, ok := clients.idIndex[ip]
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
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
|
<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> add return fmt.Errorf("Invalid ID: %s", id) </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients.go
|
keep keep keep replace keep keep keep replace
|
<mask> var b bool
<mask> clients := clientsContainer{}
<mask>
<mask> clients.Init()
<mask>
<mask> // add
<mask> c = Client{
<mask> IP: "1.1.1.1",
</s> * clients: multiple IP, CIDR, MAC addresses
+ /clients/find
* clients: move code for config read/write
* clients: move HTTP handlers </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"}, </s> remove IP: "1.1.1.2",
</s> add IDs: []string{"1.1.1.2"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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) </s> remove IP: "1.1.1.2",
</s> add IDs: []string{"1.1.1.2"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"}, </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"} </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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))) </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"}, </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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"} </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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"}, </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"}, </s> remove c.IP = "1.1.1.2"
</s> add c.IDs = []string{"1.1.1.2"}
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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"} </s> remove IP: "1.2.3.5",
</s> add IDs: []string{"1.2.3.5"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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] </s> add *old = c </s> add return fmt.Errorf("Invalid ID: %s", id)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep replace keep keep keep keep replace
|
<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 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"}, </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/clients_test.go
|
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
|
<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 </s> remove clients.Init()
</s> add clients.Init(nil)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/config.go
|
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
|
<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) </s> add return fmt.Errorf("Invalid ID: %s", id)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/config.go
|
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
|
<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 { </s> remove IP: "2.2.2.2",
</s> add IDs: []string{"2.2.2.2"},
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/config.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/home.go
|
keep add keep keep keep keep keep keep
|
<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 </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)
|
https://github.com/AdguardTeam/AdGuardHome/commit/71ce0c6da9117440e55be3cb796781508a4a8a55
|
home/home.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/home/dns.go
|
keep keep keep keep replace keep keep keep keep keep
|
<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 </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
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/home/dns.go
|
keep keep keep add keep keep keep keep keep keep
|
<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> add "encoding/json" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/aghhttp"
</s> add </s> add "os"
"sync"
"sync/atomic"
"time" </s> remove "sync"
"sync/atomic"
</s> add </s> remove "os"
</s> add "net/http"
"net/http/httptest"
"path/filepath" </s> add "github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
"go.etcd.io/bbolt"
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep keep keep replace replace keep keep replace replace replace replace replace replace replace replace keep keep
|
<mask> // The key is either a client's address or a requested address.
<mask> type topAddrs = map[string]uint64
<mask>
<mask> // statsResponse is a response for getting statistics.
<mask> type statsResponse struct {
<mask> TimeUnits string `json:"time_units"`
<mask>
<mask> NumDNSQueries uint64 `json:"num_dns_queries"`
<mask> NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
<mask> NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
<mask> NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
<mask> NumReplacedParental uint64 `json:"num_replaced_parental"`
<mask>
<mask> AvgProcessingTime float64 `json:"avg_processing_time"`
<mask>
<mask> TopQueried []topAddrs `json:"top_queried_domains"`
<mask> TopClients []topAddrs `json:"top_clients"`
</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> add NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"` </s> remove // unitDB is the structure for deserializing statistics data into the database.
</s> add // unitDB is the structure for serializing statistics data into the database. </s> add //
// Must not be rewritten after creating to be accessed concurrently without
// using mu. </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint.
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep keep keep add keep keep keep keep
|
<mask>
<mask> BlockedFiltering []uint64 `json:"blocked_filtering"`
<mask> ReplacedSafebrowsing []uint64 `json:"replaced_safebrowsing"`
<mask> ReplacedParental []uint64 `json:"replaced_parental"`
<mask> }
<mask>
<mask> // handleStats handles requests to the GET /control/stats endpoint.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
</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 // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. </s> add start := time.Now()
resp, ok := s.getData(limit) </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours)
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep replace keep replace replace replace replace replace keep keep keep keep
|
<mask>
<mask> // handleStats is a handler for getting statistics.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
<mask> start := time.Now()
<mask>
<mask> var resp statsResponse
<mask> var ok bool
<mask> resp, ok = s.getData()
<mask>
<mask> log.Debug("stats: prepared data in %v", time.Since(start))
<mask>
<mask> if !ok {
</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> add start := time.Now()
resp, ok := s.getData(limit) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> add NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"` </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep keep keep add keep keep keep keep keep
|
<mask> // handleStats handles requests to the GET /control/stats endpoint.
<mask> func (s *StatsCtx) handleStats(w http.ResponseWriter, r *http.Request) {
<mask> limit := atomic.LoadUint32(&s.limitHours)
<mask>
<mask> log.Debug("stats: prepared data in %v", time.Since(start))
<mask>
<mask> if !ok {
<mask> // Don't bring the message to the lower case since it's a part of UI
<mask> // text for the moment.
</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 start := time.Now()
var resp statsResponse
var ok bool
resp, ok = s.getData()
</s> add limit := atomic.LoadUint32(&s.limitHours) </s> remove // handleStats is a handler for getting statistics.
</s> add // handleStats handles requests to the GET /control/stats endpoint. </s> add NumDNSQueries uint64 `json:"num_dns_queries"`
NumBlockedFiltering uint64 `json:"num_blocked_filtering"`
NumReplacedSafebrowsing uint64 `json:"num_replaced_safebrowsing"`
NumReplacedSafesearch uint64 `json:"num_replaced_safesearch"`
NumReplacedParental uint64 `json:"num_replaced_parental"`
AvgProcessingTime float64 `json:"avg_processing_time"` </s> remove // Get configuration
</s> add // handleStatsInfo handles requests to the GET /control/stats_info endpoint. </s> remove // Reset data
</s> add // handleStatsReset handles requests to the POST /control/stats_reset endpoint. </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint.
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep keep replace replace keep keep keep replace keep keep keep
|
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
<mask>
<mask> return
<mask> }
<mask> }
<mask>
<mask> type config struct {
<mask> IntervalDays uint32 `json:"interval"`
<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 return
}
</s> add </s> remove aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove _, err = w.Write(data)
</s> add err := json.NewEncoder(w).Encode(resp)
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep replace keep replace replace replace replace replace replace keep keep
|
<mask>
<mask> // Get configuration
<mask> func (s *StatsCtx) handleStatsInfo(w http.ResponseWriter, r *http.Request) {
<mask> resp := config{}
<mask> resp.IntervalDays = s.limitHours / 24
<mask>
<mask> data, err := json.Marshal(resp)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
<mask>
<mask> return
</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 aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove return
}
</s> add </s> remove reqData := config{}
</s> add reqData := configResp{} </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
}
|
https://github.com/AdguardTeam/AdGuardHome/commit/72098d22551313c3a76b7dcf36594bc09188db86
|
internal/stats/http.go
|
keep replace replace keep replace keep keep keep keep
|
<mask>
<mask> return
<mask> }
<mask> w.Header().Set("Content-Type", "application/json")
<mask> _, err = w.Write(data)
<mask> if err != nil {
<mask> aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
<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 aghhttp.Error(r, w, http.StatusInternalServerError, "http write: %s", err)
</s> add aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err) </s> remove resp := config{}
resp.IntervalDays = s.limitHours / 24
data, err := json.Marshal(resp)
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "json encode: %s", err)
</s> add resp := configResp{IntervalDays: atomic.LoadUint32(&s.limitHours) / 24} </s> remove // Set configuration
</s> add // handleStatsConfig handles requests to the POST /control/stats_config
// endpoint. </s> remove
return
</s> add </s> remove s.clear()
</s> add err := s.clear()
if err != nil {
aghhttp.Error(r, w, http.StatusInternalServerError, "stats: %s", err)
}
|
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.