| 1 | //go:build !darwin && !dragonfly && !freebsd && !illumos && !linux && !netbsd && !openbsd && !windows |
| 2 | |
| 3 | package engine |
| 4 | |
| 5 | import ( |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | ) |
| 11 | |
| 12 | func cacheParentDir(baseDir string) string { |
| 13 | return filepath.Join(filepath.Clean(baseDir), cacheSubdir) |
| 14 | } |
| 15 | |
| 16 | func mkdirPrivate(path string) error { |
| 17 | return os.Mkdir(path, 0o700) |
| 18 | } |
| 19 | |
| 20 | func ensurePrivateParentDir(parent string) error { |
| 21 | if err := os.MkdirAll(parent, 0o700); err != nil { |
| 22 | return err |
| 23 | } |
| 24 | return verifyPrivateDir(parent) |
| 25 | } |
| 26 | |
| 27 | func verifyPrivateDir(path string) error { |
| 28 | info, err := os.Lstat(path) |
| 29 | if err != nil { |
| 30 | return err |
| 31 | } |
| 32 | if info.Mode()&os.ModeSymlink != 0 { |
| 33 | return fmt.Errorf("engine: refusing symlink cache directory %s", path) |
| 34 | } |
| 35 | if !info.IsDir() { |
| 36 | return fmt.Errorf("engine: cache path %s is not a directory", path) |
| 37 | } |
| 38 | return nil |
| 39 | } |
| 40 | |
| 41 | func verifyOwnedRegularFile(info os.FileInfo, path string) error { |
| 42 | if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() { |
| 43 | return fmt.Errorf("engine: refusing non-regular cache file %s", path) |
| 44 | } |
| 45 | return nil |
| 46 | } |
| 47 | |
| 48 | func openNoFollowFile(path string, flag int, perm os.FileMode) (*os.File, error) { |
| 49 | if info, err := os.Lstat(path); err == nil { |
| 50 | if err := verifyOwnedRegularFile(info, path); err != nil { |
| 51 | return nil, err |
| 52 | } |
| 53 | } else if !errors.Is(err, os.ErrNotExist) { |
| 54 | return nil, err |
| 55 | } |
| 56 | file, err := os.OpenFile(path, flag, perm) |
| 57 | if err != nil { |
| 58 | return nil, err |
| 59 | } |
| 60 | info, err := file.Stat() |
| 61 | if err != nil { |
| 62 | _ = file.Close() |
| 63 | return nil, err |
| 64 | } |
| 65 | if !info.Mode().IsRegular() { |
| 66 | _ = file.Close() |
| 67 | return nil, fmt.Errorf("engine: refusing non-regular cache file %s", path) |
| 68 | } |
| 69 | return file, nil |
| 70 | } |
| 71 | |
| 72 | func openRootRegularNoFollow(root *os.Root, cacheDir, nativeRel string) (*os.File, error) { |
| 73 | fullPath := filepath.Join(cacheDir, nativeRel) |
| 74 | linfo, err := root.Lstat(nativeRel) |
| 75 | if err != nil { |
| 76 | return nil, err |
| 77 | } |
| 78 | if err := verifyOwnedRegularFile(linfo, fullPath); err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | file, err := root.Open(nativeRel) |
| 82 | if err != nil { |
| 83 | return nil, err |
| 84 | } |
| 85 | info, err := file.Stat() |
| 86 | if err != nil { |
| 87 | _ = file.Close() |
| 88 | return nil, err |
| 89 | } |
| 90 | if err := verifyOwnedRegularFile(info, fullPath); err != nil { |
| 91 | _ = file.Close() |
| 92 | return nil, err |
| 93 | } |
| 94 | return file, nil |
| 95 | } |
| 96 |