// Package atomicfile replaces local files atomically: temp file in the same // directory → write → fsync → rename → fsync of the directory (design §9.2). // A crash or error at any point leaves either the old file or the new one, // never a truncated mix. Used for the config, the session, hosts.dat and // known_hosts. package atomicfile import ( "bufio" "errors" "fmt" "io" "io/fs" "os" "path/filepath" "syscall" ) // WriteFile atomically replaces path with data. See Write. func WriteFile(path string, data []byte, perm fs.FileMode) error { return Write(path, perm, func(w io.Writer) error { _, err := w.Write(data) return err }) } // Write atomically replaces path with what fill writes. If fill (or any later // step) fails, the temp file is removed and path is untouched. // // - If path is a symlink (dotfiles!), the file it points to is replaced and // the link is kept. // - If path exists, its permission bits are kept (perm is used only for a // new file) and, when running as root, its owner too — so sudo does not // leave a root-owned file in a user's home. func Write(path string, perm fs.FileMode, fill func(w io.Writer) error) (err error) { target, err := resolve(path) if err != nil { return err } uid, gid := -1, -1 if fi, err := os.Stat(target); err == nil { if !fi.Mode().IsRegular() { return fmt.Errorf("atomicfile: %s is not a regular file", target) } perm = fi.Mode().Perm() if st, ok := fi.Sys().(*syscall.Stat_t); ok && os.Geteuid() == 0 { uid, gid = int(st.Uid), int(st.Gid) } } else if !errors.Is(err, fs.ErrNotExist) { return err } dir := filepath.Dir(target) tmp, err := os.CreateTemp(dir, "."+filepath.Base(target)+".tmp-*") if err != nil { return err } tmpName := tmp.Name() defer func() { if err != nil { tmp.Close() os.Remove(tmpName) } }() if err = tmp.Chmod(perm); err != nil { return err } if uid >= 0 { if err = tmp.Chown(uid, gid); err != nil { return err } } bw := bufio.NewWriter(tmp) if err = fill(bw); err != nil { return err } if err = bw.Flush(); err != nil { return err } if err = tmp.Sync(); err != nil { return err } if err = tmp.Close(); err != nil { return err } if err = os.Rename(tmpName, target); err != nil { return err } syncDir(dir) return nil } // resolve follows a symlink at path to the file it names (which may not exist // yet: a dangling link is written through). func resolve(path string) (string, error) { path, err := filepath.Abs(path) if err != nil { return "", err } for range 40 { fi, err := os.Lstat(path) if errors.Is(err, fs.ErrNotExist) { return path, nil } if err != nil { return "", err } if fi.Mode()&fs.ModeSymlink == 0 { return path, nil } link, err := os.Readlink(path) if err != nil { return "", err } if !filepath.IsAbs(link) { link = filepath.Join(filepath.Dir(path), link) } path = link } return "", fmt.Errorf("atomicfile: %s: too many levels of symbolic links", path) } // syncDir makes the rename durable. Some file systems refuse fsync on a // directory; that is not worth failing the write for. func syncDir(dir string) { d, err := os.Open(dir) if err != nil { return } _ = d.Sync() d.Close() }