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 <[email protected]>
This commit is contained in:
Nick Khyl authored and Nick Khyl committed 2026-11-23 12:48:28 -08:00
1 parent 65c4e36477
commit 0afa9614d3
1 file changed
+17 -3
+17 -3
View File
@@ -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