package rootstate import ( "os" "path/filepath" "strings" "golang.org/x/sys/unix" ) func OpenAuthorityDirectory(path string) (*os.File, error) { if !filepath.IsAbs(path) || filepath.Clean(path) != path { return nil, os.ErrPermission } fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) if err != nil { return nil, err } defer func() { if fd >= 0 { unix.Close(fd) } }() for _, part := range append([]string{""}, strings.Split(strings.TrimPrefix(path, "/"), "/")...) { if part != "" { if !component(part) { return nil, os.ErrPermission } next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) if err != nil { return nil, err } unix.Close(fd) fd = next } if err := trusted(fd, 0, unix.S_IFDIR); err != nil { return nil, err } } f := os.NewFile(uintptr(fd), path) fd = -1 return f, nil }