AdGuardHome/internal/filtering/dnsrewrite.go
Ainar Garipov 3660b4810e Pull request: 4865-refactor-dns-handlers
Updates #4865.

Squashed commit of the following:

commit b874088ee72dfd0cae5f4102fac87e1f26245ddf
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Fri Sep 2 14:01:52 2022 +0300

    dnsforward: imp code, docs

commit a1b95fda58b777a54e7dcd57f0c419200f8fdc15
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Thu Sep 1 19:37:45 2022 +0300

    all: refactor dns handler; opt
2022-09-02 14:52:19 +03:00

76 lines
2.0 KiB
Go

package filtering
import (
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// DNSRewriteResult is the result of application of $dnsrewrite rules.
type DNSRewriteResult struct {
Response DNSRewriteResultResponse `json:",omitempty"`
RCode rules.RCode `json:",omitempty"`
}
// DNSRewriteResultResponse is the collection of DNS response records
// the server returns.
type DNSRewriteResultResponse map[rules.RRType][]rules.RRValue
// processDNSRewrites processes DNS rewrite rules in dnsr. It returns an empty
// result if dnsr is empty. Otherwise, the result will have either CanonName or
// DNSRewriteResult set. dnsr is expected to be non-empty.
func (d *DNSFilter) processDNSRewrites(dnsr []*rules.NetworkRule) (res Result) {
var rules []*ResultRule
dnsrr := &DNSRewriteResult{
Response: DNSRewriteResultResponse{},
}
for _, nr := range dnsr {
dr := nr.DNSRewrite
if dr.NewCNAME != "" {
// NewCNAME rules have a higher priority than other rules.
rules = []*ResultRule{{
FilterListID: int64(nr.GetFilterListID()),
Text: nr.RuleText,
}}
return Result{
Rules: rules,
Reason: RewrittenRule,
CanonName: dr.NewCNAME,
}
}
switch dr.RCode {
case dns.RcodeSuccess:
dnsrr.RCode = dr.RCode
dnsrr.Response[dr.RRType] = append(dnsrr.Response[dr.RRType], dr.Value)
rules = append(rules, &ResultRule{
FilterListID: int64(nr.GetFilterListID()),
Text: nr.RuleText,
})
default:
// RcodeRefused and other such codes have higher priority. Return
// immediately.
rules = []*ResultRule{{
FilterListID: int64(nr.GetFilterListID()),
Text: nr.RuleText,
}}
dnsrr = &DNSRewriteResult{
RCode: dr.RCode,
}
return Result{
DNSRewriteResult: dnsrr,
Rules: rules,
Reason: RewrittenRule,
}
}
}
return Result{
DNSRewriteResult: dnsrr,
Rules: rules,
Reason: RewrittenRule,
}
}