2baa33fb1f
Merge in DNS/adguard-home from 2240-removing-errorx-dependency to master Squashed commit of the following: commit 5bbe0567356f06e3b9ee5b3dc38d357b472cacb1 Merge: a6040850d02d16a0b4
Author: Eugene Burkov <e.burkov@adguard.com> Date: Thu Nov 5 14:32:22 2020 +0300 Merge branch 'master' into 2240-removing-errorx-dependency commit a6040850da3cefb131208097477b0956e80063fb Author: Eugene Burkov <e.burkov@adguard.com> Date: Thu Nov 5 14:23:36 2020 +0300 * dhcpd: convert some abbreviations to lowercase. commit d05bd51b994906b0ff52c5a8e779bd1f512f4bb7 Author: Eugene Burkov <e.burkov@adguard.com> Date: Thu Nov 5 12:47:20 2020 +0300 * agherr: last final fixes commit 164bca55035ff44e50b0abb33e129a0d24ffe87c Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Nov 3 19:11:10 2020 +0300 * all: final fixes again commit a0ac26f409c0b28a176cf2861d52c2f471b59484 Author: Ainar Garipov <A.Garipov@AdGuard.COM> Date: Tue Nov 3 18:51:39 2020 +0300 * all: final fixes commit 6147b02d402b513323b07e85856b348884f3a088 Merge: 9fd3af1a362cc334f4
Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 18:26:03 2020 +0300 Merge branch 'master' into 2240-removing-errorx-dependency commit 9fd3af1a39a3189b5c41315a8ad1568ae5cb4fc9 Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 18:23:08 2020 +0300 * all: remove useless helper commit 7cd9aeae639762b28b25f354d69c5cf74f670211 Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 17:19:26 2020 +0300 * agherr: improved code tidiness commit a74a49236e9aaace070646dac710de9201105262 Merge: dc9dedbf2df34ee5c0
Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 16:54:29 2020 +0300 Merge branch 'master' into 2240-removing-errorx-dependency commit dc9dedbf205756e3adaa3bc776d349bf3d8c69a5 Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 16:40:08 2020 +0300 * agherr: improve and cover by tests commit fd6bfe9e282156cc60e006cb7cd46cce4d3a07a8 Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 14:06:27 2020 +0300 * all: improve code quality commit ea00c2f8c5060e9611f9a80cfd0e4a039526d0c4 Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 13:03:57 2020 +0300 * all: fix linter style warnings commit 8e75e1a681a7218c2b4c69adfa2b7e1e2966f9ac Author: Eugene Burkov <e.burkov@adguard.com> Date: Tue Nov 3 12:29:26 2020 +0300 * all: remove github.com/joomcode/errorx dependency Closes #2240.
309 lines
7.8 KiB
Go
309 lines
7.8 KiB
Go
// Package dnsforward contains a DNS forwarding server.
|
|
package dnsforward
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"runtime"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/AdguardTeam/AdGuardHome/internal/dhcpd"
|
|
"github.com/AdguardTeam/AdGuardHome/internal/dnsfilter"
|
|
"github.com/AdguardTeam/AdGuardHome/internal/querylog"
|
|
"github.com/AdguardTeam/AdGuardHome/internal/stats"
|
|
"github.com/AdguardTeam/dnsproxy/proxy"
|
|
"github.com/AdguardTeam/golibs/log"
|
|
"github.com/miekg/dns"
|
|
)
|
|
|
|
// DefaultTimeout is the default upstream timeout
|
|
const DefaultTimeout = 10 * time.Second
|
|
|
|
const (
|
|
safeBrowsingBlockHost = "standard-block.dns.adguard.com"
|
|
parentalBlockHost = "family-block.dns.adguard.com"
|
|
)
|
|
|
|
var defaultDNS = []string{
|
|
"https://dns10.quad9.net/dns-query",
|
|
}
|
|
var defaultBootstrap = []string{"9.9.9.10", "149.112.112.10", "2620:fe::10", "2620:fe::fe:10"}
|
|
|
|
// Often requested by all kinds of DNS probes
|
|
var defaultBlockedHosts = []string{"version.bind", "id.server", "hostname.bind"}
|
|
|
|
var webRegistered bool
|
|
|
|
// Server is the main way to start a DNS server.
|
|
//
|
|
// Example:
|
|
// s := dnsforward.Server{}
|
|
// err := s.Start(nil) // will start a DNS server listening on default port 53, in a goroutine
|
|
// err := s.Reconfigure(ServerConfig{UDPListenAddr: &net.UDPAddr{Port: 53535}}) // will reconfigure running DNS server to listen on UDP port 53535
|
|
// err := s.Stop() // will stop listening on port 53535 and cancel all goroutines
|
|
// err := s.Start(nil) // will start listening again, on port 53535, in a goroutine
|
|
//
|
|
// The zero Server is empty and ready for use.
|
|
type Server struct {
|
|
dnsProxy *proxy.Proxy // DNS proxy instance
|
|
dnsFilter *dnsfilter.Dnsfilter // DNS filter instance
|
|
dhcpServer dhcpd.ServerInterface // DHCP server instance (optional)
|
|
queryLog querylog.QueryLog // Query log instance
|
|
stats stats.Stats
|
|
access *accessCtx
|
|
|
|
ipset ipsetCtx
|
|
|
|
tableHostToIP map[string]net.IP // "hostname -> IP" table for internal addresses (DHCP)
|
|
tableHostToIPLock sync.Mutex
|
|
|
|
tablePTR map[string]string // "IP -> hostname" table for reverse lookup
|
|
tablePTRLock sync.Mutex
|
|
|
|
// DNS proxy instance for internal usage
|
|
// We don't Start() it and so no listen port is required.
|
|
internalProxy *proxy.Proxy
|
|
|
|
isRunning bool
|
|
|
|
sync.RWMutex
|
|
conf ServerConfig
|
|
}
|
|
|
|
// DNSCreateParams - parameters for NewServer()
|
|
type DNSCreateParams struct {
|
|
DNSFilter *dnsfilter.Dnsfilter
|
|
Stats stats.Stats
|
|
QueryLog querylog.QueryLog
|
|
DHCPServer dhcpd.ServerInterface
|
|
}
|
|
|
|
// NewServer creates a new instance of the dnsforward.Server
|
|
// Note: this function must be called only once
|
|
func NewServer(p DNSCreateParams) *Server {
|
|
s := &Server{}
|
|
s.dnsFilter = p.DNSFilter
|
|
s.stats = p.Stats
|
|
s.queryLog = p.QueryLog
|
|
|
|
if p.DHCPServer != nil {
|
|
s.dhcpServer = p.DHCPServer
|
|
s.dhcpServer.SetOnLeaseChanged(s.onDHCPLeaseChanged)
|
|
s.onDHCPLeaseChanged(dhcpd.LeaseChangedAdded)
|
|
}
|
|
|
|
if runtime.GOARCH == "mips" || runtime.GOARCH == "mipsle" {
|
|
// Use plain DNS on MIPS, encryption is too slow
|
|
defaultDNS = defaultBootstrap
|
|
}
|
|
return s
|
|
}
|
|
|
|
// Close - close object
|
|
func (s *Server) Close() {
|
|
s.Lock()
|
|
s.dnsFilter = nil
|
|
s.stats = nil
|
|
s.queryLog = nil
|
|
s.dnsProxy = nil
|
|
s.Unlock()
|
|
}
|
|
|
|
// WriteDiskConfig - write configuration
|
|
func (s *Server) WriteDiskConfig(c *FilteringConfig) {
|
|
s.RLock()
|
|
sc := s.conf.FilteringConfig
|
|
*c = sc
|
|
c.RatelimitWhitelist = stringArrayDup(sc.RatelimitWhitelist)
|
|
c.BootstrapDNS = stringArrayDup(sc.BootstrapDNS)
|
|
c.AllowedClients = stringArrayDup(sc.AllowedClients)
|
|
c.DisallowedClients = stringArrayDup(sc.DisallowedClients)
|
|
c.BlockedHosts = stringArrayDup(sc.BlockedHosts)
|
|
c.UpstreamDNS = stringArrayDup(sc.UpstreamDNS)
|
|
s.RUnlock()
|
|
}
|
|
|
|
// Resolve - get IP addresses by host name from an upstream server.
|
|
// No request/response filtering is performed.
|
|
// Query log and Stats are not updated.
|
|
// This method may be called before Start().
|
|
func (s *Server) Resolve(host string) ([]net.IPAddr, error) {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
return s.internalProxy.LookupIPAddr(host)
|
|
}
|
|
|
|
// Exchange - send DNS request to an upstream server and receive response
|
|
// No request/response filtering is performed.
|
|
// Query log and Stats are not updated.
|
|
// This method may be called before Start().
|
|
func (s *Server) Exchange(req *dns.Msg) (*dns.Msg, error) {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
|
|
ctx := &proxy.DNSContext{
|
|
Proto: "udp",
|
|
Req: req,
|
|
StartTime: time.Now(),
|
|
}
|
|
err := s.internalProxy.Resolve(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return ctx.Res, nil
|
|
}
|
|
|
|
// Start starts the DNS server
|
|
func (s *Server) Start() error {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
return s.startInternal()
|
|
}
|
|
|
|
// startInternal starts without locking
|
|
func (s *Server) startInternal() error {
|
|
err := s.dnsProxy.Start()
|
|
if err == nil {
|
|
s.isRunning = true
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Prepare the object
|
|
func (s *Server) Prepare(config *ServerConfig) error {
|
|
// Initialize the server configuration
|
|
// --
|
|
if config != nil {
|
|
s.conf = *config
|
|
if s.conf.BlockingMode == "custom_ip" {
|
|
s.conf.BlockingIPAddrv4 = net.ParseIP(s.conf.BlockingIPv4)
|
|
s.conf.BlockingIPAddrv6 = net.ParseIP(s.conf.BlockingIPv6)
|
|
if s.conf.BlockingIPAddrv4 == nil || s.conf.BlockingIPAddrv6 == nil {
|
|
return fmt.Errorf("dns: invalid custom blocking IP address specified")
|
|
}
|
|
}
|
|
if s.conf.MaxGoroutines == 0 {
|
|
s.conf.MaxGoroutines = 50
|
|
}
|
|
}
|
|
|
|
// Set default values in the case if nothing is configured
|
|
// --
|
|
s.initDefaultSettings()
|
|
|
|
// Initialize IPSET configuration
|
|
// --
|
|
s.ipset.init(s.conf.IPSETList)
|
|
|
|
// Prepare DNS servers settings
|
|
// --
|
|
err := s.prepareUpstreamSettings()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Create DNS proxy configuration
|
|
// --
|
|
var proxyConfig proxy.Config
|
|
proxyConfig, err = s.createProxyConfig()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Prepare a DNS proxy instance that we use for internal DNS queries
|
|
// --
|
|
s.prepareIntlProxy()
|
|
|
|
// Initialize DNS access module
|
|
// --
|
|
s.access = &accessCtx{}
|
|
err = s.access.Init(s.conf.AllowedClients, s.conf.DisallowedClients, s.conf.BlockedHosts)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Register web handlers if necessary
|
|
// --
|
|
if !webRegistered && s.conf.HTTPRegister != nil {
|
|
webRegistered = true
|
|
s.registerHandlers()
|
|
}
|
|
|
|
// Create the main DNS proxy instance
|
|
// --
|
|
s.dnsProxy = &proxy.Proxy{Config: proxyConfig}
|
|
return nil
|
|
}
|
|
|
|
// Stop stops the DNS server
|
|
func (s *Server) Stop() error {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
return s.stopInternal()
|
|
}
|
|
|
|
// stopInternal stops without locking
|
|
func (s *Server) stopInternal() error {
|
|
if s.dnsProxy != nil {
|
|
err := s.dnsProxy.Stop()
|
|
if err != nil {
|
|
return fmt.Errorf("could not stop the DNS server properly: %w", err)
|
|
}
|
|
}
|
|
|
|
s.isRunning = false
|
|
return nil
|
|
}
|
|
|
|
// IsRunning returns true if the DNS server is running
|
|
func (s *Server) IsRunning() bool {
|
|
s.RLock()
|
|
defer s.RUnlock()
|
|
return s.isRunning
|
|
}
|
|
|
|
// Reconfigure applies the new configuration to the DNS server
|
|
func (s *Server) Reconfigure(config *ServerConfig) error {
|
|
s.Lock()
|
|
defer s.Unlock()
|
|
|
|
log.Print("Start reconfiguring the server")
|
|
err := s.stopInternal()
|
|
if err != nil {
|
|
return fmt.Errorf("could not reconfigure the server: %w", err)
|
|
}
|
|
|
|
// It seems that net.Listener.Close() doesn't close file descriptors right away.
|
|
// We wait for some time and hope that this fd will be closed.
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
err = s.Prepare(config)
|
|
if err != nil {
|
|
return fmt.Errorf("could not reconfigure the server: %w", err)
|
|
}
|
|
|
|
err = s.startInternal()
|
|
if err != nil {
|
|
return fmt.Errorf("could not reconfigure the server: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ServeHTTP is a HTTP handler method we use to provide DNS-over-HTTPS
|
|
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
s.RLock()
|
|
p := s.dnsProxy
|
|
s.RUnlock()
|
|
if p != nil { // an attempt to protect against race in case we're here after Close() was called
|
|
p.ServeHTTP(w, r)
|
|
}
|
|
}
|
|
|
|
// IsBlockedIP - return TRUE if this client should be blocked
|
|
func (s *Server) IsBlockedIP(ip string) (bool, string) {
|
|
return s.access.IsBlockedIP(ip)
|
|
}
|