cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
edgediscovery/allregions/discovery.go
153lines · modecode
| 1 | package allregions |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/tls" |
| 6 | "fmt" |
| 7 | "net" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/pkg/errors" |
| 11 | "github.com/rs/zerolog" |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | // Used to discover HA origintunneld servers |
| 16 | srvService = "origintunneld" |
| 17 | srvProto = "tcp" |
| 18 | srvName = "argotunnel.com" |
| 19 | |
| 20 | // Used to fallback to DoT when we can't use the default resolver to |
| 21 | // discover HA origintunneld servers (GitHub issue #75). |
| 22 | dotServerName = "cloudflare-dns.com" |
| 23 | dotServerAddr = "1.1.1.1:853" |
| 24 | dotTimeout = 15 * time.Second |
| 25 | |
| 26 | logFieldAddress = "address" |
| 27 | ) |
| 28 | |
| 29 | // Redeclare network functions so they can be overridden in tests. |
| 30 | var ( |
| 31 | netLookupSRV = net.LookupSRV |
| 32 | netLookupIP = net.LookupIP |
| 33 | ) |
| 34 | |
| 35 | // EdgeAddr is a representation of possible ways to refer an edge location. |
| 36 | type EdgeAddr struct { |
| 37 | TCP *net.TCPAddr |
| 38 | UDP *net.UDPAddr |
| 39 | } |
| 40 | |
| 41 | // If the call to net.LookupSRV fails, try to fall back to DoT from Cloudflare directly. |
| 42 | // |
| 43 | // Note: Instead of DoT, we could also have used DoH. Either of these: |
| 44 | // - directly via the JSON API (https://1.1.1.1/dns-query?ct=application/dns-json&name=_origintunneld._tcp.argotunnel.com&type=srv) |
| 45 | // - indirectly via `tunneldns.NewUpstreamHTTPS()` |
| 46 | // But both of these cases miss out on a key feature from the stdlib: |
| 47 | // "The returned records are sorted by priority and randomized by weight within a priority." |
| 48 | // (https://golang.org/pkg/net/#Resolver.LookupSRV) |
| 49 | // Does this matter? I don't know. It may someday. Let's use DoT so we don't need to worry about it. |
| 50 | // See also: Go feature request for stdlib-supported DoH: https://github.com/golang/go/issues/27552 |
| 51 | var fallbackLookupSRV = lookupSRVWithDOT |
| 52 | |
| 53 | var friendlyDNSErrorLines = []string{ |
| 54 | `Please try the following things to diagnose this issue:`, |
| 55 | ` 1. ensure that argotunnel.com is returning "origintunneld" service records.`, |
| 56 | ` Run your system's equivalent of: dig srv _origintunneld._tcp.argotunnel.com`, |
| 57 | ` 2. ensure that your DNS resolver is not returning compressed SRV records.`, |
| 58 | ` See GitHub issue https://github.com/golang/go/issues/27546`, |
| 59 | ` For example, you could use Cloudflare's 1.1.1.1 as your resolver:`, |
| 60 | ` https://developers.cloudflare.com/1.1.1.1/setting-up-1.1.1.1/`, |
| 61 | } |
| 62 | |
| 63 | // EdgeDiscovery implements HA service discovery lookup. |
| 64 | func edgeDiscovery(log *zerolog.Logger, srvService string) ([][]*EdgeAddr, error) { |
| 65 | log.Debug().Str("domain", "_"+srvService+"._"+srvProto+"."+srvName).Msg("looking up edge SRV record") |
| 66 | |
| 67 | _, addrs, err := netLookupSRV(srvService, srvProto, srvName) |
| 68 | if err != nil { |
| 69 | _, fallbackAddrs, fallbackErr := fallbackLookupSRV(srvService, srvProto, srvName) |
| 70 | if fallbackErr != nil || len(fallbackAddrs) == 0 { |
| 71 | // use the original DNS error `err` in messages, not `fallbackErr` |
| 72 | log.Err(err).Msg("Error looking up Cloudflare edge IPs: the DNS query failed") |
| 73 | for _, s := range friendlyDNSErrorLines { |
| 74 | log.Error().Msg(s) |
| 75 | } |
| 76 | return nil, errors.Wrapf(err, "Could not lookup srv records on _%v._%v.%v", srvService, srvProto, srvName) |
| 77 | } |
| 78 | // Accept the fallback results and keep going |
| 79 | addrs = fallbackAddrs |
| 80 | } |
| 81 | |
| 82 | var resolvedAddrPerCNAME [][]*EdgeAddr |
| 83 | for _, addr := range addrs { |
| 84 | edgeAddrs, err := resolveSRV(addr) |
| 85 | if err != nil { |
| 86 | return nil, err |
| 87 | } |
| 88 | resolvedAddrPerCNAME = append(resolvedAddrPerCNAME, edgeAddrs) |
| 89 | } |
| 90 | |
| 91 | return resolvedAddrPerCNAME, nil |
| 92 | } |
| 93 | |
| 94 | func lookupSRVWithDOT(srvService string, srvProto string, srvName string) (cname string, addrs []*net.SRV, err error) { |
| 95 | // Inspiration: https://github.com/artyom/dot/blob/master/dot.go |
| 96 | r := &net.Resolver{ |
| 97 | PreferGo: true, |
| 98 | Dial: func(ctx context.Context, _ string, _ string) (net.Conn, error) { |
| 99 | var dialer net.Dialer |
| 100 | conn, err := dialer.DialContext(ctx, "tcp", dotServerAddr) |
| 101 | if err != nil { |
| 102 | return nil, err |
| 103 | } |
| 104 | tlsConfig := &tls.Config{ServerName: dotServerName} |
| 105 | return tls.Client(conn, tlsConfig), nil |
| 106 | }, |
| 107 | } |
| 108 | ctx, cancel := context.WithTimeout(context.Background(), dotTimeout) |
| 109 | defer cancel() |
| 110 | return r.LookupSRV(ctx, srvService, srvProto, srvName) |
| 111 | } |
| 112 | |
| 113 | func resolveSRV(srv *net.SRV) ([]*EdgeAddr, error) { |
| 114 | ips, err := netLookupIP(srv.Target) |
| 115 | if err != nil { |
| 116 | return nil, errors.Wrapf(err, "Couldn't resolve SRV record %v", srv) |
| 117 | } |
| 118 | if len(ips) == 0 { |
| 119 | return nil, fmt.Errorf("SRV record %v had no IPs", srv) |
| 120 | } |
| 121 | addrs := make([]*EdgeAddr, len(ips)) |
| 122 | for i, ip := range ips { |
| 123 | addrs[i] = &EdgeAddr{ |
| 124 | TCP: &net.TCPAddr{IP: ip, Port: int(srv.Port)}, |
| 125 | UDP: &net.UDPAddr{IP: ip, Port: int(srv.Port)}, |
| 126 | } |
| 127 | } |
| 128 | return addrs, nil |
| 129 | } |
| 130 | |
| 131 | // ResolveAddrs resolves TCP address given a list of addresses. Address can be a hostname, however, it will return at most one |
| 132 | // of the hostname's IP addresses. |
| 133 | func ResolveAddrs(addrs []string, log *zerolog.Logger) (resolved []*EdgeAddr) { |
| 134 | for _, addr := range addrs { |
| 135 | tcpAddr, err := net.ResolveTCPAddr("tcp", addr) |
| 136 | if err != nil { |
| 137 | log.Error().Str(logFieldAddress, addr).Err(err).Msg("failed to resolve to TCP address") |
| 138 | continue |
| 139 | } |
| 140 | |
| 141 | udpAddr, err := net.ResolveUDPAddr("udp", addr) |
| 142 | if err != nil { |
| 143 | log.Error().Str(logFieldAddress, addr).Err(err).Msg("failed to resolve to UDP address") |
| 144 | continue |
| 145 | } |
| 146 | resolved = append(resolved, &EdgeAddr{ |
| 147 | TCP: tcpAddr, |
| 148 | UDP: udpAddr, |
| 149 | }) |
| 150 | |
| 151 | } |
| 152 | return |
| 153 | } |
| 154 | |