Skip to content

Commit

Permalink
Merge pull request #61 from thaJeztah/stricter_prefix_filter
Browse files Browse the repository at this point in the history
mountinfo: fix PrefixFilter() being too greedy
  • Loading branch information
cpuguy83 committed Mar 8, 2021
2 parents 581c797 + f11a7ca commit b0f1fd7
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
11 changes: 8 additions & 3 deletions mountinfo/mountinfo_filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@ import "strings"
// stop: true if parsing should be stopped after the entry.
type FilterFunc func(*Info) (skip, stop bool)

// PrefixFilter discards all entries whose mount points
// do not start with a specific prefix.
// PrefixFilter discards all entries whose mount points do not start with, or
// are equal to the path specified in prefix. The prefix path must be absolute,
// have all symlinks resolved, and cleaned (i.e. no extra slashes or dots).
//
// PrefixFilter treats prefix as a path, not a partial prefix, which means that
// given "/foo", "/foo/bar" and "/foobar" entries, PrefixFilter("/foo") returns
// "/foo" and "/foo/bar", and discards "/foobar".
func PrefixFilter(prefix string) FilterFunc {
return func(m *Info) (bool, bool) {
skip := !strings.HasPrefix(m.Mountpoint, prefix)
skip := !strings.HasPrefix(m.Mountpoint+"/", prefix+"/")
return skip, false
}
}
Expand Down
31 changes: 31 additions & 0 deletions mountinfo/mountinfo_filters_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package mountinfo

import "testing"

func TestPrefixFilter(t *testing.T) {
tests := []struct {
prefix string
mountPoint string
shouldSkip bool
}{
{prefix: "/a", mountPoint: "/a", shouldSkip: false},
{prefix: "/a", mountPoint: "/a/b", shouldSkip: false},
{prefix: "/a", mountPoint: "/aa", shouldSkip: true},
{prefix: "/a", mountPoint: "/aa/b", shouldSkip: true},

// invalid prefix: prefix path must be cleaned and have no trailing slash
{prefix: "/a/", mountPoint: "/a", shouldSkip: true},
{prefix: "/a/", mountPoint: "/a/b", shouldSkip: true},
}
for _, tc := range tests {
filter := PrefixFilter(tc.prefix)
skip, _ := filter(&Info{Mountpoint: tc.mountPoint})
if skip != tc.shouldSkip {
if tc.shouldSkip {
t.Errorf("prefix %q: expected %q to be skipped", tc.prefix, tc.mountPoint)
} else {
t.Errorf("prefix %q: expected %q not to be skipped", tc.prefix, tc.mountPoint)
}
}
}
}

0 comments on commit b0f1fd7

Please sign in to comment.