1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2025-12-17 14:37:02 +00:00
Files
go-chasquid-smtp/internal/safeio/safeio.go
Alberto Bertogli cda11e03a5 safeio: Preserve file ownership
This patch makes safeio preserve file ownership. This is specially
useful when using command-line utilities as root, but the files they
change are owned by a different user.
2016-10-21 22:18:53 +01:00

69 lines
1.6 KiB
Go

// Package safeio implements convenient I/O routines that provide additional
// levels of safety in the presence of unexpected failures.
package safeio
import (
"io/ioutil"
"os"
"path"
"syscall"
)
// WriteFile writes data to a file named by filename, atomically.
// It's a wrapper to ioutil.WriteFile, but provides atomicity (and increased
// safety) by writing to a temporary file and renaming it at the end.
//
// Note this relies on same-directory Rename being atomic, which holds in most
// reasonably modern filesystems.
func WriteFile(filename string, data []byte, perm os.FileMode) error {
// Note we create the temporary file in the same directory, otherwise we
// would have no expectation of Rename being atomic.
// We make the file names start with "." so there's no confusion with the
// originals.
tmpf, err := ioutil.TempFile(path.Dir(filename), "."+path.Base(filename))
if err != nil {
return err
}
if err = tmpf.Chmod(perm); err != nil {
tmpf.Close()
os.Remove(tmpf.Name())
return err
}
if uid, gid := getOwner(filename); uid >= 0 {
if err = tmpf.Chown(uid, gid); err != nil {
tmpf.Close()
os.Remove(tmpf.Name())
return err
}
}
if _, err = tmpf.Write(data); err != nil {
tmpf.Close()
os.Remove(tmpf.Name())
return err
}
if err = tmpf.Close(); err != nil {
os.Remove(tmpf.Name())
return err
}
return os.Rename(tmpf.Name(), filename)
}
func getOwner(fname string) (uid, gid int) {
uid = -1
gid = -1
stat, err := os.Stat(fname)
if err == nil {
if sysstat, ok := stat.Sys().(*syscall.Stat_t); ok {
uid = int(sysstat.Uid)
gid = int(sysstat.Gid)
}
}
return
}