github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/dns/handler_system.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package dns
    19  
    20  import (
    21  	"net"
    22  
    23  	"github.com/miekg/dns"
    24  	"github.com/pkg/errors"
    25  	"github.com/rs/zerolog/log"
    26  )
    27  
    28  // ResolveViaSystem creates proxying DNS handler.
    29  func ResolveViaSystem() (dns.Handler, error) {
    30  	handler := &proxyHandler{
    31  		client: &dns.Client{
    32  			DialTimeout:  dnsTimeout,
    33  			ReadTimeout:  dnsTimeout,
    34  			WriteTimeout: dnsTimeout,
    35  		},
    36  	}
    37  	if err := handler.configure(); err != nil {
    38  		return nil, errors.Wrap(err, "failed to find system DNS configuration")
    39  	}
    40  
    41  	return handler, nil
    42  }
    43  
    44  type proxyHandler struct {
    45  	proxyAddrs []string
    46  	client     *dns.Client
    47  }
    48  
    49  // configure configures proxy to use system DNS servers.
    50  func (ph *proxyHandler) configure() (err error) {
    51  	cfg, err := configuration()
    52  	if err != nil {
    53  		return err
    54  	}
    55  	for _, server := range cfg.Servers {
    56  		ph.proxyAddrs = append(ph.proxyAddrs, net.JoinHostPort(server, cfg.Port))
    57  	}
    58  	return nil
    59  }
    60  
    61  func (ph *proxyHandler) ServeDNS(writer dns.ResponseWriter, req *dns.Msg) {
    62  	for _, addr := range ph.proxyAddrs {
    63  		resp, _, err := ph.client.Exchange(req, addr)
    64  		if err != nil {
    65  			log.Error().Err(err).Msg("Error proxying DNS query to " + addr)
    66  			continue
    67  		}
    68  
    69  		writer.WriteMsg(resp)
    70  		return
    71  	}
    72  
    73  	resp := &dns.Msg{}
    74  	resp.SetRcode(req, dns.RcodeServerFailure)
    75  	writer.WriteMsg(resp)
    76  }