refactor(cli): rename operator command to tht
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
//go:build !windows
|
||||
|
||||
package safeio
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// ReadCanonicalRegular opens an absolute canonical path component by component from the root
|
||||
// descriptor. O_NOFOLLOW rejects symlinks at every component, and the open directory descriptors
|
||||
// prevent later parent replacement from redirecting the final open.
|
||||
func ReadCanonicalRegular(path string, maximum int64) ([]byte, error) {
|
||||
if err := ValidateCanonicalPath(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
components := strings.Split(strings.TrimPrefix(path, string(os.PathSeparator)), string(os.PathSeparator))
|
||||
if len(components) == 0 || components[0] == "" {
|
||||
return nil, ErrUnsafeFile
|
||||
}
|
||||
|
||||
directory, err := unix.Open(string(os.PathSeparator), unix.O_RDONLY|unix.O_CLOEXEC|unix.O_DIRECTORY, 0)
|
||||
if err != nil {
|
||||
return nil, ErrUnsafeFile
|
||||
}
|
||||
directories := []int{directory}
|
||||
defer func() { closeUnixDescriptors(directories) }()
|
||||
|
||||
for _, component := range components[:len(components)-1] {
|
||||
nextDirectory, err := unix.Openat(directory, component, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0)
|
||||
if err != nil {
|
||||
return nil, ErrUnsafeFile
|
||||
}
|
||||
directory = nextDirectory
|
||||
directories = append(directories, directory)
|
||||
}
|
||||
|
||||
descriptor, err := unix.Openat(directory, components[len(components)-1], unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
return nil, ErrUnsafeFile
|
||||
}
|
||||
file := os.NewFile(uintptr(descriptor), "tht-safeio")
|
||||
if file == nil {
|
||||
unix.Close(descriptor)
|
||||
return nil, ErrUnsafeFile
|
||||
}
|
||||
defer file.Close()
|
||||
return readBoundedRegularFile(path, file, maximum)
|
||||
}
|
||||
|
||||
func closeUnixDescriptors(descriptors []int) {
|
||||
for _, descriptor := range descriptors {
|
||||
unix.Close(descriptor)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user