From eaf71d1ccf0626610efec71b371f13662eef82b5 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Tue, 23 Jul 2024 07:28:10 +0530 Subject: [PATCH] Allow specifying permissions when creating anonymous temp files --- tools/utils/tmpfile_linux.go | 9 +++++++-- tools/utils/tmpfile_others.go | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/tools/utils/tmpfile_linux.go b/tools/utils/tmpfile_linux.go index cf4bf5377..77fd05d90 100644 --- a/tools/utils/tmpfile_linux.go +++ b/tools/utils/tmpfile_linux.go @@ -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) diff --git a/tools/utils/tmpfile_others.go b/tools/utils/tmpfile_others.go index 7d231c2e8..827d9c201 100644 --- a/tools/utils/tmpfile_others.go +++ b/tools/utils/tmpfile_others.go @@ -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()