AdGuardHome/internal/dnsforward/dnsrewrite.go
Ainar Garipov bdff46ec1d Pull request: all: add $dnsrewrite handling
Merge in DNS/adguard-home from 2102-dnsrewrite to master

Updates #2102.

Squashed commit of the following:

commit 8490fc18179d38c4b162ff9b257fea1f8535afbd
Merge: d9448ddca e7f7799b3
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Dec 21 16:44:00 2020 +0300

    Merge branch 'master' into 2102-dnsrewrite

commit d9448ddca6d4ef3635d767e3e496e44c35d3fc6e
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Mon Dec 21 15:44:54 2020 +0300

    querylog: support dnsrewrite rules

commit 40aa5d30acddf29fb90d249d8806941c6e1915a4
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Fri Dec 18 19:27:40 2020 +0300

    all: improve documentation

commit f776a0cd63b1640ba1e5210d9301e2a2801fd824
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Fri Dec 18 19:09:08 2020 +0300

    dnsfilter: prevent panics, improve docs

commit e14073b7500d9ed827a151c5b8fb863c980c10e8
Author: Ainar Garipov <A.Garipov@AdGuard.COM>
Date:   Fri Dec 4 15:51:02 2020 +0300

    all: add $dnsrewrite handling
2020-12-21 17:48:07 +03:00

80 lines
1.9 KiB
Go

package dnsforward
import (
"fmt"
"net"
"github.com/AdguardTeam/AdGuardHome/internal/agherr"
"github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
"github.com/AdguardTeam/dnsproxy/proxy"
"github.com/AdguardTeam/golibs/log"
"github.com/AdguardTeam/urlfilter/rules"
"github.com/miekg/dns"
)
// filterDNSRewriteResponse handles a single DNS rewrite response entry.
// It returns the constructed answer resource record.
func (s *Server) filterDNSRewriteResponse(req *dns.Msg, rr rules.RRType, v rules.RRValue) (ans dns.RR, err error) {
switch rr {
case dns.TypeA, dns.TypeAAAA:
ip, ok := v.(net.IP)
if !ok {
return nil, fmt.Errorf("value has type %T, not net.IP", v)
}
if rr == dns.TypeA {
return s.genAAnswer(req, ip.To4()), nil
}
return s.genAAAAAnswer(req, ip), nil
case dns.TypeTXT:
str, ok := v.(string)
if !ok {
return nil, fmt.Errorf("value has type %T, not string", v)
}
return s.genTXTAnswer(req, []string{str}), nil
default:
log.Debug("don't know how to handle dns rr type %d, skipping", rr)
return nil, nil
}
}
// filterDNSRewrite handles dnsrewrite filters. It constructs a DNS
// response and sets it into d.Res.
func (s *Server) filterDNSRewrite(req *dns.Msg, res dnsfilter.Result, d *proxy.DNSContext) (err error) {
resp := s.makeResponse(req)
dnsrr := res.DNSRewriteResult
if dnsrr == nil {
return agherr.Error("no dns rewrite rule content")
}
resp.Rcode = dnsrr.RCode
if resp.Rcode != dns.RcodeSuccess {
d.Res = resp
return nil
}
if dnsrr.Response == nil {
return agherr.Error("no dns rewrite rule responses")
}
rr := req.Question[0].Qtype
values := dnsrr.Response[rr]
for i, v := range values {
var ans dns.RR
ans, err = s.filterDNSRewriteResponse(req, rr, v)
if err != nil {
return fmt.Errorf("dns rewrite response for %d[%d]: %w", rr, i, err)
}
resp.Answer = append(resp.Answer, ans)
}
d.Res = resp
return nil
}