Debian Codegraph @

validator.go

raw symbols SCIP
1 package fsutil
2
3 import (
4 "os"
5 "path/filepath"
6 "sort"
7 "strings"
8 "syscall"
9
10 "github.com/pkg/errors"
11 )
12
13 type parent struct {
14 dir string
15 last string
16 }
17
18 type Validator struct {
19 parentDirs []parent
20 }
21
22 func (v *Validator) HandleChange(kind ChangeKind, p string, fi os.FileInfo, err error) (retErr error) {
23 if err != nil {
24 return err
25 }
26 // test that all paths are in order and all parent dirs were present
27 if v.parentDirs == nil {
28 v.parentDirs = make([]parent, 1, 10)
29 }
30 if p != filepath.Clean(p) {
31 return errors.WithStack(&os.PathError{Path: p, Err: syscall.EINVAL, Op: "unclean path"})
32 }
33 if filepath.IsAbs(p) {
34 return errors.WithStack(&os.PathError{Path: p, Err: syscall.EINVAL, Op: "absolute path"})
35 }
36 dir := filepath.Dir(p)
37 base := filepath.Base(p)
38 if dir == "." {
39 dir = ""
40 }
41 if dir == ".." || strings.HasPrefix(p, filepath.FromSlash("../")) {
42 return errors.WithStack(&os.PathError{Path: p, Err: syscall.EINVAL, Op: "escape check"})
43 }
44
45 // find a parent dir from saved records
46 i := sort.Search(len(v.parentDirs), func(i int) bool {
47 return ComparePath(v.parentDirs[len(v.parentDirs)-1-i].dir, dir) <= 0
48 })
49 i = len(v.parentDirs) - 1 - i
50 if i != len(v.parentDirs)-1 { // skipping back to grandparent
51 v.parentDirs = v.parentDirs[:i+1]
52 }
53
54 if dir != v.parentDirs[len(v.parentDirs)-1].dir || v.parentDirs[i].last >= base {
55 return errors.Errorf("changes out of order: %q %q", p, filepath.Join(v.parentDirs[i].dir, v.parentDirs[i].last))
56 }
57 v.parentDirs[i].last = base
58 if kind != ChangeKindDelete && fi.IsDir() {
59 v.parentDirs = append(v.parentDirs, parent{
60 dir: filepath.Join(dir, base),
61 last: "",
62 })
63 }
64 // todo: validate invalid mode combinations
65 return err
66 }
67
68 func ComparePath(p1, p2 string) int {
69 // byte-by-byte comparison to be compatible with str<>str
70 min := min(len(p1), len(p2))
71 for i := 0; i < min; i++ {
72 switch {
73 case p1[i] == p2[i]:
74 continue
75 case p2[i] != filepath.Separator && p1[i] < p2[i] || p1[i] == filepath.Separator:
76 return -1
77 default:
78 return 1
79 }
80 }
81 return len(p1) - len(p2)
82 }
83
84 func min(x, y int) int {
85 if x < y {
86 return x
87 }
88 return y
89 }