From cc75212b468ab9c196adb1736015e2943ccdb173 Mon Sep 17 00:00:00 2001 From: Leo Antunes Date: Sat, 25 Aug 2018 12:29:49 +0200 Subject: [PATCH] fsync tmpfile file before overwriting hostsfile --- etchosts.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/etchosts.go b/etchosts.go index da412b1..fe3acdc 100644 --- a/etchosts.go +++ b/etchosts.go @@ -101,14 +101,20 @@ func writeEntryWithBanner(tmp io.Writer, ip string, names []string) error { } func movePreservePerms(src, dst *os.File) error { + if err := src.Sync(); err != nil { + return fmt.Errorf("could not sync changes to %s: %s", src.Name(), err) + } + etcHostsInfo, err := dst.Stat() if err != nil { return fmt.Errorf("could not stat %s: %s", dst.Name(), err) } + // We try moving first because it's atomic; the fallback strategy is copying the content, which might generate a + // broken hosts file if some other process writes to it at the same time. err = os.Rename(src.Name(), dst.Name()) if err != nil { - log.Infof("could not rename to %s; falling back to less safe direct-write (%s)", config.EtcHostsPath, err) + log.Infof("could not rename to %s; falling back to less safe direct-write (%s)", dst.Name(), err) if _, err := src.Seek(0, io.SeekStart); err != nil { return err