From 77b62f8734c07d66a6dee5683680b1eb844d1fba Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Wed, 15 Mar 2023 20:04:26 +0700 Subject: [PATCH] cmd/ctrld: add default timeout for os resolver So it can fail fast if internet broken suddenly. While at it, also filtering out ipv6 nameservers if ipv6 not available. --- cmd/ctrld/dns_proxy.go | 5 +++-- config.go | 23 +++++++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/cmd/ctrld/dns_proxy.go b/cmd/ctrld/dns_proxy.go index 3098cc1..733ae63 100644 --- a/cmd/ctrld/dns_proxy.go +++ b/cmd/ctrld/dns_proxy.go @@ -342,6 +342,7 @@ func ttlFromMsg(msg *dns.Msg) uint32 { } var osUpstreamConfig = &ctrld.UpstreamConfig{ - Name: "OS resolver", - Type: ctrld.ResolverTypeOS, + Name: "OS resolver", + Type: ctrld.ResolverTypeOS, + Timeout: 2000, } diff --git a/config.go b/config.go index 76fa51c..b1582f6 100644 --- a/config.go +++ b/config.go @@ -165,11 +165,15 @@ func (uc *UpstreamConfig) SetupBootstrapIP() { return "" } - resolver := &osResolver{nameservers: nameservers()} + resolver := &osResolver{nameservers: availableNameservers()} resolver.nameservers = append([]string{net.JoinHostPort(bootstrapDNS, "53")}, resolver.nameservers...) ProxyLog.Debug().Msgf("Resolving %q using bootstrap DNS %q", uc.Domain, resolver.nameservers) + timeoutMs := 2000 + if uc.Timeout > 0 && uc.Timeout < timeoutMs { + timeoutMs = uc.Timeout + } do := func(dnsType uint16) { - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(uc.Timeout)*time.Millisecond) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeoutMs)*time.Millisecond) defer cancel() m := new(dns.Msg) m.SetQuestion(uc.Domain+".", dnsType) @@ -349,3 +353,18 @@ func defaultPortFor(typ string) string { } return "53" } + +func availableNameservers() []string { + nss := nameservers() + n := 0 + for _, ns := range nss { + ip, _, _ := net.SplitHostPort(ns) + // skipping invalid entry or ipv6 nameserver if ipv6 not available. + if ip == "" || (ctrldnet.IsIPv6(ip) && !ctrldnet.SupportsIPv6()) { + continue + } + nss[n] = ns + n++ + } + return nss[:n] +}