-
Notifications
You must be signed in to change notification settings - Fork 561
/
transport.go
109 lines (90 loc) · 2.3 KB
/
transport.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package netconfhttp
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"strings"
"github.com/moby/buildkit/executor/oci"
)
// NewTransport returns a http.RoundTripper that will respect the settings in
// the given network configuration as a logical override to the host's
// /etc/hosts and/or /etc/resolv.conf.
func NewTransport(rt http.RoundTripper, dns *oci.DNSConfig) http.RoundTripper {
var domains []string
var resolver *net.Resolver
if dns == nil {
resolver = net.DefaultResolver
} else {
domains = dns.SearchDomains
dialer := net.Dialer{}
resolver = &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
if len(dns.Nameservers) == 0 {
return nil, errors.New("no nameservers configured")
}
var errs []error
for _, ns := range dns.Nameservers {
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ns, "53"))
if err != nil {
errs = append(errs, err)
continue
}
return conn, nil
}
return nil, errors.Join(errs...)
},
}
}
return &transport{
rt: rt,
resolver: resolver,
searchDomains: domains,
}
}
type transport struct {
rt http.RoundTripper
resolver *net.Resolver
searchDomains []string
}
func (h *transport) RoundTrip(req *http.Request) (*http.Response, error) {
if strings.Count(req.URL.Host, ".") == 0 && len(h.searchDomains) > 0 {
if host, port, err := net.SplitHostPort(req.URL.Host); err == nil {
ip, err := h.lookup(req.Context(), host)
if err != nil {
return nil, err
}
req.URL.Host = net.JoinHostPort(ip.String(), port)
} else {
ip, err := h.lookup(req.Context(), req.URL.Host)
if err != nil {
return nil, err
}
req.URL.Host = ip.String()
}
}
return h.rt.RoundTrip(req)
}
func (h *transport) lookup(ctx context.Context, target string) (net.IP, error) {
var errs []error
for _, domain := range append([]string{""}, h.searchDomains...) {
qualified := target
if domain != "" {
qualified += "." + domain
}
ips, err := h.resolver.LookupIPAddr(ctx, qualified)
if err != nil {
errs = append(errs, err)
continue
}
if len(ips) > 0 {
return ips[0].IP, nil
}
}
if len(errs) > 0 {
return nil, errors.Join(errs...)
}
return nil, fmt.Errorf("no IPs found for %s", target)
}