Download this file
| 1 | package rootstate |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | |
| 8 | "golang.org/x/sys/unix" |
| 9 | ) |
| 10 | |
| 11 | func OpenAuthorityDirectory(path string) (*os.File, error) { |
| 12 | if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| 13 | return nil, os.ErrPermission |
| 14 | } |
| 15 | fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| 16 | if err != nil { |
| 17 | return nil, err |
| 18 | } |
| 19 | defer func() { |
| 20 | if fd >= 0 { |
| 21 | unix.Close(fd) |
| 22 | } |
| 23 | }() |
| 24 | for _, part := range append([]string{""}, strings.Split(strings.TrimPrefix(path, "/"), "/")...) { |
| 25 | if part != "" { |
| 26 | if !component(part) { |
| 27 | return nil, os.ErrPermission |
| 28 | } |
| 29 | next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 30 | if err != nil { |
| 31 | return nil, err |
| 32 | } |
| 33 | unix.Close(fd) |
| 34 | fd = next |
| 35 | } |
| 36 | if err := trusted(fd, 0, unix.S_IFDIR); err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | } |
| 40 | f := os.NewFile(uintptr(fd), path) |
| 41 | fd = -1 |
| 42 | return f, nil |
| 43 | } |
| 44 | |