Allow specifying permissions when creating anonymous temp files

This commit is contained in:
Kovid Goyal 2024-07-23 07:28:10 +05:30
parent 4c0ead129e
commit eaf71d1ccf
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
2 changed files with 25 additions and 3 deletions

View file

@ -5,6 +5,7 @@ package utils
import (
"fmt"
"io/fs"
"os"
"strconv"
@ -13,11 +14,15 @@ import (
var _ = fmt.Print
func CreateAnonymousTemp(dir string) (*os.File, error) {
func CreateAnonymousTemp(dir string, perms ...fs.FileMode) (*os.File, error) {
if dir == "" {
dir = os.TempDir()
}
fd, err := unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, 0600)
var perm fs.FileMode = unix.S_IREAD | unix.S_IWRITE
if len(perms) > 0 {
perm = perms[0]
}
fd, err := unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, uint32(perm&fs.ModePerm))
if err == nil {
path := "/proc/self/fd/" + strconv.FormatUint(uint64(fd), 10)

View file

@ -6,16 +6,33 @@ package utils
import (
"fmt"
"io/fs"
"os"
"golang.org/x/sys/unix"
)
var _ = fmt.Print
func CreateAnonymousTemp(dir string) (*os.File, error) {
func CreateAnonymousTemp(dir string, perms ...fs.FileMode) (*os.File, error) {
var perm fs.FileMode = unix.S_IREAD | unix.S_IWRITE
default_perm := perm
if len(perms) > 0 {
perm = perms[0]
}
f, err := os.CreateTemp(dir, "")
if err != nil {
return nil, err
}
if perm != default_perm {
err = f.Chmod(perm & fs.ModePerm)
if err != nil {
os.Remove(f.Name())
f.Close()
return nil, err
}
}
err = os.Remove(f.Name())
if err != nil {
f.Close()