Skip to content

Commit

Permalink
Merge pull request #3930 from cyphar/close_range
Browse files Browse the repository at this point in the history
utils: use close_range(2) to close leftover file descriptors
  • Loading branch information
AkihiroSuda authored Aug 3, 2023
2 parents 2da710c + 70f4e46 commit f0a5e6b
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions libcontainer/utils/utils_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ package utils

import (
"fmt"
"math"
"os"
"strconv"
"sync"

"golang.org/x/sys/unix"
)
Expand All @@ -23,9 +25,38 @@ func EnsureProcHandle(fh *os.File) error {
return nil
}

var (
haveCloseRangeCloexecBool bool
haveCloseRangeCloexecOnce sync.Once
)

func haveCloseRangeCloexec() bool {
haveCloseRangeCloexecOnce.Do(func() {
// Make sure we're not closing a random file descriptor.
tmpFd, err := unix.FcntlInt(0, unix.F_DUPFD_CLOEXEC, 0)
if err != nil {
return
}
defer unix.Close(tmpFd)

err = unix.CloseRange(uint(tmpFd), uint(tmpFd), unix.CLOSE_RANGE_CLOEXEC)
// Any error means we cannot use close_range(CLOSE_RANGE_CLOEXEC).
// -ENOSYS and -EINVAL ultimately mean we don't have support, but any
// other potential error would imply that even the most basic close
// operation wouldn't work.
haveCloseRangeCloexecBool = err == nil
})
return haveCloseRangeCloexecBool
}

// CloseExecFrom applies O_CLOEXEC to all file descriptors currently open for
// the process (except for those below the given fd value).
func CloseExecFrom(minFd int) error {
if haveCloseRangeCloexec() {
err := unix.CloseRange(uint(minFd), math.MaxUint, unix.CLOSE_RANGE_CLOEXEC)
return os.NewSyscallError("close_range", err)
}

fdDir, err := os.Open("/proc/self/fd")
if err != nil {
return err
Expand Down

0 comments on commit f0a5e6b

Please sign in to comment.