2015-06-27 11:13:17 +08:00
|
|
|
// +build !windows
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
2019-09-27 10:01:07 +08:00
|
|
|
"fmt"
|
2017-03-03 04:53:06 +08:00
|
|
|
"os"
|
2015-06-27 11:13:17 +08:00
|
|
|
"strconv"
|
2017-05-10 05:38:27 +08:00
|
|
|
|
|
|
|
"golang.org/x/sys/unix"
|
2015-06-27 11:13:17 +08:00
|
|
|
)
|
|
|
|
|
2019-09-27 10:01:07 +08:00
|
|
|
// EnsureProcHandle returns whether or not the given file handle is on procfs.
|
|
|
|
func EnsureProcHandle(fh *os.File) error {
|
|
|
|
var buf unix.Statfs_t
|
|
|
|
if err := unix.Fstatfs(int(fh.Fd()), &buf); err != nil {
|
|
|
|
return fmt.Errorf("ensure %s is on procfs: %v", fh.Name(), err)
|
|
|
|
}
|
|
|
|
if buf.Type != unix.PROC_SUPER_MAGIC {
|
|
|
|
return fmt.Errorf("%s is not on procfs", fh.Name())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CloseExecFrom applies O_CLOEXEC to all file descriptors currently open for
|
|
|
|
// the process (except for those below the given fd value).
|
2015-06-27 11:13:17 +08:00
|
|
|
func CloseExecFrom(minFd int) error {
|
2019-09-27 10:01:07 +08:00
|
|
|
fdDir, err := os.Open("/proc/self/fd")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer fdDir.Close()
|
|
|
|
|
|
|
|
if err := EnsureProcHandle(fdDir); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fdList, err := fdDir.Readdirnames(-1)
|
2015-06-27 11:13:17 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-09-27 10:01:07 +08:00
|
|
|
for _, fdStr := range fdList {
|
|
|
|
fd, err := strconv.Atoi(fdStr)
|
|
|
|
// Ignore non-numeric file names.
|
2015-06-27 11:13:17 +08:00
|
|
|
if err != nil {
|
|
|
|
continue
|
|
|
|
}
|
2019-09-27 10:01:07 +08:00
|
|
|
// Ignore descriptors lower than our specified minimum.
|
2015-06-27 11:13:17 +08:00
|
|
|
if fd < minFd {
|
|
|
|
continue
|
|
|
|
}
|
2019-09-27 10:01:07 +08:00
|
|
|
// Intentionally ignore errors from unix.CloseOnExec -- the cases where
|
|
|
|
// this might fail are basically file descriptors that have already
|
|
|
|
// been closed (including and especially the one that was created when
|
|
|
|
// ioutil.ReadDir did the "opendir" syscall).
|
2017-05-10 05:38:27 +08:00
|
|
|
unix.CloseOnExec(fd)
|
2015-06-27 11:13:17 +08:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2017-03-03 04:53:06 +08:00
|
|
|
|
|
|
|
// NewSockPair returns a new unix socket pair
|
|
|
|
func NewSockPair(name string) (parent *os.File, child *os.File, err error) {
|
2017-05-10 05:38:27 +08:00
|
|
|
fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM|unix.SOCK_CLOEXEC, 0)
|
2017-03-03 04:53:06 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, err
|
|
|
|
}
|
|
|
|
return os.NewFile(uintptr(fds[1]), name+"-p"), os.NewFile(uintptr(fds[0]), name+"-c"), nil
|
|
|
|
}
|