mirror of
https://github.com/kopia/kopia.git
synced 2026-04-04 06:22:59 -04:00
Minor robustness improvements - add safety check when converting file descriptor (`os.File.Fd()`) to `int` - check that file descriptor returned by Open (on Linux) is non-negative before converting to `uintptr`. This addresses a linter warning for a most-likely-non-existent-edge-case of converting a negative file descriptor. - check that parsed content IDs (hashes) do not exceed the maximum id hash length. - add nolint annotation for safe conversion
34 lines
758 B
Go
34 lines
758 B
Go
package tempfile
|
|
|
|
import (
|
|
"errors"
|
|
"os"
|
|
"syscall"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
const permissions = 0o600
|
|
|
|
// CreateAutoDelete creates a temporary file that will be automatically deleted on close.
|
|
func CreateAutoDelete() (*os.File, error) {
|
|
dir := os.TempDir()
|
|
|
|
// on reasonably modern Linux (3.11 and above) O_TMPFILE is supported,
|
|
// which creates invisible, unlinked file in a given directory.
|
|
fd, err := unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, permissions)
|
|
if err == nil && fd >= 0 {
|
|
return os.NewFile(uintptr(fd), ""), nil
|
|
}
|
|
|
|
if err == nil || errors.Is(err, syscall.EISDIR) || errors.Is(err, syscall.EOPNOTSUPP) {
|
|
return createUnixFallback()
|
|
}
|
|
|
|
return nil, &os.PathError{
|
|
Op: "open",
|
|
Path: dir,
|
|
Err: err,
|
|
}
|
|
}
|