From 326d7a43d47812a1bf4c4b0698902040896309fa Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Fri, 20 Jan 2023 13:24:04 +0700 Subject: [PATCH] cmd/ctrld: rework reset DNS statically vs DHCP If the interface was originally configured DNS via DHCP, ctrld should reset the interface using DHCP, not statically. --- cmd/ctrld/cli.go | 2 +- cmd/ctrld/os_windows.go | 15 ++++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cmd/ctrld/cli.go b/cmd/ctrld/cli.go index 05bf9fb..0235b1c 100644 --- a/cmd/ctrld/cli.go +++ b/cmd/ctrld/cli.go @@ -195,7 +195,7 @@ func initCLI() { writeDefaultConfig := !noConfigStart && configBase64 == "" if configPath == "" && writeDefaultConfig { defaultConfigFile = filepath.Join(dir, defaultConfigFile) - readConfigFile(true) + readConfigFile(writeDefaultConfig && cdUID == "") } sc.Arguments = append(sc.Arguments, "--homedir="+dir) } diff --git a/cmd/ctrld/os_windows.go b/cmd/ctrld/os_windows.go index 373479e..075b30d 100644 --- a/cmd/ctrld/os_windows.go +++ b/cmd/ctrld/os_windows.go @@ -4,6 +4,7 @@ package main import ( + "bytes" "errors" "net" "os/exec" @@ -42,6 +43,9 @@ func resetDNS(iface *net.Interface, nameservers []string) error { if err := resetDNSUseDHCP(iface); err != nil { mainLog.Debug().Err(err).Msg("could not reset DNS using DHCP") } + if len(nameservers) == 0 { + return nil + } return setDNS(iface, nameservers) } @@ -77,7 +81,7 @@ func addSecondaryDNS(iface *net.Interface, dns string) error { } func resetDNSUseDHCP(iface *net.Interface) error { - if supportsIPv6() { + if supportsIPv6ListenLocal() { if output, err := netsh("interface", "ipv6", "set", "dnsserver", strconv.Itoa(iface.Index), "dhcp"); err != nil { mainLog.Warn().Err(err).Msgf("failed to reset ipv6 DNS: %s", string(output)) } @@ -95,6 +99,9 @@ func netsh(args ...string) ([]byte, error) { } func currentDNS(iface *net.Interface) []string { + if hasDNSFromDHCP(iface, "ipv4") || hasDNSFromDHCP(iface, "ipv6") { + return nil + } luid, err := winipcfg.LUIDFromIndex(uint32(iface.Index)) if err != nil { mainLog.Error().Err(err).Msg("failed to get interface LUID") @@ -111,3 +118,9 @@ func currentDNS(iface *net.Interface) []string { } return ns } + +func hasDNSFromDHCP(iface *net.Interface, ipVer string) bool { + idx := strconv.Itoa(iface.Index) + output, _ := netsh("interface", ipVer, "show", "dnsservers", idx) + return bytes.Contains(output, []byte(" through DHCP:")) +}