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> "strconv"
<mask> "strings"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/miekg/dns"
<mask> )
<mask>
<mask> // TODO(a.garipov): Use a proper structured approach here.
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/json.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> return jsonEntry
<mask> }
<mask>
<mask> func resultRulesToJSONRules(rules []*dnsfilter.ResultRule) (jsonRules []jobject) {
<mask> jsonRules = make([]jobject, len(rules))
<mask> for i, r := range rules {
<mask> jsonRules[i] = jobject{
<mask> "filter_list_id": r.FilterListID,
<mask> "text": r.Text,
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove filters = append(filters, dnsfilter.Filter{
</s> add filters = append(filters, filtering.Filter{ </s> remove ent.Result.Reason = dnsfilter.Reason(i)
</s> add ent.Result.Reason = filtering.Reason(i) </s> remove var whiteFilters []dnsfilter.Filter
filters := []dnsfilter.Filter{{
</s> add var whiteFilters []filtering.Filter
filters := []filtering.Filter{{ </s> remove if !dnsfilter.BlockedSvcKnown(s) {
</s> add if !filtering.BlockedSvcKnown(s) { </s> remove filters := []dnsfilter.Filter{{
</s> add filters := []filtering.Filter{{ </s> remove } else if res.Reason == dnsfilter.RewrittenAutoHosts && len(res.ReverseHosts) != 0 {
</s> add } else if res.Reason == filtering.RewrittenAutoHosts && len(res.ReverseHosts) != 0 {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/json.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> "strings"
<mask> "sync"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/miekg/dns"
<mask> )
<mask>
<mask> const (
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> Answer []byte `json:",omitempty"` // sometimes empty answers happen like binerdunt.top or rev2.globalrootservers.net
<mask> OrigAnswer []byte `json:",omitempty"`
<mask>
<mask> Result dnsfilter.Result
<mask> Elapsed time.Duration
<mask> Upstream string `json:",omitempty"` // if empty, means it was cached
<mask> }
<mask>
<mask> func (l *queryLog) Start() {
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove Result *dnsfilter.Result // Filtering result (optional)
</s> add Result *filtering.Result // Filtering result (optional) </s> remove ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of dnsfilter features
</s> add ProtectionEnabled bool `yaml:"protection_enabled"` // whether or not use any of filtering features </s> remove result *dnsfilter.Result
</s> add result *filtering.Result </s> remove s = createTestServer(t, &dnsfilter.Config{}, ServerConfig{
</s> add s = createTestServer(t, &filtering.Config{}, ServerConfig{ </s> remove if result.Reason == dnsfilter.FilteredSafeSearch &&
</s> add if result.Reason == filtering.FilteredSafeSearch && </s> remove // If the query was filtered by "Safe search", dnsfilter also must return
</s> add // If the query was filtered by "Safe search", filtering also must return
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> return
<mask> }
<mask>
<mask> if params.Result == nil {
<mask> params.Result = &dnsfilter.Result{}
<mask> }
<mask>
<mask> now := time.Now()
<mask> entry := logEntry{
<mask> IP: l.getClientIP(params.ClientIP),
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove ctx.result = &dnsfilter.Result{}
</s> add ctx.result = &filtering.Result{} </s> remove ent.Result.DNSRewriteResult = &dnsfilter.DNSRewriteResult{}
</s> add ent.Result.DNSRewriteResult = &filtering.DNSRewriteResult{} </s> remove ent.Result.DNSRewriteResult = &dnsfilter.DNSRewriteResult{}
</s> add ent.Result.DNSRewriteResult = &filtering.DNSRewriteResult{} </s> remove } else if res.Reason == dnsfilter.RewrittenRule {
</s> add } else if res.Reason == filtering.RewrittenRule { </s> remove ent.Result.Reason = dnsfilter.Reason(i)
</s> add ent.Result.Reason = filtering.Reason(i) </s> remove c := dnsfilter.Config{}
</s> add c := filtering.Config{}
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> "testing"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/aghtest"
<mask> "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
<mask> "github.com/AdguardTeam/dnsproxy/proxyutil"
<mask> "github.com/miekg/dns"
<mask> "github.com/stretchr/testify/assert"
<mask> "github.com/stretchr/testify/require"
<mask> )
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog_test.go
|
keep replace keep replace keep keep
|
<mask> }
<mask> res := dnsfilter.Result{
<mask> IsFiltered: true,
<mask> Reason: dnsfilter.Rewritten,
<mask> ServiceName: "SomeService",
<mask> Rules: []*dnsfilter.ResultRule{{
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove Rules: []*dnsfilter.ResultRule{{
</s> add Rules: []*filtering.ResultRule{{ </s> remove Reason: dnsfilter.FilteredBlockList,
</s> add Reason: filtering.FilteredBlockList, </s> remove Result: dnsfilter.Result{
</s> add Result: filtering.Result{ </s> remove Rules: []*dnsfilter.ResultRule{{
</s> add Rules: []*filtering.ResultRule{{ </s> remove case dnsfilter.Rewritten,
dnsfilter.RewrittenRule:
</s> add case filtering.Rewritten,
filtering.RewrittenRule:
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> res := dnsfilter.Result{
<mask> IsFiltered: true,
<mask> Reason: dnsfilter.Rewritten,
<mask> ServiceName: "SomeService",
<mask> Rules: []*dnsfilter.ResultRule{{
<mask> FilterListID: 1,
<mask> Text: "SomeRule",
<mask> }},
<mask> }
<mask> params := AddParams{
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove Reason: dnsfilter.Rewritten,
</s> add Reason: filtering.Rewritten, </s> remove res := dnsfilter.Result{
</s> add res := filtering.Result{ </s> remove Reason: dnsfilter.FilteredBlockList,
</s> add Reason: filtering.FilteredBlockList, </s> remove Rules: []*dnsfilter.ResultRule{{
</s> add Rules: []*filtering.ResultRule{{ </s> remove Result: dnsfilter.Result{
</s> add Result: filtering.Result{ </s> remove makeRes := func(rcode rules.RCode, rr rules.RRType, v rules.RRValue) (res dnsfilter.Result) {
resp := dnsfilter.DNSRewriteResultResponse{
</s> add makeRes := func(rcode rules.RCode, rr rules.RRType, v rules.RRValue) (res filtering.Result) {
resp := filtering.DNSRewriteResultResponse{
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/qlog_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> "path/filepath"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/agherr"
<mask> "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/miekg/dns"
<mask> )
<mask>
<mask> // QueryLog - main interface
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/querylog.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> type AddParams struct {
<mask> Question *dns.Msg
<mask> Answer *dns.Msg // The response we sent to the client (optional)
<mask> OrigAnswer *dns.Msg // The response from an upstream server (optional)
<mask> Result *dnsfilter.Result // Filtering result (optional)
<mask> Elapsed time.Duration // Time spent for processing the request
<mask> ClientID string
<mask> ClientIP net.IP
<mask> Upstream string // Upstream server URL
<mask> ClientProto ClientProto
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove result *dnsfilter.Result
</s> add result *filtering.Result </s> remove setts *dnsfilter.FilteringSettings
</s> add setts *filtering.Settings </s> remove Result dnsfilter.Result
</s> add Result filtering.Result </s> remove dnsFilter *dnsfilter.DNSFilter // DNS filter instance
</s> add dnsFilter *filtering.DNSFilter // DNS filter instance </s> remove case dnsfilter.NotFilteredAllowList:
</s> add case filtering.NotFilteredAllowList: </s> remove func (s *Server) genDNSFilterMessage(d *proxy.DNSContext, result *dnsfilter.Result) *dns.Msg {
</s> add func (s *Server) genDNSFilterMessage(d *proxy.DNSContext, result *filtering.Result) *dns.Msg {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/querylog.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> "strings"
<mask> "unicode"
<mask> "unicode/utf8"
<mask>
<mask> "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
<mask> )
<mask>
<mask> type criterionType int
<mask>
<mask> const (
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering" </s> remove "github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
</s> add "github.com/AdguardTeam/AdGuardHome/internal/filtering"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> return c.ctDomainOrClientCaseNonStrict(term, clientID, name, host, ip)
<mask> }
<mask>
<mask> func (c *searchCriterion) ctFilteringStatusCase(res dnsfilter.Result) bool {
<mask> switch c.value {
<mask> case filteringStatusAll:
<mask> return true
<mask>
<mask> case filteringStatusFiltered:
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove dnsfilter.NotFilteredAllowList,
dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.NotFilteredAllowList,
filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule, </s> remove case dnsfilter.FilteredSafeBrowsing:
</s> add case filtering.FilteredSafeBrowsing: </s> remove case dnsfilter.FilteredParental:
</s> add case filtering.FilteredParental: </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeBrowsing
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeBrowsing </s> remove return res.Reason == dnsfilter.NotFilteredAllowList
</s> add return res.Reason == filtering.NotFilteredAllowList </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
</s> add return res.IsFiltered && res.Reason == filtering.FilteredParental
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep replace replace replace replace keep keep keep keep replace keep keep keep keep
|
<mask> case filteringStatusFiltered:
<mask> return res.IsFiltered ||
<mask> res.Reason.In(
<mask> dnsfilter.NotFilteredAllowList,
<mask> dnsfilter.Rewritten,
<mask> dnsfilter.RewrittenAutoHosts,
<mask> dnsfilter.RewrittenRule,
<mask> )
<mask>
<mask> case filteringStatusBlocked:
<mask> return res.IsFiltered &&
<mask> res.Reason.In(dnsfilter.FilteredBlockList, dnsfilter.FilteredBlockedService)
<mask>
<mask> case filteringStatusBlockedService:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredBlockedService
<mask>
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredBlockedService
</s> add return res.IsFiltered && res.Reason == filtering.FilteredBlockedService </s> remove dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule, </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
</s> add return res.IsFiltered && res.Reason == filtering.FilteredParental </s> remove return res.Reason == dnsfilter.NotFilteredAllowList
</s> add return res.Reason == filtering.NotFilteredAllowList </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeSearch
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep replace keep keep replace keep
|
<mask> res.Reason.In(dnsfilter.FilteredBlockList, dnsfilter.FilteredBlockedService)
<mask>
<mask> case filteringStatusBlockedService:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredBlockedService
<mask>
<mask> case filteringStatusBlockedParental:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
<mask>
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove res.Reason.In(dnsfilter.FilteredBlockList, dnsfilter.FilteredBlockedService)
</s> add res.Reason.In(filtering.FilteredBlockList, filtering.FilteredBlockedService) </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeBrowsing
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeBrowsing </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeSearch </s> remove return res.Reason == dnsfilter.NotFilteredAllowList
</s> add return res.Reason == filtering.NotFilteredAllowList </s> remove dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule,
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep keep replace keep keep replace
|
<mask> case filteringStatusBlockedParental:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
<mask>
<mask> case filteringStatusBlockedSafebrowsing:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeBrowsing
<mask>
<mask> case filteringStatusWhitelisted:
<mask> return res.Reason == dnsfilter.NotFilteredAllowList
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
</s> add return res.IsFiltered && res.Reason == filtering.FilteredParental </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredBlockedService
</s> add return res.IsFiltered && res.Reason == filtering.FilteredBlockedService </s> remove res.Reason.In(dnsfilter.FilteredBlockList, dnsfilter.FilteredBlockedService)
</s> add res.Reason.In(filtering.FilteredBlockList, filtering.FilteredBlockedService) </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeSearch </s> remove dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule,
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep keep replace replace replace keep keep keep replace keep keep
|
<mask> return res.Reason == dnsfilter.NotFilteredAllowList
<mask>
<mask> case filteringStatusRewritten:
<mask> return res.Reason.In(
<mask> dnsfilter.Rewritten,
<mask> dnsfilter.RewrittenAutoHosts,
<mask> dnsfilter.RewrittenRule,
<mask> )
<mask>
<mask> case filteringStatusSafeSearch:
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
<mask>
<mask> case filteringStatusProcessed:
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove return res.Reason == dnsfilter.NotFilteredAllowList
</s> add return res.Reason == filtering.NotFilteredAllowList </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeBrowsing
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeBrowsing </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
</s> add return res.IsFiltered && res.Reason == filtering.FilteredParental </s> remove dnsfilter.NotFilteredAllowList,
dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.NotFilteredAllowList,
filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule, </s> remove dnsfilter.FilteredBlockList,
dnsfilter.FilteredBlockedService,
dnsfilter.NotFilteredAllowList,
</s> add filtering.FilteredBlockList,
filtering.FilteredBlockedService,
filtering.NotFilteredAllowList,
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<mask> return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
<mask>
<mask> case filteringStatusProcessed:
<mask> return !res.Reason.In(
<mask> dnsfilter.FilteredBlockList,
<mask> dnsfilter.FilteredBlockedService,
<mask> dnsfilter.NotFilteredAllowList,
<mask> )
<mask>
<mask> default:
<mask> return false
<mask> }
</s> Pull request: all: less annoying pkg names
Merge in DNS/adguard-home from imp-naming to master
Squashed commit of the following:
commit d9e75c37af9a738384393735c141a41406d22eeb
Author: Ainar Garipov <[email protected]>
Date: Thu May 13 15:52:14 2021 +0300
all: less annoying pkg names </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeSearch
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeSearch </s> remove dnsfilter.Rewritten,
dnsfilter.RewrittenAutoHosts,
dnsfilter.RewrittenRule,
</s> add filtering.Rewritten,
filtering.RewrittenAutoHosts,
filtering.RewrittenRule, </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredParental
</s> add return res.IsFiltered && res.Reason == filtering.FilteredParental </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredBlockedService
</s> add return res.IsFiltered && res.Reason == filtering.FilteredBlockedService </s> remove return res.IsFiltered && res.Reason == dnsfilter.FilteredSafeBrowsing
</s> add return res.IsFiltered && res.Reason == filtering.FilteredSafeBrowsing </s> remove res.Reason.In(dnsfilter.FilteredBlockList, dnsfilter.FilteredBlockedService)
</s> add res.Reason.In(filtering.FilteredBlockList, filtering.FilteredBlockedService)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f2f8de92215eb2911241c036b8a5ed136d0eaed
|
internal/querylog/searchcriterion.go
|
keep keep keep add keep keep keep
|
<mask> "client_updated": "Client \"{{key}}\" successfully updated",
<mask> "table_statistics": "Requests count (last 24 hours)",
<mask> "clients_not_found": "No clients found",
<mask> "client_confirm_delete": "Are you sure you want to delete client \"{{key}}\"?",
<mask> "auto_clients_title": "Clients (runtime)",
<mask> "auto_clients_desc": "Data on the clients that use AdGuard Home, but not stored in the configuration"
<mask> } </s> * client: use JSON for filtering/remove_url </s> remove GET_CLIENTS = { path: 'clients', method: 'GET' }
ADD_CLIENT = { path: 'clients/add', method: 'POST' }
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
</s> add GET_CLIENTS = { path: 'clients', method: 'GET' };
ADD_CLIENT = { path: 'clients/add', method: 'POST' };
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }; </s> add handleDelete = (url) => {
// eslint-disable-next-line no-alert
if (window.confirm(this.props.t('filter_confirm_delete'))) {
this.props.removeFilter({ url });
}
}
</s> remove const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
</s> add const parameters = {
data: config,
headers: { 'Content-Type': 'application/json' }, </s> remove removeFilter(url) {
</s> add removeFilter(config) { </s> remove return this.makeRequest(path, method, config);
</s> add return this.makeRequest(path, method, parameters); </s> remove onClick={() => this.props.removeFilter(value)}
</s> add onClick={() => this.handleDelete(value)}
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/__locales/en.json
|
keep keep keep replace keep replace replace replace replace replace keep keep
|
<mask> return this.makeRequest(path, method, config);
<mask> }
<mask>
<mask> removeFilter(url) {
<mask> const { path, method } = this.FILTERING_REMOVE_FILTER;
<mask> const parameter = 'url';
<mask> const requestBody = `${parameter}=${url}`;
<mask> const config = {
<mask> data: requestBody,
<mask> header: { 'Content-Type': 'text/plain' },
<mask> };
<mask> return this.makeRequest(path, method, config);
</s> * client: use JSON for filtering/remove_url </s> remove return this.makeRequest(path, method, config);
</s> add return this.makeRequest(path, method, parameters); </s> remove GET_CLIENTS = { path: 'clients', method: 'GET' }
ADD_CLIENT = { path: 'clients/add', method: 'POST' }
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
</s> add GET_CLIENTS = { path: 'clients', method: 'GET' };
ADD_CLIENT = { path: 'clients/add', method: 'POST' };
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }; </s> add handleDelete = (url) => {
// eslint-disable-next-line no-alert
if (window.confirm(this.props.t('filter_confirm_delete'))) {
this.props.removeFilter({ url });
}
}
</s> add "filter_confirm_delete": "Are you sure you want to delete filter?", </s> remove onClick={() => this.props.removeFilter(value)}
</s> add onClick={() => this.handleDelete(value)}
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/api/Api.js
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> const config = {
<mask> data: requestBody,
<mask> header: { 'Content-Type': 'text/plain' },
<mask> };
<mask> return this.makeRequest(path, method, config);
<mask> }
<mask>
<mask> setRules(rules) {
<mask> const { path, method } = this.FILTERING_SET_RULES;
<mask> const parameters = {
</s> * client: use JSON for filtering/remove_url </s> remove const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
</s> add const parameters = {
data: config,
headers: { 'Content-Type': 'application/json' }, </s> remove removeFilter(url) {
</s> add removeFilter(config) { </s> remove GET_CLIENTS = { path: 'clients', method: 'GET' }
ADD_CLIENT = { path: 'clients/add', method: 'POST' }
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
</s> add GET_CLIENTS = { path: 'clients', method: 'GET' };
ADD_CLIENT = { path: 'clients/add', method: 'POST' };
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }; </s> add handleDelete = (url) => {
// eslint-disable-next-line no-alert
if (window.confirm(this.props.t('filter_confirm_delete'))) {
this.props.removeFilter({ url });
}
}
</s> add "filter_confirm_delete": "Are you sure you want to delete filter?", </s> remove onClick={() => this.props.removeFilter(value)}
</s> add onClick={() => this.handleDelete(value)}
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/api/Api.js
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<mask> return this.makeRequest(path, method, parameters);
<mask> }
<mask>
<mask> // Per-client settings
<mask> GET_CLIENTS = { path: 'clients', method: 'GET' }
<mask> ADD_CLIENT = { path: 'clients/add', method: 'POST' }
<mask> DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
<mask> UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
<mask>
<mask> getClients() {
<mask> const { path, method } = this.GET_CLIENTS;
<mask> return this.makeRequest(path, method);
<mask> }
</s> * client: use JSON for filtering/remove_url </s> remove return this.makeRequest(path, method, config);
</s> add return this.makeRequest(path, method, parameters); </s> remove removeFilter(url) {
</s> add removeFilter(config) { </s> remove const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
</s> add const parameters = {
data: config,
headers: { 'Content-Type': 'application/json' }, </s> add handleDelete = (url) => {
// eslint-disable-next-line no-alert
if (window.confirm(this.props.t('filter_confirm_delete'))) {
this.props.removeFilter({ url });
}
}
</s> add "filter_confirm_delete": "Are you sure you want to delete filter?", </s> remove onClick={() => this.props.removeFilter(value)}
</s> add onClick={() => this.handleDelete(value)}
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/api/Api.js
|
keep add keep keep keep keep
|
<mask> };
<mask>
<mask> columns = [{
<mask> Header: <Trans>enabled_table_header</Trans>,
<mask> accessor: 'enabled',
<mask> Cell: this.renderCheckbox,
</s> * client: use JSON for filtering/remove_url </s> remove GET_CLIENTS = { path: 'clients', method: 'GET' }
ADD_CLIENT = { path: 'clients/add', method: 'POST' }
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
</s> add GET_CLIENTS = { path: 'clients', method: 'GET' };
ADD_CLIENT = { path: 'clients/add', method: 'POST' };
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }; </s> remove onClick={() => this.props.removeFilter(value)}
</s> add onClick={() => this.handleDelete(value)} </s> remove removeFilter(url) {
</s> add removeFilter(config) { </s> remove return this.makeRequest(path, method, config);
</s> add return this.makeRequest(path, method, parameters); </s> remove const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
</s> add const parameters = {
data: config,
headers: { 'Content-Type': 'application/json' }, </s> add "filter_confirm_delete": "Are you sure you want to delete filter?",
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/components/Filters/index.js
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> Cell: ({ value }) => (
<mask> <button
<mask> type="button"
<mask> className="btn btn-icon btn-outline-secondary btn-sm"
<mask> onClick={() => this.props.removeFilter(value)}
<mask> title={this.props.t('delete_table_action')}
<mask> >
<mask> <svg className="icons">
<mask> <use xlinkHref="#delete" />
<mask> </svg>
</s> * client: use JSON for filtering/remove_url </s> add handleDelete = (url) => {
// eslint-disable-next-line no-alert
if (window.confirm(this.props.t('filter_confirm_delete'))) {
this.props.removeFilter({ url });
}
}
</s> remove GET_CLIENTS = { path: 'clients', method: 'GET' }
ADD_CLIENT = { path: 'clients/add', method: 'POST' }
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' }
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }
</s> add GET_CLIENTS = { path: 'clients', method: 'GET' };
ADD_CLIENT = { path: 'clients/add', method: 'POST' };
DELETE_CLIENT = { path: 'clients/delete', method: 'POST' };
UPDATE_CLIENT = { path: 'clients/update', method: 'POST' }; </s> remove return this.makeRequest(path, method, config);
</s> add return this.makeRequest(path, method, parameters); </s> remove const parameter = 'url';
const requestBody = `${parameter}=${url}`;
const config = {
data: requestBody,
header: { 'Content-Type': 'text/plain' },
</s> add const parameters = {
data: config,
headers: { 'Content-Type': 'application/json' }, </s> remove removeFilter(url) {
</s> add removeFilter(config) { </s> add "filter_confirm_delete": "Are you sure you want to delete filter?",
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f5ac19b592c2a63e52a5e5319e9e8eb687c7410
|
client/src/components/Filters/index.js
|
keep replace keep replace replace replace replace replace keep keep
|
<mask> import (
<mask> "bufio"
<mask> "bytes"
<mask> "context"
<mask> "crypto/sha256"
<mask> "encoding/binary"
<mask> "encoding/gob"
<mask> "encoding/json"
<mask> "fmt"
<mask> "io/ioutil"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "bytes"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/hex" </s> remove "net/http"
"net/http/httptest"
</s> add </s> add "net" </s> remove // check safeSearch if no match
</s> add </s> remove // nothing matched, return nothing
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<mask> "os"
<mask> "runtime"
<mask> "strings"
<mask> "sync"
<mask> "sync/atomic"
<mask> "time"
<mask>
<mask> "github.com/joomcode/errorx"
<mask>
<mask> "github.com/AdguardTeam/dnsproxy/upstream"
<mask> "github.com/AdguardTeam/golibs/cache"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/AdguardTeam/urlfilter"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "time" </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> remove "github.com/bluele/gcache"
</s> add </s> remove "time"
</s> add </s> add "net" </s> add "github.com/miekg/dns"
"golang.org/x/net/publicsuffix"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep replace keep replace keep keep
|
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/AdguardTeam/urlfilter"
<mask> "github.com/bluele/gcache"
<mask> "github.com/miekg/dns"
<mask> "golang.org/x/net/publicsuffix"
<mask> )
<mask>
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove "github.com/bluele/gcache"
</s> add </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> add "github.com/miekg/dns"
"golang.org/x/net/publicsuffix" </s> remove "time"
</s> add </s> add "time"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace replace replace replace replace replace replace replace replace keep keep keep keep keep
|
<mask> "github.com/miekg/dns"
<mask> "golang.org/x/net/publicsuffix"
<mask> )
<mask>
<mask> const defaultHTTPTimeout = 5 * time.Minute
<mask> const defaultHTTPMaxIdleConnections = 100
<mask>
<mask> const defaultSafebrowsingServer = "sb.adtidy.org"
<mask> const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
<mask> const defaultParentalServer = "pctrl.adguard.com"
<mask> const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
<mask> const defaultParentalSensitivity = 13 // use "TEEN" by default
<mask> const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
<mask>
<mask> // ServiceEntry - blocked service array element
<mask> type ServiceEntry struct {
<mask> Name string
<mask> Rules []*urlfilter.NetworkRule
<mask> }
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove "golang.org/x/net/publicsuffix"
</s> add </s> add "github.com/miekg/dns"
"golang.org/x/net/publicsuffix" </s> remove "github.com/bluele/gcache"
</s> add </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove dialCache gcache.Cache // "host" -> "IP" cache for safebrowsing and parental control servers
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // Config allows you to configure DNS filtering with New() or just change variables directly.
<mask> type Config struct {
<mask> ParentalSensitivity int `yaml:"parental_sensitivity"` // must be either 3, 10, 13 or 17
<mask> ParentalEnabled bool `yaml:"parental_enabled"`
<mask> UsePlainHTTP bool `yaml:"-"` // use plain HTTP for requests to parental and safe browsing servers
<mask> SafeSearchEnabled bool `yaml:"safesearch_enabled"`
<mask> SafeBrowsingEnabled bool `yaml:"safebrowsing_enabled"`
<mask> ResolverAddress string `yaml:"-"` // DNS server address
<mask>
<mask> SafeBrowsingCacheSize uint `yaml:"safebrowsing_cache_size"` // (in bytes)
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // HTTP lookups for safebrowsing and parental
client http.Client // handle for http client -- single instance as recommended by docs
transport *http.Transport // handle for http transport used by http client
parentalServer string // access via methods
safeBrowsingServer string // access via methods
</s> add parentalServer string // access via methods
safeBrowsingServer string // access via methods
parentalUpstream upstream.Upstream
safeBrowsingUpstream upstream.Upstream </s> remove const defaultHTTPTimeout = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalServer = "pctrl.adguard.com"
const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
const defaultParentalSensitivity = 13 // use "TEEN" by default
const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
</s> add </s> remove dialCache gcache.Cache // "host" -> "IP" cache for safebrowsing and parental control servers
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace replace replace replace replace keep keep keep keep keep
|
<mask> rulesStorage *urlfilter.RuleStorage
<mask> filteringEngine *urlfilter.DNSEngine
<mask> engineLock sync.RWMutex
<mask>
<mask> // HTTP lookups for safebrowsing and parental
<mask> client http.Client // handle for http client -- single instance as recommended by docs
<mask> transport *http.Transport // handle for http transport used by http client
<mask>
<mask> parentalServer string // access via methods
<mask> safeBrowsingServer string // access via methods
<mask>
<mask> Config // for direct access by library users, even a = assignment
<mask> confLock sync.RWMutex
<mask>
<mask> // Channel for passing data to filters-initializer goroutine
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove const defaultHTTPTimeout = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalServer = "pctrl.adguard.com"
const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
const defaultParentalSensitivity = 13 // use "TEEN" by default
const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
</s> add </s> remove UsePlainHTTP bool `yaml:"-"` // use plain HTTP for requests to parental and safe browsing servers
</s> add </s> remove dialCache gcache.Cache // "host" -> "IP" cache for safebrowsing and parental control servers
</s> add </s> remove // nothing matched, return nothing
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove // check safebrowsing if no match
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<mask> }
<mask>
<mask> // Close - close the object
<mask> func (d *Dnsfilter) Close() {
<mask> if d != nil && d.transport != nil {
<mask> d.transport.CloseIdleConnections()
<mask> }
<mask> if d.rulesStorage != nil {
<mask> d.rulesStorage.Close()
<mask> }
<mask> }
<mask>
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove
if len(c.ResolverAddress) != 0 && gctx.dialCache == nil {
dur := time.Duration(c.CacheTime) * time.Minute
gctx.dialCache = gcache.New(maxDialCacheSize).LRU().Expiration(dur).Build()
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove
func TestDnsfilterDialCache(t *testing.T) {
d := Dnsfilter{}
gctx.dialCache = gcache.New(1).LRU().Expiration(30 * time.Minute).Build()
d.shouldBeInDialCache("hostname")
if searchInDialCache("hostname") != "" {
t.Errorf("searchInDialCache")
}
addToDialCache("hostname", "1.1.1.1")
if searchInDialCache("hostname") != "1.1.1.1" {
t.Errorf("searchInDialCache")
}
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> }
<mask>
<mask> type dnsFilterContext struct {
<mask> stats Stats
<mask> dialCache gcache.Cache // "host" -> "IP" cache for safebrowsing and parental control servers
<mask> safebrowsingCache cache.Cache
<mask> parentalCache cache.Cache
<mask> safeSearchCache cache.Cache
<mask> }
<mask>
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove const defaultHTTPTimeout = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalServer = "pctrl.adguard.com"
const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
const defaultParentalSensitivity = 13 // use "TEEN" by default
const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
</s> add </s> remove UsePlainHTTP bool `yaml:"-"` // use plain HTTP for requests to parental and safe browsing servers
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove // check parental if no match
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep replace keep keep keep replace keep keep keep
|
<mask>
<mask> // check safeSearch if no match
<mask> if setts.SafeSearchEnabled {
<mask> result, err = d.checkSafeSearch(host)
<mask> if err != nil {
<mask> log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
<mask> return Result{}, nil
<mask> }
<mask>
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeBrowsing: failed: %v", err) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
</s> add log.Printf("Parental: failed: %v", err) </s> remove // check safebrowsing if no match
</s> add </s> remove // check parental if no match
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace keep keep keep replace replace keep keep keep
|
<mask> return result, nil
<mask> }
<mask> }
<mask>
<mask> // check safebrowsing if no match
<mask> if setts.SafeBrowsingEnabled {
<mask> result, err = d.checkSafeBrowsing(host)
<mask> if err != nil {
<mask> // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
<mask> log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
<mask> return Result{}, nil
<mask> }
<mask> if result.Reason.Matched() {
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
</s> add log.Printf("Parental: failed: %v", err) </s> remove // check parental if no match
</s> add </s> remove log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeSearch: failed: %v", err) </s> remove // check safeSearch if no match
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep replace keep keep keep replace replace keep keep keep keep
|
<mask>
<mask> // check parental if no match
<mask> if setts.ParentalEnabled {
<mask> result, err = d.checkParental(host)
<mask> if err != nil {
<mask> // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
<mask> log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
<mask> return Result{}, nil
<mask> }
<mask> if result.Reason.Matched() {
<mask> return result, nil
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeBrowsing: failed: %v", err) </s> remove // check safebrowsing if no match
</s> add </s> remove log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeSearch: failed: %v", err) </s> remove // check safeSearch if no match
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> return result, nil
<mask> }
<mask> }
<mask>
<mask> // nothing matched, return nothing
<mask> return Result{}, nil
<mask> }
<mask>
<mask> // Process rewrites table
<mask> // . Find CNAME for a domain name
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // check safeSearch if no match
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeSearch: failed: %v", err) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeBrowsing: failed: %v", err) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
</s> add log.Printf("Parental: failed: %v", err)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.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 replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace 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> }
<mask> return res
<mask> }
<mask>
<mask> /*
<mask> expire byte[4]
<mask> res Result
<mask> */
<mask> func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
<mask> var buf bytes.Buffer
<mask>
<mask> expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
<mask> var exp []byte
<mask> exp = make([]byte, 4)
<mask> binary.BigEndian.PutUint32(exp, uint32(expire))
<mask> _, _ = buf.Write(exp)
<mask>
<mask> enc := gob.NewEncoder(&buf)
<mask> err := enc.Encode(res)
<mask> if err != nil {
<mask> log.Error("gob.Encode(): %s", err)
<mask> return
<mask> }
<mask> _ = cache.Set([]byte(host), buf.Bytes())
<mask> log.Debug("Stored in cache %p: %s", cache, host)
<mask> }
<mask>
<mask> func getCachedResult(cache cache.Cache, host string) (Result, bool) {
<mask> data := cache.Get([]byte(host))
<mask> if data == nil {
<mask> return Result{}, false
<mask> }
<mask>
<mask> exp := int(binary.BigEndian.Uint32(data[:4]))
<mask> if exp <= int(time.Now().Unix()) {
<mask> cache.Del([]byte(host))
<mask> return Result{}, false
<mask> }
<mask>
<mask> var buf bytes.Buffer
<mask> buf.Write(data[4:])
<mask> dec := gob.NewDecoder(&buf)
<mask> r := Result{}
<mask> err := dec.Decode(&r)
<mask> if err != nil {
<mask> log.Debug("gob.Decode(): %s", err)
<mask> return Result{}, false
<mask> }
<mask>
<mask> return r, true
<mask> }
<mask>
<mask> // for each dot, hash it and add it to string
<mask> func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
<mask> var hashparam bytes.Buffer
<mask> hashes := map[string]bool{}
<mask> tld, icann := publicsuffix.PublicSuffix(host)
<mask> if !icann {
<mask> // private suffixes like cloudfront.net
<mask> tld = ""
<mask> }
<mask> curhost := host
<mask> for {
<mask> if curhost == "" {
<mask> // we've reached end of string
<mask> break
<mask> }
<mask> if tld != "" && curhost == tld {
<mask> // we've reached the TLD, don't hash it
<mask> break
<mask> }
<mask> tohash := []byte(curhost)
<mask> if addslash {
<mask> tohash = append(tohash, '/')
<mask> }
<mask> sum := sha256.Sum256(tohash)
<mask> hexhash := fmt.Sprintf("%X", sum)
<mask> hashes[hexhash] = true
<mask> hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
<mask> pos := strings.IndexByte(curhost, byte('.'))
<mask> if pos < 0 {
<mask> break
<mask> }
<mask> curhost = curhost[pos+1:]
<mask> }
<mask> return hashparam.String(), hashes
<mask> }
<mask>
<mask> func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
<mask> if log.GetLevel() >= log.DEBUG {
<mask> timer := log.StartTimer()
<mask> defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
<mask> }
<mask>
<mask> // Check cache. Return cached result if it was found
<mask> cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
<mask> if isFound {
<mask> atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
<mask> log.Tracef("%s: found in SafeSearch cache", host)
<mask> return cachedValue, nil
<mask> }
<mask>
<mask> safeHost, ok := d.SafeSearchDomain(host)
<mask> if !ok {
<mask> return Result{}, nil
<mask> }
<mask>
<mask> res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
<mask> if ip := net.ParseIP(safeHost); ip != nil {
<mask> res.IP = ip
<mask> d.setCacheResult(gctx.safeSearchCache, host, res)
<mask> return res, nil
<mask> }
<mask>
<mask> // TODO this address should be resolved with upstream that was configured in dnsforward
<mask> addrs, err := net.LookupIP(safeHost)
<mask> if err != nil {
<mask> log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
<mask> return Result{}, err
<mask> }
<mask>
<mask> for _, i := range addrs {
<mask> if ipv4 := i.To4(); ipv4 != nil {
<mask> res.IP = ipv4
<mask> break
<mask> }
<mask> }
<mask>
<mask> if len(res.IP) == 0 {
<mask> return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
<mask> }
<mask>
<mask> // Cache result
<mask> d.setCacheResult(gctx.safeSearchCache, host, res)
<mask> return res, nil
<mask> }
<mask>
<mask> func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
<mask> if log.GetLevel() >= log.DEBUG {
<mask> timer := log.StartTimer()
<mask> defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
<mask> }
<mask>
<mask> format := func(hashparam string) string {
<mask> schema := "https"
<mask> if d.UsePlainHTTP {
<mask> schema = "http"
<mask> }
<mask> url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
<mask> return url
<mask> }
<mask> handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
<mask> result := Result{}
<mask> scanner := bufio.NewScanner(strings.NewReader(string(body)))
<mask> for scanner.Scan() {
<mask> line := scanner.Text()
<mask> splitted := strings.Split(line, ":")
<mask> if len(splitted) < 3 {
<mask> continue
<mask> }
<mask> hash := splitted[2]
<mask> if _, ok := hashes[hash]; ok {
<mask> // it's in the hash
<mask> result.IsFiltered = true
<mask> result.Reason = FilteredSafeBrowsing
<mask> result.Rule = splitted[0]
<mask> break
<mask> }
<mask> }
<mask>
<mask> if err := scanner.Err(); err != nil {
<mask> // error, don't save cache
<mask> return Result{}, err
<mask> }
<mask> return result, nil
<mask> }
<mask>
<mask> // check cache
<mask> cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
<mask> if isFound {
<mask> atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
<mask> log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
<mask> return cachedValue, nil
<mask> }
<mask>
<mask> result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
<mask>
<mask> if err == nil {
<mask> d.setCacheResult(gctx.safebrowsingCache, host, result)
<mask> }
<mask>
<mask> return result, err
<mask> }
<mask>
<mask> func (d *Dnsfilter) checkParental(host string) (Result, error) {
<mask> if log.GetLevel() >= log.DEBUG {
<mask> timer := log.StartTimer()
<mask> defer timer.LogElapsed("Parental HTTP lookup for %s", host)
<mask> }
<mask>
<mask> format := func(hashparam string) string {
<mask> schema := "https"
<mask> if d.UsePlainHTTP {
<mask> schema = "http"
<mask> }
<mask> sensitivity := d.ParentalSensitivity
<mask> if sensitivity == 0 {
<mask> sensitivity = defaultParentalSensitivity
<mask> }
<mask> url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
<mask> return url
<mask> }
<mask> handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
<mask> // parse json
<mask> var m []struct {
<mask> Blocked bool `json:"blocked"`
<mask> ClientTTL int `json:"clientTtl"`
<mask> Reason string `json:"reason"`
<mask> Hash string `json:"hash"`
<mask> }
<mask> err := json.Unmarshal(body, &m)
<mask> if err != nil {
<mask> // error, don't save cache
<mask> log.Printf("Couldn't parse json '%s': %s", body, err)
<mask> return Result{}, err
<mask> }
<mask>
<mask> result := Result{}
<mask>
<mask> for i := range m {
<mask> if !hashes[m[i].Hash] {
<mask> continue
<mask> }
<mask> if m[i].Blocked {
<mask> result.IsFiltered = true
<mask> result.Reason = FilteredParental
<mask> result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
<mask> break
<mask> }
<mask> }
<mask> return result, nil
<mask> }
<mask>
<mask> // check cache
<mask> cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
<mask> if isFound {
<mask> atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
<mask> log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
<mask> return cachedValue, nil
<mask> }
<mask>
<mask> result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
<mask>
<mask> if err == nil {
<mask> d.setCacheResult(gctx.parentalCache, host, result)
<mask> }
<mask>
<mask> return result, err
<mask> }
<mask>
<mask> type formatHandler func(hashparam string) string
<mask> type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
<mask>
<mask> // real implementation of lookup/check
<mask> func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
<mask> // convert hostname to hash parameters
<mask> hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
<mask>
<mask> // format URL with our hashes
<mask> url := format(hashparam)
<mask>
<mask> // do HTTP request
<mask> atomic.AddUint64(&lookupstats.Requests, 1)
<mask> atomic.AddInt64(&lookupstats.Pending, 1)
<mask> updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
<mask> resp, err := d.client.Get(url)
<mask> atomic.AddInt64(&lookupstats.Pending, -1)
<mask> if resp != nil && resp.Body != nil {
<mask> defer resp.Body.Close()
<mask> }
<mask> if err != nil {
<mask> // error, don't save cache
<mask> return Result{}, err
<mask> }
<mask>
<mask> // get body text
<mask> body, err := ioutil.ReadAll(resp.Body)
<mask> if err != nil {
<mask> // error, don't save cache
<mask> return Result{}, err
<mask> }
<mask>
<mask> // handle status code
<mask> switch {
<mask> case resp.StatusCode == 204:
<mask> // empty result, save cache
<mask> return Result{}, nil
<mask> case resp.StatusCode != 200:
<mask> return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
<mask> }
<mask>
<mask> result, err := handleBody(body, hashes)
<mask> if err != nil {
<mask> return Result{}, err
<mask> }
<mask>
<mask> return result, nil
<mask> }
<mask>
<mask> //
<mask> // Adding rule and matching against the rules
<mask> //
<mask>
<mask> // Return TRUE if file exists
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeBrowsing: failed: %v", err) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
</s> add log.Printf("Parental: failed: %v", err) </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove // check safeSearch if no match
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.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 keep keep keep keep keep
|
<mask>
<mask> return Result{}, nil
<mask> }
<mask>
<mask> //
<mask> // lifecycle helper functions
<mask> //
<mask>
<mask> // Return TRUE if this host's IP should be cached
<mask> func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
<mask> return host == d.safeBrowsingServer ||
<mask> host == d.parentalServer
<mask> }
<mask>
<mask> // Search for an IP address by host name
<mask> func searchInDialCache(host string) string {
<mask> rawValue, err := gctx.dialCache.Get(host)
<mask> if err != nil {
<mask> return ""
<mask> }
<mask>
<mask> ip, _ := rawValue.(string)
<mask> log.Debug("Found in cache: %s -> %s", host, ip)
<mask> return ip
<mask> }
<mask>
<mask> // Add "hostname" -> "IP address" entry to cache
<mask> func addToDialCache(host, ip string) {
<mask> err := gctx.dialCache.Set(host, ip)
<mask> if err != nil {
<mask> log.Debug("dialCache.Set: %s", err)
<mask> }
<mask> log.Debug("Added to cache: %s -> %s", host, ip)
<mask> }
<mask>
<mask> type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
<mask>
<mask> // Connect to a remote server resolving hostname using our own DNS server
<mask> func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
<mask> return func(ctx context.Context, network, addr string) (net.Conn, error) {
<mask> log.Tracef("network:%v addr:%v", network, addr)
<mask>
<mask> host, port, err := net.SplitHostPort(addr)
<mask> if err != nil {
<mask> return nil, err
<mask> }
<mask>
<mask> dialer := &net.Dialer{
<mask> Timeout: time.Minute * 5,
<mask> }
<mask>
<mask> if net.ParseIP(host) != nil {
<mask> con, err := dialer.DialContext(ctx, network, addr)
<mask> return con, err
<mask> }
<mask>
<mask> cache := d.shouldBeInDialCache(host)
<mask> if cache {
<mask> ip := searchInDialCache(host)
<mask> if len(ip) != 0 {
<mask> addr = fmt.Sprintf("%s:%s", ip, port)
<mask> return dialer.DialContext(ctx, network, addr)
<mask> }
<mask> }
<mask>
<mask> r := upstream.NewResolver(resolverAddr, 30*time.Second)
<mask> addrs, e := r.LookupIPAddr(ctx, host)
<mask> log.Tracef("LookupIPAddr: %s: %v", host, addrs)
<mask> if e != nil {
<mask> return nil, e
<mask> }
<mask>
<mask> if len(addrs) == 0 {
<mask> return nil, fmt.Errorf("couldn't lookup host: %s", host)
<mask> }
<mask>
<mask> var dialErrs []error
<mask> for _, a := range addrs {
<mask> addr = fmt.Sprintf("%s:%s", a.String(), port)
<mask> con, err := dialer.DialContext(ctx, network, addr)
<mask> if err != nil {
<mask> dialErrs = append(dialErrs, err)
<mask> continue
<mask> }
<mask>
<mask> if cache {
<mask> addToDialCache(host, a.String())
<mask> }
<mask>
<mask> return con, err
<mask> }
<mask> return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
<mask> }
<mask> }
<mask>
<mask> // New creates properly initialized DNS Filter that is ready to be used
<mask> func New(c *Config, filters map[int]string) *Dnsfilter {
<mask>
<mask> if c != nil {
<mask> cacheConf := cache.Config{
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove // check safeSearch if no match
</s> add </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do safebrowsing HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeBrowsing: failed: %v", err) </s> remove // failed to do HTTP lookup -- treat it as if we got empty response, but don't save cache
log.Printf("Failed to do parental HTTP lookup, ignoring check: %v", err)
</s> add log.Printf("Parental: failed: %v", err)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep replace replace replace replace replace keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace replace keep keep keep
|
<mask> }
<mask>
<mask> if len(c.ResolverAddress) != 0 && gctx.dialCache == nil {
<mask> dur := time.Duration(c.CacheTime) * time.Minute
<mask> gctx.dialCache = gcache.New(maxDialCacheSize).LRU().Expiration(dur).Build()
<mask> }
<mask> }
<mask>
<mask> d := new(Dnsfilter)
<mask>
<mask> // Customize the Transport to have larger connection pool,
<mask> // We are not (re)using http.DefaultTransport because of race conditions found by tests
<mask> d.transport = &http.Transport{
<mask> Proxy: http.ProxyFromEnvironment,
<mask> MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
<mask> MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
<mask> IdleConnTimeout: 90 * time.Second,
<mask> TLSHandshakeTimeout: 10 * time.Second,
<mask> ExpectContinueTimeout: 1 * time.Second,
<mask> }
<mask> if c != nil && len(c.ResolverAddress) != 0 {
<mask> d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
<mask> }
<mask> d.client = http.Client{
<mask> Transport: d.transport,
<mask> Timeout: defaultHTTPTimeout,
<mask> }
<mask> d.safeBrowsingServer = defaultSafebrowsingServer
<mask> d.parentalServer = defaultParentalServer
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove d.safeBrowsingServer = defaultSafebrowsingServer
d.parentalServer = defaultParentalServer
</s> add </s> remove const defaultHTTPTimeout = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalServer = "pctrl.adguard.com"
const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
const defaultParentalSensitivity = 13 // use "TEEN" by default
const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
</s> add </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove
func TestDnsfilterDialCache(t *testing.T) {
d := Dnsfilter{}
gctx.dialCache = gcache.New(1).LRU().Expiration(30 * time.Minute).Build()
d.shouldBeInDialCache("hostname")
if searchInDialCache("hostname") != "" {
t.Errorf("searchInDialCache")
}
addToDialCache("hostname", "1.1.1.1")
if searchInDialCache("hostname") != "1.1.1.1" {
t.Errorf("searchInDialCache")
}
}
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace keep keep keep keep keep
|
<mask> d.client = http.Client{
<mask> Transport: d.transport,
<mask> Timeout: defaultHTTPTimeout,
<mask> }
<mask> d.safeBrowsingServer = defaultSafebrowsingServer
<mask> d.parentalServer = defaultParentalServer
<mask> if c != nil {
<mask> d.Config = *c
<mask> }
<mask>
<mask> if filters != nil {
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove
if len(c.ResolverAddress) != 0 && gctx.dialCache == nil {
dur := time.Duration(c.CacheTime) * time.Minute
gctx.dialCache = gcache.New(maxDialCacheSize).LRU().Expiration(dur).Build()
}
</s> add </s> add // test cached result
d.parentalServer = "127.0.0.1"
d.checkMatch(t, "pornhub.com")
d.checkMatchEmpty(t, "yandex.ru")
d.parentalServer = defaultParentalServer </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.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 keep keep keep keep keep
|
<mask> }
<mask> return d
<mask> }
<mask>
<mask> //
<mask> // config manipulation helpers
<mask> //
<mask>
<mask> // SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
<mask> func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
<mask> if len(host) == 0 {
<mask> d.safeBrowsingServer = defaultSafebrowsingServer
<mask> } else {
<mask> d.safeBrowsingServer = host
<mask> }
<mask> }
<mask>
<mask> // SetHTTPTimeout lets you optionally change timeout during lookups
<mask> func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
<mask> d.client.Timeout = t
<mask> }
<mask>
<mask> // ResetHTTPTimeout resets lookup timeouts
<mask> func (d *Dnsfilter) ResetHTTPTimeout() {
<mask> d.client.Timeout = defaultHTTPTimeout
<mask> }
<mask>
<mask> // SafeSearchDomain returns replacement address for search engine
<mask> func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
<mask> if d.SafeSearchEnabled {
<mask> val, ok := safeSearchDomains[host]
<mask> return val, ok
<mask> }
<mask> return "", false
<mask> }
<mask>
<mask> //
<mask> // stats
<mask> //
<mask>
<mask> // GetStats return dns filtering stats since startup
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove if d != nil && d.transport != nil {
d.transport.CloseIdleConnections()
}
</s> add </s> remove d := NewForTest(nil, nil)
defer d.Close()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
</s> add d := NewForTest(&Config{SafeSearchEnabled: true}, nil) </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter.go
|
keep keep replace replace keep keep keep replace keep keep keep
|
<mask> "fmt"
<mask> "net"
<mask> "net/http"
<mask> "net/http/httptest"
<mask> "path"
<mask> "runtime"
<mask> "testing"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/urlfilter"
<mask> "github.com/bluele/gcache"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "net" </s> remove "github.com/bluele/gcache"
</s> add </s> remove "context"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/json"
</s> add </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add </s> add "bytes"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/hex"
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> "testing"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/urlfilter"
<mask> "github.com/bluele/gcache"
<mask> "github.com/miekg/dns"
<mask> "github.com/stretchr/testify/assert"
<mask> )
<mask>
<mask> var setts RequestFilteringSettings
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove "time"
</s> add </s> remove "github.com/bluele/gcache"
</s> add </s> remove "golang.org/x/net/publicsuffix"
</s> add </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> remove "net/http"
"net/http/httptest"
</s> add </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // SAFE BROWSING
<mask> // SAFE SEARCH
<mask> // PARENTAL
<mask> // FILTERING
<mask> // CLIENTS SETTINGS
<mask> // BENCHMARKS
<mask>
<mask> // HELPERS
<mask>
<mask> func purgeCaches() {
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove d := NewForTest(nil, nil)
defer d.Close()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
</s> add d := NewForTest(&Config{SafeSearchEnabled: true}, nil) </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> add // test cached result
d.parentalServer = "127.0.0.1"
d.checkMatch(t, "pornhub.com")
d.checkMatchEmpty(t, "yandex.ru")
d.parentalServer = defaultParentalServer </s> remove l := gctx.stats.Parental.Requests
d.checkMatchEmpty(t, "yandex.ru")
if gctx.stats.Parental.Requests != l {
t.Errorf("Parental lookup negative cache is not working")
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.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 keep keep keep keep keep
|
<mask>
<mask> // SAFE BROWSING
<mask>
<mask> func TestSafeBrowsing(t *testing.T) {
<mask> testCases := []string{
<mask> "",
<mask> "sb.adtidy.org",
<mask> }
<mask> for _, tc := range testCases {
<mask> t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
<mask> d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
<mask> defer d.Close()
<mask> gctx.stats.Safebrowsing.Requests = 0
<mask> d.checkMatch(t, "wmconvirus.narod.ru")
<mask> d.checkMatch(t, "wmconvirus.narod.ru")
<mask> if gctx.stats.Safebrowsing.Requests != 1 {
<mask> t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
<mask> }
<mask> d.checkMatch(t, "WMconvirus.narod.ru")
<mask> if gctx.stats.Safebrowsing.Requests != 1 {
<mask> t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
<mask> }
<mask> d.checkMatch(t, "test.wmconvirus.narod.ru")
<mask> d.checkMatchEmpty(t, "yandex.ru")
<mask> d.checkMatchEmpty(t, "pornhub.com")
<mask> l := gctx.stats.Safebrowsing.Requests
<mask> d.checkMatchEmpty(t, "pornhub.com")
<mask> if gctx.stats.Safebrowsing.Requests != l {
<mask> t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
<mask> }
<mask> })
<mask> }
<mask> }
<mask>
<mask> func TestParallelSB(t *testing.T) {
<mask> d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
<mask> defer d.Close()
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove d.checkMatch(t, "pornhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "PORNhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
</s> add </s> remove l := gctx.stats.Parental.Requests
d.checkMatchEmpty(t, "yandex.ru")
if gctx.stats.Parental.Requests != l {
t.Errorf("Parental lookup negative cache is not working")
}
</s> add </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove d := NewForTest(nil, nil)
defer d.Close()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
</s> add d := NewForTest(&Config{SafeSearchEnabled: true}, nil) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.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> }
<mask> })
<mask> }
<mask>
<mask> // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
<mask> func TestSafeBrowsingCustomServerFail(t *testing.T) {
<mask> d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
<mask> defer d.Close()
<mask> ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<mask> // w.Write("Hello, client")
<mask> fmt.Fprintln(w, "Hello, client")
<mask> }))
<mask> defer ts.Close()
<mask> address := ts.Listener.Addr().String()
<mask>
<mask> d.SetHTTPTimeout(time.Second * 5)
<mask> d.SetSafeBrowsingServer(address) // this will ensure that test fails
<mask> d.checkMatchEmpty(t, "wmconvirus.narod.ru")
<mask> }
<mask>
<mask> // SAFE SEARCH
<mask>
<mask> func TestSafeSearch(t *testing.T) {
<mask> d := NewForTest(nil, nil)
<mask> defer d.Close()
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove d := NewForTest(nil, nil)
defer d.Close()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
</s> add d := NewForTest(&Config{SafeSearchEnabled: true}, nil) </s> remove d.checkMatch(t, "pornhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "PORNhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
</s> add </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove
func TestDnsfilterDialCache(t *testing.T) {
d := Dnsfilter{}
gctx.dialCache = gcache.New(1).LRU().Expiration(30 * time.Minute).Build()
d.shouldBeInDialCache("hostname")
if searchInDialCache("hostname") != "" {
t.Errorf("searchInDialCache")
}
addToDialCache("hostname", "1.1.1.1")
if searchInDialCache("hostname") != "1.1.1.1" {
t.Errorf("searchInDialCache")
}
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep keep replace replace replace replace replace replace replace replace keep keep keep keep keep
|
<mask>
<mask> // SAFE SEARCH
<mask>
<mask> func TestSafeSearch(t *testing.T) {
<mask> d := NewForTest(nil, nil)
<mask> defer d.Close()
<mask> _, ok := d.SafeSearchDomain("www.google.com")
<mask> if ok {
<mask> t.Errorf("Expected safesearch to error when disabled")
<mask> }
<mask>
<mask> d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
<mask> defer d.Close()
<mask> val, ok := d.SafeSearchDomain("www.google.com")
<mask> if !ok {
<mask> t.Errorf("Expected safesearch to find result for www.google.com")
<mask> }
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove //
// config manipulation helpers
//
// SetSafeBrowsingServer lets you optionally change hostname of safesearch lookup
func (d *Dnsfilter) SetSafeBrowsingServer(host string) {
if len(host) == 0 {
d.safeBrowsingServer = defaultSafebrowsingServer
} else {
d.safeBrowsingServer = host
}
}
// SetHTTPTimeout lets you optionally change timeout during lookups
func (d *Dnsfilter) SetHTTPTimeout(t time.Duration) {
d.client.Timeout = t
}
// ResetHTTPTimeout resets lookup timeouts
func (d *Dnsfilter) ResetHTTPTimeout() {
d.client.Timeout = defaultHTTPTimeout
}
// SafeSearchDomain returns replacement address for search engine
func (d *Dnsfilter) SafeSearchDomain(host string) (string, bool) {
if d.SafeSearchEnabled {
val, ok := safeSearchDomains[host]
return val, ok
}
return "", false
}
</s> add </s> remove d.checkMatch(t, "pornhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "PORNhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add </s> remove
func TestDnsfilterDialCache(t *testing.T) {
d := Dnsfilter{}
gctx.dialCache = gcache.New(1).LRU().Expiration(30 * time.Minute).Build()
d.shouldBeInDialCache("hostname")
if searchInDialCache("hostname") != "" {
t.Errorf("searchInDialCache")
}
addToDialCache("hostname", "1.1.1.1")
if searchInDialCache("hostname") != "1.1.1.1" {
t.Errorf("searchInDialCache")
}
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep replace replace replace replace replace replace replace replace keep keep keep replace replace replace replace replace replace keep keep
|
<mask> defer d.Close()
<mask> d.ParentalSensitivity = 3
<mask> d.checkMatch(t, "pornhub.com")
<mask> d.checkMatch(t, "pornhub.com")
<mask> if gctx.stats.Parental.Requests != 1 {
<mask> t.Errorf("Parental lookup positive cache is not working")
<mask> }
<mask> d.checkMatch(t, "PORNhub.com")
<mask> if gctx.stats.Parental.Requests != 1 {
<mask> t.Errorf("Parental lookup positive cache is not working")
<mask> }
<mask> d.checkMatch(t, "www.pornhub.com")
<mask> d.checkMatchEmpty(t, "www.yandex.ru")
<mask> d.checkMatchEmpty(t, "yandex.ru")
<mask> l := gctx.stats.Parental.Requests
<mask> d.checkMatchEmpty(t, "yandex.ru")
<mask> if gctx.stats.Parental.Requests != l {
<mask> t.Errorf("Parental lookup negative cache is not working")
<mask> }
<mask>
<mask> d.checkMatchEmpty(t, "api.jquery.com")
<mask> }
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> add // test cached result
d.parentalServer = "127.0.0.1"
d.checkMatch(t, "pornhub.com")
d.checkMatchEmpty(t, "yandex.ru")
d.parentalServer = defaultParentalServer </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove // Customize the Transport to have larger connection pool,
// We are not (re)using http.DefaultTransport because of race conditions found by tests
d.transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: defaultHTTPMaxIdleConnections, // default 100
MaxIdleConnsPerHost: defaultHTTPMaxIdleConnections, // default 2
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
if c != nil && len(c.ResolverAddress) != 0 {
d.transport.DialContext = d.createCustomDialContext(c.ResolverAddress)
}
d.client = http.Client{
Transport: d.transport,
Timeout: defaultHTTPTimeout,
</s> add err := d.initSecurityServices()
if err != nil {
log.Error("dnsfilter: initialize services: %s", err)
return nil </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep add keep keep keep keep keep
|
<mask> d.checkMatchEmpty(t, "yandex.ru")
<mask> d.checkMatchEmpty(t, "api.jquery.com")
<mask> }
<mask>
<mask> // FILTERING
<mask>
<mask> var blockingRules = "||example.org^\n"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove l := gctx.stats.Parental.Requests
d.checkMatchEmpty(t, "yandex.ru")
if gctx.stats.Parental.Requests != l {
t.Errorf("Parental lookup negative cache is not working")
}
</s> add </s> remove d.checkMatch(t, "pornhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
d.checkMatch(t, "PORNhub.com")
if gctx.stats.Parental.Requests != 1 {
t.Errorf("Parental lookup positive cache is not working")
}
</s> add </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove // CLIENTS SETTINGS
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep keep replace replace replace replace replace replace replace replace replace replace replace replace replace replace
|
<mask> }
<mask> }
<mask> })
<mask> }
<mask>
<mask> func TestDnsfilterDialCache(t *testing.T) {
<mask> d := Dnsfilter{}
<mask> gctx.dialCache = gcache.New(1).LRU().Expiration(30 * time.Minute).Build()
<mask>
<mask> d.shouldBeInDialCache("hostname")
<mask> if searchInDialCache("hostname") != "" {
<mask> t.Errorf("searchInDialCache")
<mask> }
<mask> addToDialCache("hostname", "1.1.1.1")
<mask> if searchInDialCache("hostname") != "1.1.1.1" {
<mask> t.Errorf("searchInDialCache")
<mask> }
<mask> }
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove
if len(c.ResolverAddress) != 0 && gctx.dialCache == nil {
dur := time.Duration(c.CacheTime) * time.Minute
gctx.dialCache = gcache.New(maxDialCacheSize).LRU().Expiration(dur).Build()
}
</s> add </s> remove testCases := []string{
"",
"sb.adtidy.org",
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("%s in %s", tc, _Func()), func(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "wmconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "WMconvirus.narod.ru")
if gctx.stats.Safebrowsing.Requests != 1 {
t.Errorf("Safebrowsing lookup positive cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
l := gctx.stats.Safebrowsing.Requests
d.checkMatchEmpty(t, "pornhub.com")
if gctx.stats.Safebrowsing.Requests != l {
t.Errorf("Safebrowsing lookup negative cache is not working: %v", gctx.stats.Safebrowsing.Requests)
}
})
}
</s> add d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
gctx.stats.Safebrowsing.Requests = 0
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatch(t, "test.wmconvirus.narod.ru")
d.checkMatchEmpty(t, "yandex.ru")
d.checkMatchEmpty(t, "pornhub.com")
// test cached result
d.safeBrowsingServer = "127.0.0.1"
d.checkMatch(t, "wmconvirus.narod.ru")
d.checkMatchEmpty(t, "pornhub.com")
d.safeBrowsingServer = defaultSafebrowsingServer </s> remove // the only way to verify that custom server option is working is to point it at a server that does serve safebrowsing
func TestSafeBrowsingCustomServerFail(t *testing.T) {
d := NewForTest(&Config{SafeBrowsingEnabled: true}, nil)
defer d.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// w.Write("Hello, client")
fmt.Fprintln(w, "Hello, client")
}))
defer ts.Close()
address := ts.Listener.Addr().String()
d.SetHTTPTimeout(time.Second * 5)
d.SetSafeBrowsingServer(address) // this will ensure that test fails
d.checkMatchEmpty(t, "wmconvirus.narod.ru")
}
</s> add </s> remove d := NewForTest(nil, nil)
defer d.Close()
_, ok := d.SafeSearchDomain("www.google.com")
if ok {
t.Errorf("Expected safesearch to error when disabled")
}
d = NewForTest(&Config{SafeSearchEnabled: true}, nil)
</s> add d := NewForTest(&Config{SafeSearchEnabled: true}, nil) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove if d != nil && d.transport != nil {
d.transport.CloseIdleConnections()
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/dnsfilter_test.go
|
keep keep keep add keep keep keep keep keep
|
<mask> package dnsfilter
<mask>
<mask> import (
<mask> "bufio"
<mask> "encoding/json"
<mask> "errors"
<mask> "fmt"
<mask> "io"
<mask> "net"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove "context"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/json"
</s> add </s> remove "bufio"
</s> add </s> add "net" </s> remove "net/http"
"net/http/httptest"
</s> add </s> remove // check safeSearch if no match
</s> add </s> remove // nothing matched, return nothing
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/security.go
|
keep keep add keep keep keep keep keep keep
|
<mask> "errors"
<mask> "fmt"
<mask> "io"
<mask> "net/http"
<mask> "strconv"
<mask> "strings"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/dnsproxy/upstream"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "time" </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> add "bytes"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/hex" </s> remove "net/http"
"net/http/httptest"
</s> add </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add </s> remove "context"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/json"
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/security.go
|
keep add keep keep keep keep keep keep
|
<mask> "strconv"
<mask> "strings"
<mask>
<mask> "github.com/AdguardTeam/dnsproxy/upstream"
<mask> "github.com/AdguardTeam/golibs/cache"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/miekg/dns"
<mask> "golang.org/x/net/publicsuffix"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> remove "github.com/bluele/gcache"
</s> add </s> add "github.com/miekg/dns"
"golang.org/x/net/publicsuffix" </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add </s> add "net" </s> remove "golang.org/x/net/publicsuffix"
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/security.go
|
keep keep keep add keep keep keep keep keep
|
<mask> "strconv"
<mask> "strings"
<mask> "time"
<mask>
<mask> "github.com/AdguardTeam/golibs/log"
<mask> "github.com/miekg/dns"
<mask> "golang.org/x/net/publicsuffix"
<mask> )
<mask>
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> add "time" </s> remove "github.com/bluele/gcache"
</s> add </s> add "net" </s> add "github.com/miekg/dns"
"golang.org/x/net/publicsuffix" </s> remove "golang.org/x/net/publicsuffix"
</s> add </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/security.go
|
keep keep add keep keep keep keep
|
<mask> "github.com/AdguardTeam/dnsproxy/upstream"
<mask> "github.com/AdguardTeam/golibs/cache"
<mask> "github.com/AdguardTeam/golibs/log"
<mask> )
<mask>
<mask> const dnsTimeout = 3 * time.Second
<mask> const defaultSafebrowsingServer = "https://dns-family.adguard.com/dns-query"
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove "github.com/bluele/gcache"
</s> add </s> remove "golang.org/x/net/publicsuffix"
</s> add </s> remove const defaultHTTPTimeout = 5 * time.Minute
const defaultHTTPMaxIdleConnections = 100
const defaultSafebrowsingServer = "sb.adtidy.org"
const defaultSafebrowsingURL = "%s://%s/safebrowsing-lookup-hash.html?prefixes=%s"
const defaultParentalServer = "pctrl.adguard.com"
const defaultParentalURL = "%s://%s/check-parental-control-hash?prefixes=%s&sensitivity=%d"
const defaultParentalSensitivity = 13 // use "TEEN" by default
const maxDialCacheSize = 2 // the number of host names for safebrowsing and parental control
</s> add </s> add "github.com/AdguardTeam/dnsproxy/upstream"
"github.com/AdguardTeam/golibs/cache" </s> add "time" </s> remove "sync/atomic"
"time"
"github.com/joomcode/errorx"
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
dnsfilter/security.go
|
keep keep keep keep replace keep replace
|
<mask> github.com/AdguardTeam/dnsproxy v0.19.6
<mask> github.com/AdguardTeam/golibs v0.2.4
<mask> github.com/AdguardTeam/urlfilter v0.6.1
<mask> github.com/NYTimes/gziphandler v1.1.1
<mask> github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833
<mask> github.com/etcd-io/bbolt v1.3.3
<mask> github.com/go-test/deep v1.0.4
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833 h1:yCfXxYaelOyqnia8F/Yng47qhmfC9nKTRIbYRrRueq4=
github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833/go.mod h1:8c4/i2VlovMO2gBnHGQPN5EJw+H0lx1u/5p+cgsXtCk=
</s> add </s> remove "context"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/json"
</s> add </s> remove log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeSearch: failed: %v", err) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
go.mod
|
keep keep keep keep replace replace keep keep keep keep keep
|
<mask> github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a h1:idn718Q4B6AGu/h5Sxe66HYVdqdGu2l9Iebqhi/AEoA=
<mask> github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY=
<mask> github.com/beefsack/go-rate v0.0.0-20180408011153-efa7637bb9b6 h1:KXlsf+qt/X5ttPGEjR0tPH1xaWWoKBEg9Q1THAj2h3I=
<mask> github.com/beefsack/go-rate v0.0.0-20180408011153-efa7637bb9b6/go.mod h1:6YNgTHLutezwnBvyneBbwvB8C82y3dcoOj5EQJIdGXA=
<mask> github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833 h1:yCfXxYaelOyqnia8F/Yng47qhmfC9nKTRIbYRrRueq4=
<mask> github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833/go.mod h1:8c4/i2VlovMO2gBnHGQPN5EJw+H0lx1u/5p+cgsXtCk=
<mask> github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
<mask> github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
<mask> github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
<mask> github.com/etcd-io/bbolt v1.3.3 h1:gSJmxrs37LgTqR/oyJBWok6k6SvXEUerFTbltIhXkBM=
<mask> github.com/etcd-io/bbolt v1.3.3/go.mod h1:ZF2nL25h33cCyBtcyWeZ2/I3HQOfTP+0PIEvHjkjCrw=
</s> + dnsfilter: use AG DNS server for SB/PC services
* move SS/SB/PC services to security.go
* remove old useless code (HTTP client) </s> remove github.com/bluele/gcache v0.0.0-20190518031135-bc40bd653833
</s> add </s> remove github.com/go-test/deep v1.0.4
</s> add github.com/go-test/deep v1.0.4 // indirect </s> remove "context"
"crypto/sha256"
"encoding/binary"
"encoding/gob"
"encoding/json"
</s> add </s> remove log.Printf("Failed to safesearch HTTP lookup, ignoring check: %v", err)
</s> add log.Info("SafeSearch: failed: %v", err) </s> remove //
// lifecycle helper functions
//
// Return TRUE if this host's IP should be cached
func (d *Dnsfilter) shouldBeInDialCache(host string) bool {
return host == d.safeBrowsingServer ||
host == d.parentalServer
}
// Search for an IP address by host name
func searchInDialCache(host string) string {
rawValue, err := gctx.dialCache.Get(host)
if err != nil {
return ""
}
ip, _ := rawValue.(string)
log.Debug("Found in cache: %s -> %s", host, ip)
return ip
}
// Add "hostname" -> "IP address" entry to cache
func addToDialCache(host, ip string) {
err := gctx.dialCache.Set(host, ip)
if err != nil {
log.Debug("dialCache.Set: %s", err)
}
log.Debug("Added to cache: %s -> %s", host, ip)
}
type dialFunctionType func(ctx context.Context, network, addr string) (net.Conn, error)
// Connect to a remote server resolving hostname using our own DNS server
func (d *Dnsfilter) createCustomDialContext(resolverAddr string) dialFunctionType {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
log.Tracef("network:%v addr:%v", network, addr)
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
con, err := dialer.DialContext(ctx, network, addr)
return con, err
}
cache := d.shouldBeInDialCache(host)
if cache {
ip := searchInDialCache(host)
if len(ip) != 0 {
addr = fmt.Sprintf("%s:%s", ip, port)
return dialer.DialContext(ctx, network, addr)
}
}
r := upstream.NewResolver(resolverAddr, 30*time.Second)
addrs, e := r.LookupIPAddr(ctx, host)
log.Tracef("LookupIPAddr: %s: %v", host, addrs)
if e != nil {
return nil, e
}
if len(addrs) == 0 {
return nil, fmt.Errorf("couldn't lookup host: %s", host)
}
var dialErrs []error
for _, a := range addrs {
addr = fmt.Sprintf("%s:%s", a.String(), port)
con, err := dialer.DialContext(ctx, network, addr)
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
if cache {
addToDialCache(host, a.String())
}
return con, err
}
return nil, errorx.DecorateMany(fmt.Sprintf("couldn't dial to %s", addr), dialErrs...)
}
}
</s> add </s> remove /*
expire byte[4]
res Result
*/
func (d *Dnsfilter) setCacheResult(cache cache.Cache, host string, res Result) {
var buf bytes.Buffer
expire := uint(time.Now().Unix()) + d.Config.CacheTime*60
var exp []byte
exp = make([]byte, 4)
binary.BigEndian.PutUint32(exp, uint32(expire))
_, _ = buf.Write(exp)
enc := gob.NewEncoder(&buf)
err := enc.Encode(res)
if err != nil {
log.Error("gob.Encode(): %s", err)
return
}
_ = cache.Set([]byte(host), buf.Bytes())
log.Debug("Stored in cache %p: %s", cache, host)
}
func getCachedResult(cache cache.Cache, host string) (Result, bool) {
data := cache.Get([]byte(host))
if data == nil {
return Result{}, false
}
exp := int(binary.BigEndian.Uint32(data[:4]))
if exp <= int(time.Now().Unix()) {
cache.Del([]byte(host))
return Result{}, false
}
var buf bytes.Buffer
buf.Write(data[4:])
dec := gob.NewDecoder(&buf)
r := Result{}
err := dec.Decode(&r)
if err != nil {
log.Debug("gob.Decode(): %s", err)
return Result{}, false
}
return r, true
}
// for each dot, hash it and add it to string
func hostnameToHashParam(host string, addslash bool) (string, map[string]bool) {
var hashparam bytes.Buffer
hashes := map[string]bool{}
tld, icann := publicsuffix.PublicSuffix(host)
if !icann {
// private suffixes like cloudfront.net
tld = ""
}
curhost := host
for {
if curhost == "" {
// we've reached end of string
break
}
if tld != "" && curhost == tld {
// we've reached the TLD, don't hash it
break
}
tohash := []byte(curhost)
if addslash {
tohash = append(tohash, '/')
}
sum := sha256.Sum256(tohash)
hexhash := fmt.Sprintf("%X", sum)
hashes[hexhash] = true
hashparam.WriteString(fmt.Sprintf("%02X%02X%02X%02X/", sum[0], sum[1], sum[2], sum[3]))
pos := strings.IndexByte(curhost, byte('.'))
if pos < 0 {
break
}
curhost = curhost[pos+1:]
}
return hashparam.String(), hashes
}
func (d *Dnsfilter) checkSafeSearch(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeSearch HTTP lookup for %s", host)
}
// Check cache. Return cached result if it was found
cachedValue, isFound := getCachedResult(gctx.safeSearchCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safesearch.CacheHits, 1)
log.Tracef("%s: found in SafeSearch cache", host)
return cachedValue, nil
}
safeHost, ok := d.SafeSearchDomain(host)
if !ok {
return Result{}, nil
}
res := Result{IsFiltered: true, Reason: FilteredSafeSearch}
if ip := net.ParseIP(safeHost); ip != nil {
res.IP = ip
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
// TODO this address should be resolved with upstream that was configured in dnsforward
addrs, err := net.LookupIP(safeHost)
if err != nil {
log.Tracef("SafeSearchDomain for %s was found but failed to lookup for %s cause %s", host, safeHost, err)
return Result{}, err
}
for _, i := range addrs {
if ipv4 := i.To4(); ipv4 != nil {
res.IP = ipv4
break
}
}
if len(res.IP) == 0 {
return Result{}, fmt.Errorf("no ipv4 addresses in safe search response for %s", safeHost)
}
// Cache result
d.setCacheResult(gctx.safeSearchCache, host, res)
return res, nil
}
func (d *Dnsfilter) checkSafeBrowsing(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("SafeBrowsing HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
url := fmt.Sprintf(defaultSafebrowsingURL, schema, d.safeBrowsingServer, hashparam)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
result := Result{}
scanner := bufio.NewScanner(strings.NewReader(string(body)))
for scanner.Scan() {
line := scanner.Text()
splitted := strings.Split(line, ":")
if len(splitted) < 3 {
continue
}
hash := splitted[2]
if _, ok := hashes[hash]; ok {
// it's in the hash
result.IsFiltered = true
result.Reason = FilteredSafeBrowsing
result.Rule = splitted[0]
break
}
}
if err := scanner.Err(); err != nil {
// error, don't save cache
return Result{}, err
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.safebrowsingCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Safebrowsing.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.safebrowsingCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Safebrowsing, true, format, handleBody)
if err == nil {
d.setCacheResult(gctx.safebrowsingCache, host, result)
}
return result, err
}
func (d *Dnsfilter) checkParental(host string) (Result, error) {
if log.GetLevel() >= log.DEBUG {
timer := log.StartTimer()
defer timer.LogElapsed("Parental HTTP lookup for %s", host)
}
format := func(hashparam string) string {
schema := "https"
if d.UsePlainHTTP {
schema = "http"
}
sensitivity := d.ParentalSensitivity
if sensitivity == 0 {
sensitivity = defaultParentalSensitivity
}
url := fmt.Sprintf(defaultParentalURL, schema, d.parentalServer, hashparam, sensitivity)
return url
}
handleBody := func(body []byte, hashes map[string]bool) (Result, error) {
// parse json
var m []struct {
Blocked bool `json:"blocked"`
ClientTTL int `json:"clientTtl"`
Reason string `json:"reason"`
Hash string `json:"hash"`
}
err := json.Unmarshal(body, &m)
if err != nil {
// error, don't save cache
log.Printf("Couldn't parse json '%s': %s", body, err)
return Result{}, err
}
result := Result{}
for i := range m {
if !hashes[m[i].Hash] {
continue
}
if m[i].Blocked {
result.IsFiltered = true
result.Reason = FilteredParental
result.Rule = fmt.Sprintf("parental %s", m[i].Reason)
break
}
}
return result, nil
}
// check cache
cachedValue, isFound := getCachedResult(gctx.parentalCache, host)
if isFound {
atomic.AddUint64(&gctx.stats.Parental.CacheHits, 1)
log.Tracef("%s: found in the lookup cache %p", host, gctx.parentalCache)
return cachedValue, nil
}
result, err := d.lookupCommon(host, &gctx.stats.Parental, false, format, handleBody)
if err == nil {
d.setCacheResult(gctx.parentalCache, host, result)
}
return result, err
}
type formatHandler func(hashparam string) string
type bodyHandler func(body []byte, hashes map[string]bool) (Result, error)
// real implementation of lookup/check
func (d *Dnsfilter) lookupCommon(host string, lookupstats *LookupStats, hashparamNeedSlash bool, format formatHandler, handleBody bodyHandler) (Result, error) {
// convert hostname to hash parameters
hashparam, hashes := hostnameToHashParam(host, hashparamNeedSlash)
// format URL with our hashes
url := format(hashparam)
// do HTTP request
atomic.AddUint64(&lookupstats.Requests, 1)
atomic.AddInt64(&lookupstats.Pending, 1)
updateMax(&lookupstats.Pending, &lookupstats.PendingMax)
resp, err := d.client.Get(url)
atomic.AddInt64(&lookupstats.Pending, -1)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
// error, don't save cache
return Result{}, err
}
// get body text
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// error, don't save cache
return Result{}, err
}
// handle status code
switch {
case resp.StatusCode == 204:
// empty result, save cache
return Result{}, nil
case resp.StatusCode != 200:
return Result{}, fmt.Errorf("HTTP status code: %d", resp.StatusCode)
}
result, err := handleBody(body, hashes)
if err != nil {
return Result{}, err
}
return result, nil
}
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7f69848084a68cdf1e227a555454991295fc5866
|
go.sum
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<mask> if ip == nil {
<mask> return 0, nil
<mask> }
<mask> val = ip
<mask> if ip.To4() != nil {
<mask> val = ip.To4()
<mask> }
<mask>
<mask> default:
<mask> return 0, nil
<mask> }
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> add return ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)) </s> remove func (s *statsCtx) getClientIP(clientIP string) string {
if s.conf.AnonymizeClientIP {
ip := net.ParseIP(clientIP)
if ip != nil {
ip4 := ip.To4()
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip4 != nil {
clientIP = ip4.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)).String()
} else {
clientIP = ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)).String()
}
</s> add func (s *statsCtx) getClientIP(ip net.IP) (clientIP net.IP) {
if s.conf.AnonymizeClientIP && ip != nil {
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip.To4() != nil {
return ip.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)) </s> remove func (l *queryLog) getClientIP(clientIP string) string {
if l.conf.AnonymizeClientIP {
ip := net.ParseIP(clientIP)
if ip != nil {
ip4 := ip.To4()
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip4 != nil {
clientIP = ip4.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)).String()
} else {
clientIP = ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)).String()
}
</s> add func (l *queryLog) getClientIP(ip net.IP) (clientIP net.IP) {
if l.conf.AnonymizeClientIP && ip != nil {
const AnonymizeClientIPv4Mask = 16
const AnonymizeClientIPv6Mask = 112
if ip.To4() != nil {
return ip.Mask(net.CIDRMask(AnonymizeClientIPv4Mask, 32)) </s> remove ip := dnsforward.IPStringFromAddr(d.Addr)
if ip == "" {
</s> add ip := dnsforward.IPFromAddr(d.Addr)
if ip == nil { </s> add func ipSliceOrNil(ip net.IP) []string {
if ip == nil {
return nil
}
return []string{ip.String()}
}
</s> remove assert.Equal(t, "1.2.3.4", net.IP(string(val)).String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(net.IP(val)))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/dhcpd.go
|
keep keep keep keep replace keep keep keep replace keep
|
<mask>
<mask> ll := s.srv4.GetLeases(LeasesAll)
<mask>
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:bb", ll[0].HWAddr.String())
<mask> assert.Equal(t, "192.168.10.101", ll[0].IP.String())
<mask> assert.EqualValues(t, leaseExpireStatic, ll[0].Expiry.Unix())
<mask>
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", ll[1].HWAddr.String())
<mask> assert.Equal(t, "192.168.10.100", ll[1].IP.String())
<mask> assert.Equal(t, exp1.Unix(), ll[1].Expiry.Unix())
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.152", ls[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 152}.Equal(ls[1].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask())))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/dhcpd_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> assert.EqualValues(t, 0, code)
<mask>
<mask> code, val = parseOptionString("123 ip 1.2.3.4")
<mask> assert.EqualValues(t, 123, code)
<mask> assert.Equal(t, "1.2.3.4", net.IP(string(val)).String())
<mask>
<mask> code, _ = parseOptionString("256 ip 1.1.1.1")
<mask> assert.EqualValues(t, 0, code)
<mask> code, _ = parseOptionString("-1 ip 1.1.1.1")
<mask> assert.EqualValues(t, 0, code)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "127.0.0.1", topClients[0])
</s> add assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0])) </s> remove if ip.To4() != nil {
val = ip.To4()
}
</s> add </s> remove assert.Equal(t, "192.168.10.100", ll[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(ll[1].IP)) </s> remove assert.Equal(t, "192.168.10.152", ls[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 152}.Equal(ls[1].IP)) </s> remove assert.Equal(t, "192.168.10.101", ll[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 101}.Equal(ll[0].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/dhcpd_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> }
<mask> }
<mask>
<mask> type v6ServerConfJSON struct {
<mask> RangeStart string `json:"range_start"`
<mask> LeaseDuration uint32 `json:"lease_duration"`
<mask> }
<mask>
<mask> func v6JSONToServerConf(j v6ServerConfJSON) V6ServerConf {
<mask> return V6ServerConf{
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove IP string `json:"ip"`
</s> add IP net.IP `json:"ip"` </s> remove IP string `json:"ip"`
</s> add IP net.IP `json:"ip"` </s> remove BindHost string `yaml:"bind_host"`
</s> add BindHost net.IP `yaml:"bind_host"` </s> remove Addresses []string `json:"ip_addresses"`
</s> add Addresses []net.IP `json:"ip_addresses"` </s> remove RangeStart string `yaml:"range_start" json:"range_start"`
</s> add RangeStart net.IP `yaml:"range_start"` </s> remove IP string `json:"IP"` // Client IP
</s> add IP net.IP `json:"IP"` // Client IP
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/dhcphttp.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> result.V4.StaticIP.Static = "error"
<mask> result.V4.StaticIP.Error = err.Error()
<mask> } else if !isStaticIP {
<mask> result.V4.StaticIP.Static = "no"
<mask> result.V4.StaticIP.IP = util.GetSubnet(interfaceName)
<mask> }
<mask>
<mask> if found4 {
<mask> result.V4.OtherServer.Found = "yes"
<mask> } else if err4 != nil {
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove } else if reqData.DNS.IP != "0.0.0.0" {
</s> add } else if !reqData.DNS.IP.IsUnspecified() { </s> remove resp.IP = util.GetSubnet(interfaceName)
</s> add resp.IP = util.GetSubnet(interfaceName).String() </s> remove } else if config.BindHost == "0.0.0.0" {
</s> add } else if config.BindHost.IsUnspecified() { </s> remove func (s *statsCtx) getClientIP(clientIP string) string {
if s.conf.AnonymizeClientIP {
ip := net.ParseIP(clientIP)
if ip != nil {
ip4 := ip.To4()
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip4 != nil {
clientIP = ip4.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)).String()
} else {
clientIP = ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)).String()
}
</s> add func (s *statsCtx) getClientIP(ip net.IP) (clientIP net.IP) {
if s.conf.AnonymizeClientIP && ip != nil {
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip.To4() != nil {
return ip.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)) </s> remove log.Printf("Go to %s://%s", proto, net.JoinHostPort(config.BindHost, port))
</s> add hostStr = config.BindHost.String()
log.Printf("Go to %s://%s", proto, net.JoinHostPort(hostStr, port)) </s> remove func (l *queryLog) getClientIP(clientIP string) string {
if l.conf.AnonymizeClientIP {
ip := net.ParseIP(clientIP)
if ip != nil {
ip4 := ip.To4()
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip4 != nil {
clientIP = ip4.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)).String()
} else {
clientIP = ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)).String()
}
</s> add func (l *queryLog) getClientIP(ip net.IP) (clientIP net.IP) {
if l.conf.AnonymizeClientIP && ip != nil {
const AnonymizeClientIPv4Mask = 16
const AnonymizeClientIPv6Mask = 112
if ip.To4() != nil {
return ip.Mask(net.CIDRMask(AnonymizeClientIPv4Mask, 32))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/dhcphttp.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> InterfaceName string `yaml:"-" json:"-"`
<mask>
<mask> // The first IP address for dynamic leases
<mask> // The last allowed IP address ends with 0xff byte
<mask> RangeStart string `yaml:"range_start" json:"range_start"`
<mask>
<mask> LeaseDuration uint32 `yaml:"lease_duration" json:"lease_duration"` // in seconds
<mask>
<mask> RaSlaacOnly bool `yaml:"ra_slaac_only" json:"-"` // send ICMPv6.RA packets without MO flags
<mask> RaAllowSlaac bool `yaml:"ra_allow_slaac" json:"-"` // send ICMPv6.RA packets with MO flags
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove Name string // Network interface name
MTU int // MTU
HardwareAddr string // Hardware address
Addresses []string // Array with the network interface addresses
Subnets []string // Array with CIDR addresses of this network interface
Flags string // Network interface flags (up, broadcast, etc)
</s> add Name string // Network interface name
MTU int // MTU
HardwareAddr string // Hardware address
Addresses []net.IP // Array with the network interface addresses
Subnets []*net.IPNet // Array with CIDR addresses of this network interface
Flags string // Network interface flags (up, broadcast, etc) </s> remove RangeStart string `json:"range_start"`
</s> add RangeStart net.IP `json:"range_start"` </s> remove bindHost string // host address to bind HTTP server on
</s> add bindHost net.IP // host address to bind HTTP server on </s> remove ClientIP string
</s> add ClientIP net.IP </s> remove IP string `json:"ip"`
</s> add IP net.IP `json:"ip"` </s> remove func (clients *clientsContainer) Exists(ip string, source clientSource) bool {
</s> add func (clients *clientsContainer) Exists(ip net.IP, source clientSource) bool {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/server.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> // check
<mask> ls = s.GetLeases(LeasesStatic)
<mask> assert.Len(t, ls, 1)
<mask> assert.Equal(t, "192.168.10.150", ls[0].IP.String())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", ls[0].HWAddr.String())
<mask> assert.EqualValues(t, leaseExpireStatic, ls[0].Expiry.Unix())
<mask>
<mask> // try to remove static lease - fail
<mask> l.IP = net.IP{192, 168, 10, 110}
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.100", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.152", ls[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 152}.Equal(ls[1].IP)) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep replace keep keep keep replace keep keep keep
|
<mask>
<mask> assert.Equal(t, "192.168.10.150", ls[0].IP.String())
<mask> assert.Equal(t, "33:aa:aa:aa:aa:aa", ls[0].HWAddr.String())
<mask> assert.EqualValues(t, leaseExpireStatic, ls[0].Expiry.Unix())
<mask>
<mask> assert.Equal(t, "192.168.10.152", ls[1].IP.String())
<mask> assert.Equal(t, "22:aa:aa:aa:aa:aa", ls[1].HWAddr.String())
<mask> assert.EqualValues(t, leaseExpireStatic, ls[1].Expiry.Unix())
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.100", ll[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(ll[1].IP)) </s> remove assert.Equal(t, "192.168.10.101", ll[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 101}.Equal(ll[0].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "127.0.0.1", topClients[0])
</s> add assert.True(t, net.IP{127, 0, 0, 1}.Equal(topClients[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep keep replace replace replace replace keep keep keep keep keep
|
<mask>
<mask> // check "Offer"
<mask> assert.Equal(t, dhcpv4.MessageTypeOffer, resp.MessageType())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", resp.ClientHWAddr.String())
<mask> assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
<mask> assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
<mask> assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
<mask> assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
<mask> assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds())
<mask>
<mask> // "Request"
<mask> req, _ = dhcpv4.NewRequestFromOffer(resp)
<mask> resp, _ = dhcpv4.NewReplyFromRequest(req)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.2.3.4", net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)]).String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)]))) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep replace replace replace replace keep keep keep keep replace
|
<mask> // check "Ack"
<mask> assert.Equal(t, dhcpv4.MessageTypeAck, resp.MessageType())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", resp.ClientHWAddr.String())
<mask> assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
<mask> assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
<mask> assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
<mask> assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
<mask> assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds())
<mask>
<mask> dnsAddrs := resp.DNS()
<mask> assert.Len(t, dnsAddrs, 1)
<mask> assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "1.2.3.4", net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)]).String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)])))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> // check lease
<mask> ls := s.GetLeases(LeasesStatic)
<mask> assert.Len(t, ls, 1)
<mask> assert.Equal(t, "192.168.10.150", ls[0].IP.String())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", ls[0].HWAddr.String())
<mask> }
<mask>
<mask> func TestV4DynamicLeaseGet(t *testing.T) {
<mask> conf := V4ServerConf{
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.100", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.152", ls[1].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 152}.Equal(ls[1].IP))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep replace replace replace replace keep keep replace keep keep keep
|
<mask> // check "Offer"
<mask> assert.Equal(t, dhcpv4.MessageTypeOffer, resp.MessageType())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", resp.ClientHWAddr.String())
<mask> assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
<mask> assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
<mask> assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
<mask> assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
<mask> assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds())
<mask> assert.Equal(t, []byte("012"), resp.Options[uint8(dhcpv4.OptionFQDN)])
<mask> assert.Equal(t, "1.2.3.4", net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)]).String())
<mask>
<mask> // "Request"
<mask> req, _ = dhcpv4.NewRequestFromOffer(resp)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep keep replace replace replace replace keep keep keep keep replace keep keep keep
|
<mask>
<mask> // check "Ack"
<mask> assert.Equal(t, dhcpv4.MessageTypeAck, resp.MessageType())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", resp.ClientHWAddr.String())
<mask> assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
<mask> assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
<mask> assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
<mask> assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
<mask> assert.Equal(t, s.conf.leaseTime.Seconds(), resp.IPAddressLeaseTime(-1).Seconds())
<mask>
<mask> dnsAddrs := resp.DNS()
<mask> assert.Len(t, dnsAddrs, 1)
<mask> assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
<mask>
<mask> // check lease
<mask> ls := s.GetLeases(LeasesDynamic)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "192.168.10.150", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask()))) </s> remove assert.Equal(t, "1.2.3.4", net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)]).String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(net.IP(resp.Options[uint8(dhcpv4.OptionRelayAgentInformation)])))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> // check lease
<mask> ls := s.GetLeases(LeasesDynamic)
<mask> assert.Len(t, ls, 1)
<mask> assert.Equal(t, "192.168.10.100", ls[0].IP.String())
<mask> assert.Equal(t, "aa:aa:aa:aa:aa:aa", ls[0].HWAddr.String())
<mask>
<mask> start := net.IP{192, 168, 10, 100}
<mask> stop := net.IP{192, 168, 10, 200}
<mask> assert.False(t, ip4InRange(start, stop, net.IP{192, 168, 10, 99}))
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.1", dnsAddrs[0].String())
</s> add assert.True(t, net.IP{192, 168, 10, 1}.Equal(dnsAddrs[0])) </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.Equal(t, "192.168.10.100", resp.YourIPAddr.String())
assert.Equal(t, "192.168.10.1", resp.Router()[0].String())
assert.Equal(t, "192.168.10.1", resp.ServerIdentifier().String())
assert.Equal(t, "255.255.255.0", net.IP(resp.SubnetMask()).String())
</s> add assert.True(t, net.IP{192, 168, 10, 100}.Equal(resp.YourIPAddr))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.Router()[0]))
assert.True(t, net.IP{192, 168, 10, 1}.Equal(resp.ServerIdentifier()))
assert.True(t, net.IP{255, 255, 255, 0}.Equal(net.IP(resp.SubnetMask())))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v4_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> if !conf.Enabled {
<mask> return s, nil
<mask> }
<mask>
<mask> s.conf.ipStart = net.ParseIP(conf.RangeStart)
<mask> if s.conf.ipStart == nil || s.conf.ipStart.To16() == nil {
<mask> return s, fmt.Errorf("dhcpv6: invalid range-start IP: %s", conf.RangeStart)
<mask> }
<mask>
<mask> if conf.LeaseDuration == 0 {
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove if len(ent.IP) == 0 {
ent.IP = v
</s> add if ent.IP == nil {
ent.IP = net.ParseIP(v) </s> add func ipSliceOrNil(ip net.IP) []string {
if ip == nil {
return nil
}
return []string{ip.String()}
}
</s> remove ip := util.GetSubnet(ifaceName)
if len(ip) == 0 {
</s> add ipNet := util.GetSubnet(ifaceName)
if ipNet.IP == nil { </s> remove return clientIP
</s> add return ip </s> remove if ip.To4() != nil {
val = ip.To4()
}
</s> add </s> remove client := s.getClientIP(e.Client.String())
</s> add client := s.getClientIP(e.Client)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v6.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> func TestV6StaticLeaseAddRemove(t *testing.T) {
<mask> conf := V6ServerConf{
<mask> Enabled: true,
<mask> RangeStart: "2001::1",
<mask> notify: notify6,
<mask> }
<mask> s, err := v6Create(conf)
<mask> assert.Nil(t, err)
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::2",
</s> add RangeStart: net.ParseIP("2001::2"), </s> remove s.conf.FilterHandler = func(_ string, settings *dnsfilter.RequestFilteringSettings) {
</s> add s.conf.FilterHandler = func(_ net.IP, settings *dnsfilter.RequestFilteringSettings) { </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.True(t, clients.Exists("1.1.1.1", ClientSourceHostsFile))
</s> add assert.True(t, clients.Exists(net.IPv4(1, 1, 1, 1), ClientSourceHostsFile))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v6_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> func TestV6StaticLeaseAddReplaceDynamic(t *testing.T) {
<mask> conf := V6ServerConf{
<mask> Enabled: true,
<mask> RangeStart: "2001::1",
<mask> notify: notify6,
<mask> }
<mask> sIface, err := v6Create(conf)
<mask> s := sIface.(*v6Server)
<mask> assert.Nil(t, err)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::2",
</s> add RangeStart: net.ParseIP("2001::2"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove s.conf.FilterHandler = func(_ string, settings *dnsfilter.RequestFilteringSettings) {
</s> add s.conf.FilterHandler = func(_ net.IP, settings *dnsfilter.RequestFilteringSettings) { </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.True(t, clients.Exists("1.1.1.1", ClientSourceHostsFile))
</s> add assert.True(t, clients.Exists(net.IPv4(1, 1, 1, 1), ClientSourceHostsFile))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v6_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> func TestV6GetLease(t *testing.T) {
<mask> conf := V6ServerConf{
<mask> Enabled: true,
<mask> RangeStart: "2001::1",
<mask> notify: notify6,
<mask> }
<mask> sIface, err := v6Create(conf)
<mask> s := sIface.(*v6Server)
<mask> assert.Nil(t, err)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::2",
</s> add RangeStart: net.ParseIP("2001::2"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove s.conf.FilterHandler = func(_ string, settings *dnsfilter.RequestFilteringSettings) {
</s> add s.conf.FilterHandler = func(_ net.IP, settings *dnsfilter.RequestFilteringSettings) { </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.True(t, clients.Exists("1.1.1.1", ClientSourceHostsFile))
</s> add assert.True(t, clients.Exists(net.IPv4(1, 1, 1, 1), ClientSourceHostsFile))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v6_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> func TestV6GetDynamicLease(t *testing.T) {
<mask> conf := V6ServerConf{
<mask> Enabled: true,
<mask> RangeStart: "2001::2",
<mask> notify: notify6,
<mask> }
<mask> sIface, err := v6Create(conf)
<mask> s := sIface.(*v6Server)
<mask> assert.Nil(t, err)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove s.conf.FilterHandler = func(_ string, settings *dnsfilter.RequestFilteringSettings) {
</s> add s.conf.FilterHandler = func(_ net.IP, settings *dnsfilter.RequestFilteringSettings) { </s> remove assert.Equal(t, "192.168.10.150", ls[0].IP.String())
</s> add assert.True(t, net.IP{192, 168, 10, 150}.Equal(ls[0].IP)) </s> remove assert.True(t, clients.Exists("1.1.1.1", ClientSourceHostsFile))
</s> add assert.True(t, clients.Exists(net.IPv4(1, 1, 1, 1), ClientSourceHostsFile))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dhcpd/v6_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> SafeBrowsingEnabled bool
<mask> ParentalEnabled bool
<mask>
<mask> ClientName string
<mask> ClientIP string
<mask> ClientTags []string
<mask>
<mask> ServicesRules []ServiceEntry
<mask> }
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove IP string `json:"ip"`
</s> add IP net.IP `json:"ip"` </s> remove bindHost string // host address to bind HTTP server on
</s> add bindHost net.IP // host address to bind HTTP server on </s> remove RangeStart string `yaml:"range_start" json:"range_start"`
</s> add RangeStart net.IP `yaml:"range_start"` </s> remove BindHost string
</s> add BindHost net.IP </s> remove Addresses []string `json:"ip_addresses"`
</s> add Addresses []net.IP `json:"ip_addresses"` </s> remove func assertLogEntry(t *testing.T, entry *logEntry, host, answer, client string) bool {
</s> add func assertLogEntry(t *testing.T, entry *logEntry, host string, answer, client net.IP) bool {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/dnsfilter.go
|
keep keep keep keep replace replace replace keep keep keep keep keep
|
<mask>
<mask> ureq := urlfilter.DNSRequest{
<mask> Hostname: host,
<mask> SortedClientTags: setts.ClientTags,
<mask> ClientIP: setts.ClientIP,
<mask> ClientName: setts.ClientName,
<mask> DNSType: qtype,
<mask> }
<mask>
<mask> if d.filteringEngineAllow != nil {
<mask> dnsres, ok := d.filteringEngineAllow.MatchRequest(ureq)
<mask> if ok {
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove _, ok := a.disallowedClients[ip]
</s> add _, ok := a.disallowedClients[ipStr] </s> remove _, ok := a.allowedClients[ip]
</s> add _, ok := a.allowedClients[ipStr] </s> remove c, ok := clients.idIndex[ip]
</s> add c, ok := clients.idIndex[ip.String()] </s> remove return true, ip
</s> add return true, ipStr </s> remove c, ok := clients.findByIP(ip)
</s> add c, ok := clients.findByIP(net.ParseIP(ip)) </s> remove if len(ent.IP) == 0 {
ent.IP = v
</s> add if ent.IP == nil {
ent.IP = net.ParseIP(v)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/dnsfilter.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match exact
<mask> r := d.processRewrites("host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "1.1.1.1", r.IPList[0].String())
<mask>
<mask> // match L2
<mask> r = d.processRewrites("sub.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "3.3.3.3", r.IPList[0].String())
</s> add assert.True(t, net.IP{3, 3, 3, 3}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "127.0.0.2", ips[0].String())
</s> add assert.True(t, net.IP{127, 0, 0, 2}.Equal(ips[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match L2
<mask> r = d.processRewrites("sub.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "2.2.2.2", r.IPList[0].String())
<mask>
<mask> // match L3
<mask> r = d.processRewrites("my.sub.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.1.1.1", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 1, 1, 1}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "3.3.3.3", r.IPList[0].String())
</s> add assert.True(t, net.IP{3, 3, 3, 3}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "127.0.0.2", ips[0].String())
</s> add assert.True(t, net.IP{127, 0, 0, 2}.Equal(ips[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match L3
<mask> r = d.processRewrites("my.sub.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "3.3.3.3", r.IPList[0].String())
<mask> }
<mask>
<mask> func TestRewritesExceptionCNAME(t *testing.T) {
<mask> d := DNSFilter{}
<mask> // wildcard; exception for a sub-domain
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.1.1.1", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 1, 1, 1}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "127.0.0.2", ips[0].String())
</s> add assert.True(t, net.IP{127, 0, 0, 2}.Equal(ips[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match sub-domain
<mask> r := d.processRewrites("my.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "2.2.2.2", r.IPList[0].String())
<mask>
<mask> // match sub-domain, but handle exception
<mask> r = d.processRewrites("sub.host.com", dns.TypeA)
<mask> assert.Equal(t, NotFilteredNotFound, r.Reason)
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.1.1.1", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 1, 1, 1}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "3.3.3.3", r.IPList[0].String())
</s> add assert.True(t, net.IP{3, 3, 3, 3}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "127.0.0.2", ips[0].String())
</s> add assert.True(t, net.IP{127, 0, 0, 2}.Equal(ips[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match sub-domain
<mask> r := d.processRewrites("my.host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "2.2.2.2", r.IPList[0].String())
<mask>
<mask> // match sub-domain, but handle exception
<mask> r = d.processRewrites("my.sub.host.com", dns.TypeA)
<mask> assert.Equal(t, NotFilteredNotFound, r.Reason)
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.1.1.1", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 1, 1, 1}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "3.3.3.3", r.IPList[0].String())
</s> add assert.True(t, net.IP{3, 3, 3, 3}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "127.0.0.2", ips[0].String())
</s> add assert.True(t, net.IP{127, 0, 0, 2}.Equal(ips[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> // match domain
<mask> r := d.processRewrites("host.com", dns.TypeA)
<mask> assert.Equal(t, Rewritten, r.Reason)
<mask> assert.Len(t, r.IPList, 1)
<mask> assert.Equal(t, "1.2.3.4", r.IPList[0].String())
<mask>
<mask> // match exception
<mask> r = d.processRewrites("host.com", dns.TypeAAAA)
<mask> assert.Equal(t, NotFilteredNotFound, r.Reason)
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.1.1.1", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 1, 1, 1}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "2.2.2.2", r.IPList[0].String())
</s> add assert.True(t, net.IP{2, 2, 2, 2}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "3.3.3.3", r.IPList[0].String())
</s> add assert.True(t, net.IP{3, 3, 3, 3}.Equal(r.IPList[0])) </s> remove assert.Equal(t, "1.2.3.4", a.A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(a.A))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsfilter/rewrites_test.go
|
keep keep keep keep replace keep keep keep keep replace keep keep keep keep
|
<mask> // IsBlockedIP - return TRUE if this client should be blocked
<mask> // Returns the item from the "disallowedClients" list that lead to blocking IP.
<mask> // If it returns TRUE and an empty string, it means that the "allowedClients" is not empty,
<mask> // but the ip does not belong to it.
<mask> func (a *accessCtx) IsBlockedIP(ip string) (bool, string) {
<mask> a.lock.Lock()
<mask> defer a.lock.Unlock()
<mask>
<mask> if len(a.allowedClients) != 0 || len(a.allowedClientsIPNet) != 0 {
<mask> _, ok := a.allowedClients[ip]
<mask> if ok {
<mask> return false, ""
<mask> }
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove func (s *Server) IsBlockedIP(ip string) (bool, string) {
</s> add func (s *Server) IsBlockedIP(ip net.IP) (bool, string) { </s> remove // GetSubnet - Get IP address with netmask for the specified interface
// Returns an empty string if it fails to find it
func GetSubnet(ifaceName string) string {
</s> add // GetSubnet returns pointer to net.IPNet for the specified interface or nil if
// the search fails.
func GetSubnet(ifaceName string) *net.IPNet { </s> remove func (clients *clientsContainer) findTemporary(ip string) (cj clientJSON, found bool) {
</s> add func (clients *clientsContainer) findTemporary(ip net.IP) (cj clientJSON, found bool) {
ipStr := ip.String() </s> remove _, ok := a.disallowedClients[ip]
</s> add _, ok := a.disallowedClients[ipStr] </s> remove ipAddr := net.ParseIP(ip)
</s> add
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access.go
|
keep replace keep replace keep keep keep keep
|
<mask> if len(a.allowedClientsIPNet) != 0 {
<mask> ipAddr := net.ParseIP(ip)
<mask> for _, ipnet := range a.allowedClientsIPNet {
<mask> if ipnet.Contains(ipAddr) {
<mask> return false, ""
<mask> }
<mask> }
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove if ipnet.Contains(ipAddr) {
</s> add if ipnet.Contains(ip) { </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove return true, ip
</s> add return true, ipStr </s> remove _, ok := a.allowedClients[ip]
</s> add _, ok := a.allowedClients[ipStr] </s> remove topClients := Context.stats.GetTopClientsIP(topClientsNumber)
for _, ip := range topClients {
ipAddr := net.ParseIP(ip)
if !ipAddr.IsLoopback() {
</s> add for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
if !ip.IsLoopback() {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> return true, ""
<mask> }
<mask>
<mask> _, ok := a.disallowedClients[ip]
<mask> if ok {
<mask> return true, ip
<mask> }
<mask>
<mask> if len(a.disallowedClientsIPNet) != 0 {
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove return true, ip
</s> add return true, ipStr </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove if ipnet.Contains(ipAddr) {
</s> add if ipnet.Contains(ip) { </s> remove _, ok := a.allowedClients[ip]
</s> add _, ok := a.allowedClients[ipStr] </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove c, ok := clients.idIndex[ip]
</s> add c, ok := clients.idIndex[ip.String()]
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access.go
|
keep replace keep keep keep replace keep keep
|
<mask> if ok {
<mask> return true, ip
<mask> }
<mask>
<mask> if len(a.disallowedClientsIPNet) != 0 {
<mask> ipAddr := net.ParseIP(ip)
<mask> for _, ipnet := range a.disallowedClientsIPNet {
<mask> if ipnet.Contains(ipAddr) {
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove if ipnet.Contains(ipAddr) {
</s> add if ipnet.Contains(ip) { </s> remove if ipnet.Contains(ipAddr) {
</s> add if ipnet.Contains(ip) { </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove _, ok := a.disallowedClients[ip]
</s> add _, ok := a.disallowedClients[ipStr] </s> remove topClients := Context.stats.GetTopClientsIP(topClientsNumber)
for _, ip := range topClients {
ipAddr := net.ParseIP(ip)
if !ipAddr.IsLoopback() {
</s> add for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
if !ip.IsLoopback() {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> if len(a.disallowedClientsIPNet) != 0 {
<mask> ipAddr := net.ParseIP(ip)
<mask> for _, ipnet := range a.disallowedClientsIPNet {
<mask> if ipnet.Contains(ipAddr) {
<mask> return true, ipnet.String()
<mask> }
<mask> }
<mask> }
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove return true, ip
</s> add return true, ipStr </s> remove if ipnet.Contains(ipAddr) {
</s> add if ipnet.Contains(ip) { </s> remove ipAddr := net.ParseIP(ip)
</s> add </s> remove _, ok := a.disallowedClients[ip]
</s> add _, ok := a.disallowedClients[ipStr] </s> remove topClients := Context.stats.GetTopClientsIP(topClientsNumber)
for _, ip := range topClients {
ipAddr := net.ParseIP(ip)
if !ipAddr.IsLoopback() {
</s> add for _, ip := range Context.stats.GetTopClientsIP(topClientsNumber) {
if !ip.IsLoopback() {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access.go
|
keep keep add keep keep keep keep
|
<mask> package dnsforward
<mask>
<mask> import (
<mask> "testing"
<mask>
<mask> "github.com/stretchr/testify/assert"
<mask> )
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> add "net" </s> add "net" </s> add "net" </s> add "net" </s> add "net" </s> remove // TODO(e.burkov): remove this weird buildtag.
</s> add // TODO(e.burkov): Remove this weird buildtag.
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access_test.go
|
keep replace keep keep keep replace
|
<mask>
<mask> disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
<mask> assert.False(t, disallowed)
<mask> assert.Empty(t, disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
</s> add disallowed, disallowedRule := a.IsBlockedIP(net.IPv4(1, 1, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 3, 1, 1))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access_test.go
|
keep keep replace keep keep keep replace keep keep keep
|
<mask> assert.Empty(t, disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
<mask> assert.False(t, disallowed)
<mask> assert.Empty(t, disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
<mask> assert.True(t, disallowed)
<mask> assert.Empty(t, disallowedRule)
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 3, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
</s> add disallowed, disallowedRule := a.IsBlockedIP(net.IPv4(1, 1, 1, 1))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access_test.go
|
keep replace keep keep keep replace keep keep keep
|
<mask>
<mask> disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
<mask> assert.True(t, disallowed)
<mask> assert.Equal(t, "1.1.1.1", disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
<mask> assert.False(t, disallowed)
<mask> assert.Empty(t, disallowedRule)
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
</s> add disallowed, disallowedRule := a.IsBlockedIP(net.IPv4(1, 1, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 3, 1, 1))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access_test.go
|
keep keep replace keep keep keep replace keep keep keep keep
|
<mask> assert.Empty(t, disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
<mask> assert.True(t, disallowed)
<mask> assert.Equal(t, "2.2.0.0/16", disallowedRule)
<mask>
<mask> disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
<mask> assert.False(t, disallowed)
<mask> assert.Empty(t, disallowedRule)
<mask> }
<mask>
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.2.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 2, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("2.3.1.1")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(2, 3, 1, 1)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule = a.IsBlockedIP("1.1.1.2")
</s> add disallowed, disallowedRule = a.IsBlockedIP(net.IPv4(1, 1, 1, 2)) </s> remove disallowed, disallowedRule := a.IsBlockedIP("1.1.1.1")
</s> add disallowed, disallowedRule := a.IsBlockedIP(net.IPv4(1, 1, 1, 1))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/access_test.go
|
keep keep keep keep replace keep keep keep replace keep
|
<mask> // Callbacks for other modules
<mask> // --
<mask>
<mask> // Filtering callback function
<mask> FilterHandler func(clientAddr string, settings *dnsfilter.RequestFilteringSettings) `yaml:"-"`
<mask>
<mask> // GetCustomUpstreamByClient - a callback function that returns upstreams configuration
<mask> // based on the client IP address. Returns nil if there are no custom upstreams for the client
<mask> // TODO(e.burkov): replace argument type with net.IP.
<mask> GetCustomUpstreamByClient func(clientAddr string) *proxy.UpstreamConfig `yaml:"-"`
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove func (a *accessCtx) IsBlockedIP(ip string) (bool, string) {
</s> add func (a *accessCtx) IsBlockedIP(ip net.IP) (bool, string) {
ipStr := ip.String()
</s> remove // GetSubnet - Get IP address with netmask for the specified interface
// Returns an empty string if it fails to find it
func GetSubnet(ifaceName string) string {
</s> add // GetSubnet returns pointer to net.IPNet for the specified interface or nil if
// the search fails.
func GetSubnet(ifaceName string) *net.IPNet { </s> remove // TODO(e.burkov): this should removed with the API v1 when the appropriate
</s> add // TODO(e.burkov): This should removed with the API v1 when the appropriate </s> remove BindHost string `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to
</s> add BindHost net.IP `yaml:"bind_host"` // BindHost is the IP address of the HTTP server to bind to </s> remove // GetInterfaceByIP - Get interface name by its IP address.
func GetInterfaceByIP(ip string) string {
</s> add // GetInterfaceByIP returns the name of interface containing provided ip.
func GetInterfaceByIP(ip net.IP) string {
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/config.go
|
keep keep keep keep replace keep keep
|
<mask> }
<mask> }
<mask>
<mask> // IsBlockedIP - return TRUE if this client should be blocked
<mask> func (s *Server) IsBlockedIP(ip string) (bool, string) {
<mask> return s.access.IsBlockedIP(ip)
<mask> }
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove func (a *accessCtx) IsBlockedIP(ip string) (bool, string) {
</s> add func (a *accessCtx) IsBlockedIP(ip net.IP) (bool, string) {
ipStr := ip.String()
</s> remove ip := IPStringFromAddr(d.Addr)
</s> add ip := IPFromAddr(d.Addr) </s> remove clientAddr := IPStringFromAddr(d.Addr)
s.conf.FilterHandler(clientAddr, &setts)
</s> add s.conf.FilterHandler(IPFromAddr(d.Addr), &setts) </s> remove func (s *statsCtx) GetTopClientsIP(maxCount uint) []string {
</s> add func (s *statsCtx) GetTopClientsIP(maxCount uint) []net.IP { </s> remove func (s *statsCtx) getClientIP(clientIP string) string {
if s.conf.AnonymizeClientIP {
ip := net.ParseIP(clientIP)
if ip != nil {
ip4 := ip.To4()
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip4 != nil {
clientIP = ip4.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)).String()
} else {
clientIP = ip.Mask(net.CIDRMask(AnonymizeClientIP6Mask, 128)).String()
}
</s> add func (s *statsCtx) getClientIP(ip net.IP) (clientIP net.IP) {
if s.conf.AnonymizeClientIP && ip != nil {
const AnonymizeClientIP4Mask = 16
const AnonymizeClientIP6Mask = 112
if ip.To4() != nil {
return ip.Mask(net.CIDRMask(AnonymizeClientIP4Mask, 32)) </s> remove return clientIP
</s> add return ip
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> assert.Nil(t, err)
<mask> assert.Equal(t, dns.RcodeSuccess, reply.Rcode)
<mask> assert.NotNil(t, reply.Answer)
<mask> assert.Equal(t, "192.168.0.1", reply.Answer[0].(*dns.A).A.String())
<mask> assert.Nil(t, s.Stop())
<mask> }
<mask>
<mask> // testUpstream is a mock of real upstream.
<mask> // specify fields with necessary values to simulate real upstream behaviour
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.2.3.4", a.A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(a.A)) </s> remove assert.Equal(t, "1.2.3.4", reply.Answer[1].(*dns.A).A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(reply.Answer[1].(*dns.A).A)) </s> remove assert.Equal(t, answer, ip.String())
</s> add assert.Equal(t, answer, ip) </s> remove ip := proxyutil.GetIPFromDNSRecord(msg.Answer[0])
</s> add ip := proxyutil.GetIPFromDNSRecord(msg.Answer[0]).To16() </s> remove c, b := clients.Find("1.1.1.2")
</s> add c, b := clients.Find(net.IPv4(1, 1, 1, 2)) </s> remove assert.Equal(t, "127.0.0.1", DNSUnreverseAddr("1.0.0.127.in-addr.arpa").String())
</s> add assert.True(t, net.IP{127, 0, 0, 1}.Equal(DNSUnreverseAddr("1.0.0.127.in-addr.arpa")))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask>
<mask> func TestClientRulesForCNAMEMatching(t *testing.T) {
<mask> s := createTestServer(t)
<mask> testUpstm := &testUpstream{testCNAMEs, testIPv4, nil}
<mask> s.conf.FilterHandler = func(_ string, settings *dnsfilter.RequestFilteringSettings) {
<mask> settings.FilteringEnabled = false
<mask> }
<mask> err := s.startWithUpstream(testUpstm)
<mask> assert.Nil(t, err)
<mask> addr := s.dnsProxy.Addr(proxy.ProtoUDP)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove RangeStart: "2001::2",
</s> add RangeStart: net.ParseIP("2001::2"), </s> remove RangeStart: "2001::1",
</s> add RangeStart: net.ParseIP("2001::1"), </s> remove if ip == addr {
</s> add if ip.Equal(addr) { </s> remove macFound := clients.dhcpServer.FindMACbyIP(ipAddr)
</s> add macFound := clients.dhcpServer.FindMACbyIP(ip)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> assert.Nil(t, err)
<mask> assert.Len(t, reply.Answer, 1)
<mask> a, ok := reply.Answer[0].(*dns.A)
<mask> assert.True(t, ok)
<mask> assert.Equal(t, "0.0.0.1", a.A.String())
<mask>
<mask> req = createTestMessageWithType("null.example.org.", dns.TypeAAAA)
<mask> reply, err = dns.Exchange(req, addr.String())
<mask> assert.Nil(t, err)
<mask> assert.Len(t, reply.Answer, 1)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.2.3.4", a.A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(a.A)) </s> remove assert.Equal(t, "1.2.3.4", reply.Answer[1].(*dns.A).A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(reply.Answer[1].(*dns.A).A)) </s> remove c, b := clients.Find("1.1.1.2")
</s> add c, b := clients.Find(net.IPv4(1, 1, 1, 2)) </s> remove ip := proxyutil.GetIPFromDNSRecord(msg.Answer[0])
</s> add ip := proxyutil.GetIPFromDNSRecord(msg.Answer[0]).To16() </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove assert.Equal(t, answer, ip.String())
</s> add assert.Equal(t, answer, ip)
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> assert.Nil(t, err)
<mask> assert.Len(t, reply.Answer, 1)
<mask> a, ok := reply.Answer[0].(*dns.A)
<mask> assert.True(t, ok)
<mask> assert.Equal(t, "1.2.3.4", a.A.String())
<mask>
<mask> req = createTestMessageWithType("test.com.", dns.TypeAAAA)
<mask> reply, err = dns.Exchange(req, addr.String())
<mask> assert.Nil(t, err)
<mask> assert.Empty(t, reply.Answer)
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "0.0.0.1", a.A.String())
</s> add assert.True(t, net.IP{0, 0, 0, 1}.Equal(a.A)) </s> remove assert.Equal(t, "1.2.3.4", reply.Answer[1].(*dns.A).A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(reply.Answer[1].(*dns.A).A)) </s> remove c, b := clients.Find("1.1.1.2")
</s> add c, b := clients.Find(net.IPv4(1, 1, 1, 2)) </s> remove assert.Equal(t, "192.168.0.1", reply.Answer[0].(*dns.A).A.String())
</s> add assert.True(t, net.IP{192, 168, 0, 1}.Equal(reply.Answer[0].(*dns.A).A)) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0])) </s> remove c, b = clients.Find("1.1.1.1")
</s> add c, b = clients.Find(net.IPv4(1, 1, 1, 1))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward_test.go
|
keep keep keep keep replace keep keep keep keep keep
|
<mask> reply, err = dns.Exchange(req, addr.String())
<mask> assert.Nil(t, err)
<mask> assert.Len(t, reply.Answer, 2)
<mask> assert.Equal(t, "test.com.", reply.Answer[0].(*dns.CNAME).Target)
<mask> assert.Equal(t, "1.2.3.4", reply.Answer[1].(*dns.A).A.String())
<mask>
<mask> req = createTestMessageWithType("my.alias.example.org.", dns.TypeA)
<mask> reply, err = dns.Exchange(req, addr.String())
<mask> assert.Nil(t, err)
<mask> assert.Equal(t, "my.alias.example.org.", reply.Question[0].Name) // the original question is restored
</s> Pull request: 2508 ip conversion vol.2
Merge in DNS/adguard-home from 2508-ip-conversion-vol2 to master
Closes #2508.
Squashed commit of the following:
commit 5b9d33f9cd352756831f63e34c4aea48674628c1
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:15:17 2021 +0300
util: replace net.IPNet with pointer
commit 680126de7d59464077f9edf1bbaa925dd3fcee19
Merge: d3ba6a6c 5a50efad
Author: Eugene Burkov <[email protected]>
Date: Wed Jan 20 17:02:41 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit d3ba6a6cdd01c0aa736418fdb86ed40120169fe9
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 18:29:54 2021 +0300
all: remove last conversion
commit 88b63f11a6c3f8705d7fa0c448c50dd646cc9214
Author: Eugene Burkov <[email protected]>
Date: Tue Jan 19 14:12:45 2021 +0300
all: improve code quality
commit 71af60c70a0dbaf55e2221023d6d2e4993c9e9a7
Merge: 98af3784 9f75725d
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 17:13:27 2021 +0300
Merge branch 'master' into 2508-ip-conversion-vol2
commit 98af3784ce44d0993d171653c13d6e83bb8d1e6a
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:32:53 2021 +0300
all: log changes
commit e99595a172bae1e844019d344544be84ddd65e4e
Author: Eugene Burkov <[email protected]>
Date: Mon Jan 18 16:06:49 2021 +0300
all: fix or remove remaining net.IP <-> string conversions
commit 7fd0634ce945f7e4c9b856684c5199f8a84a543e
Author: Eugene Burkov <[email protected]>
Date: Fri Jan 15 15:36:17 2021 +0300
all: remove redundant net.IP <-> string converions
commit 5df8af030421237d41b67ed659f83526cc258199
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:35:25 2021 +0300
stats: remove redundant net.IP <-> string conversion
commit fbe4e3fc015e6898063543a90c04401d76dbb18f
Author: Eugene Burkov <[email protected]>
Date: Thu Jan 14 16:20:35 2021 +0300
querylog: remove redundant net.IP <-> string conversion </s> remove assert.Equal(t, "1.2.3.4", a.A.String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(a.A)) </s> remove assert.Equal(t, "0.0.0.1", a.A.String())
</s> add assert.True(t, net.IP{0, 0, 0, 1}.Equal(a.A)) </s> remove c, b := clients.Find("1.1.1.2")
</s> add c, b := clients.Find(net.IPv4(1, 1, 1, 2)) </s> remove c, b = clients.Find("1.1.1.1")
</s> add c, b = clients.Find(net.IPv4(1, 1, 1, 1)) </s> remove assert.Equal(t, "192.168.0.1", reply.Answer[0].(*dns.A).A.String())
</s> add assert.True(t, net.IP{192, 168, 0, 1}.Equal(reply.Answer[0].(*dns.A).A)) </s> remove assert.Equal(t, "1.2.3.4", r.IPList[0].String())
</s> add assert.True(t, net.IP{1, 2, 3, 4}.Equal(r.IPList[0]))
|
https://github.com/AdguardTeam/AdGuardHome/commit/7fab31beaeb8c7d1c9892746bbf37e99d4f9dc01
|
internal/dnsforward/dnsforward_test.go
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.