AdGuardHome/internal/dnsforward/dialcontext.go
Dimitry Kolyshev 75cb9d412a Pull request: all: upd dnsproxy
Squashed commit of the following:

commit 65525439e8f8868d4bc2b444bad9e96f702dadda
Merge: a6c507977 2965d1fb6
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Fri Dec 1 10:02:29 2023 +0200

    Merge remote-tracking branch 'origin/master' into upd-dnsproxy

commit a6c507977968c15ec024a36adfdbc1323505a574
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Nov 30 14:55:15 2023 +0200

    dnsforward: imp code

commit 5bd6805d54ec5908682481cd942dd1f088e576ff
Merge: 094a9c9b0 0e4e243e8
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Nov 30 10:56:58 2023 +0200

    Merge remote-tracking branch 'origin/master' into upd-dnsproxy

commit 094a9c9b091182dadcfcc3a7ef312c1032ac42df
Author: Dimitry Kolyshev <dkolyshev@adguard.com>
Date:   Thu Nov 30 10:54:39 2023 +0200

    all: upd dnsproxy
2023-12-01 11:12:03 +03:00

63 lines
1.4 KiB
Go

package dnsforward
import (
"context"
"fmt"
"net"
"net/netip"
"strconv"
"time"
"github.com/AdguardTeam/golibs/errors"
"github.com/AdguardTeam/golibs/log"
)
// DialContext is an [aghnet.DialContextFunc] that uses s to resolve hostnames.
// addr should be a valid host:port address, where host could be a domain name
// or an IP address.
func (s *Server) DialContext(ctx context.Context, network, addr string) (conn net.Conn, err error) {
log.Debug("dnsforward: dialing %q for network %q", addr, network)
host, portStr, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
dialer := &net.Dialer{
// TODO(a.garipov): Consider making configurable.
Timeout: time.Minute * 5,
}
if net.ParseIP(host) != nil {
return dialer.DialContext(ctx, network, addr)
}
port, err := strconv.Atoi(portStr)
if err != nil {
return nil, fmt.Errorf("invalid port %s: %w", portStr, err)
}
ips, err := s.Resolve(ctx, network, host)
if err != nil {
return nil, fmt.Errorf("resolving %q: %w", host, err)
} else if len(ips) == 0 {
return nil, fmt.Errorf("no addresses for host %q", host)
}
log.Debug("dnsforward: resolved %q: %v", host, ips)
var dialErrs []error
for _, ip := range ips {
addrPort := netip.AddrPortFrom(ip, uint16(port))
conn, err = dialer.DialContext(ctx, network, addrPort.String())
if err != nil {
dialErrs = append(dialErrs, err)
continue
}
return conn, nil
}
return nil, errors.Join(dialErrs...)
}