Skip to content

Commit

Permalink
mountinfo: fix PrefixFilter() being too greedy
Browse files Browse the repository at this point in the history
The PrefixFilter matched on a literal "prefix", making it too greedy, and,
for example, filtering on "/a" prefix would also return mounts for
"/aaa" or "/abc".

This patch changes the matching to match on a prefix / parent _path_ instead.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
  • Loading branch information
thaJeztah committed Mar 4, 2021
1 parent 4836a5f commit f11a7ca
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 f11a7ca

Please sign in to comment.