46 lines
977 B
Go
46 lines
977 B
Go
//go:build linux || darwin
|
|
|
|
package safeio
|
|
|
|
import (
|
|
"golang.org/x/sys/unix"
|
|
"os"
|
|
)
|
|
|
|
func publishCanonicalNewFile(path string, contents []byte, mode os.FileMode) error {
|
|
directory, target, err := openCanonicalParentDirectory(path)
|
|
if err != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
defer unix.Close(directory)
|
|
temporary, err := writePrivateTemporaryAt(directory, contents)
|
|
if err != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
defer func() {
|
|
if temporary != "" {
|
|
_ = unix.Unlinkat(directory, temporary, 0)
|
|
}
|
|
}()
|
|
fd, err := unix.Openat(directory, temporary, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
|
|
if err != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
err = unix.Fchmod(fd, uint32(mode))
|
|
if err == nil {
|
|
err = unix.Fsync(fd)
|
|
}
|
|
_ = unix.Close(fd)
|
|
if err != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
if err := publishNoReplace(directory, temporary, target); err != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
temporary = ""
|
|
if unix.Fsync(directory) != nil {
|
|
return ErrUnsafeFile
|
|
}
|
|
return nil
|
|
}
|