From 0afa9614d3e53bf834b2b91fff019d7fcfbf9bf1 Mon Sep 17 00:00:00 2001 From: Nick Khyl Date: Mon, 23 Nov 2026 12:15:26 -0800 Subject: [PATCH] net/dns: stage the new hosts file outside of the etc directory on Windows atomicfile.WriteFile creates its temporary file next to the target, and changes in System32\drivers\etc make the DNS Client service reload the hosts file. Besides the extra reloads, the service may then have the hosts file open just as we try to replace it. In this PR, we create the temporary file in System32\drivers instead, which is on the same volume, and move it into place with atomicfile.Rename. Updates #21001 Updates #5753 Updates #8161 Updates #21617 Updates #14327 Updates tailscale/corp#52076 Signed-off-by: Nick Khyl --- net/dns/manager_windows.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/net/dns/manager_windows.go b/net/dns/manager_windows.go index ca6bdc2bf..8860a8783 100644 --- a/net/dns/manager_windows.go +++ b/net/dns/manager_windows.go @@ -325,7 +325,8 @@ func (m *windowsManager) writeHosts(hosts []*HostEntry) error { if err != nil { return err } - hostsFile := filepath.Join(systemDir, "drivers", "etc", "hosts") + driversDir := filepath.Join(systemDir, "drivers") + hostsFile := filepath.Join(driversDir, "etc", "hosts") b, err := os.ReadFile(hostsFile) switch { case err == nil: @@ -345,8 +346,21 @@ func (m *windowsManager) writeHosts(hosts []*HostEntry) error { return nil } - const fileMode = 0 // ignored on windows. - return atomicfile.WriteFile(hostsFile, outB, fileMode) + // Stage the new file outside of the etc directory, where creating + // and removing a temporary file would make the DNS Client service + // (Dnscache) reload the hosts file. It must be on the same volume + // as the hosts file to replace it. + tmpFile := filepath.Join(driversDir, "tailscale-hosts.tmp") + defer os.Remove(tmpFile) // no-op if the file is renamed + f, err := os.Create(tmpFile) + if err != nil { + return err + } + _, err = f.Write(outB) + if err := errors.Join(err, f.Sync(), f.Close()); err != nil { + return err + } + return atomicfile.Rename(tmpFile, hostsFile) } // setPrimaryDNS sets the given resolvers and domains as the Tailscale