lib/fs: Evaluate root when watching not on fs creation (fixes #5043) (#5105)

This commit is contained in:
Simon Frei 2018-08-11 22:24:36 +02:00 committed by Jakob Borg
parent b37c05c6b8
commit e20679afe1
5 changed files with 83 additions and 53 deletions

View File

@ -26,7 +26,6 @@ var (
// All paths are relative to the root and cannot (should not) escape the root directory. // All paths are relative to the root and cannot (should not) escape the root directory.
type BasicFilesystem struct { type BasicFilesystem struct {
root string root string
rootSymlinkEvaluated string
} }
func newBasicFilesystem(root string) *BasicFilesystem { func newBasicFilesystem(root string) *BasicFilesystem {
@ -36,7 +35,8 @@ func newBasicFilesystem(root string) *BasicFilesystem {
// C:\somedir\ -> C:\somedir\\ -> C:\somedir // C:\somedir\ -> C:\somedir\\ -> C:\somedir
// This way in the tests, we get away without OS specific separators // This way in the tests, we get away without OS specific separators
// in the test configs. // in the test configs.
root = filepath.Dir(root + string(filepath.Separator)) sep := string(filepath.Separator)
root = filepath.Dir(root + sep)
// Attempt tilde expansion; leave unchanged in case of error // Attempt tilde expansion; leave unchanged in case of error
if path, err := ExpandTilde(root); err == nil { if path, err := ExpandTilde(root); err == nil {
@ -53,34 +53,17 @@ func newBasicFilesystem(root string) *BasicFilesystem {
} }
} }
rootSymlinkEvaluated, err := filepath.EvalSymlinks(root)
if err != nil {
rootSymlinkEvaluated = root
}
return &BasicFilesystem{
root: adjustRoot(root),
rootSymlinkEvaluated: adjustRoot(rootSymlinkEvaluated),
}
}
func adjustRoot(root string) string {
// Attempt to enable long filename support on Windows. We may still not // Attempt to enable long filename support on Windows. We may still not
// have an absolute path here if the previous steps failed. // have an absolute path here if the previous steps failed.
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
if filepath.IsAbs(root) && !strings.HasPrefix(root, `\\`) { root = longFilenameSupport(root)
root = `\\?\` + root } else if !strings.HasSuffix(root, sep) {
}
return root
}
// If we're not on Windows, we want the path to end with a slash to // If we're not on Windows, we want the path to end with a slash to
// penetrate symlinks. On Windows, paths must not end with a slash. // penetrate symlinks. On Windows, paths must not end with a slash.
if root[len(root)-1] != filepath.Separator { root = root + sep
root = root + string(filepath.Separator)
} }
return root return &BasicFilesystem{root}
} }
// rooted expands the relative path to the full path that is then used with os // rooted expands the relative path to the full path that is then used with os
@ -91,14 +74,6 @@ func (f *BasicFilesystem) rooted(rel string) (string, error) {
return rooted(rel, f.root) return rooted(rel, f.root)
} }
// rootedSymlinkEvaluated does the same as rooted, but the returned path will not
// contain any symlinks. package. If the relative path somehow causes the final
// path to escape the root directory, this returns an error, to prevent accessing
// files that are not in the shared directory.
func (f *BasicFilesystem) rootedSymlinkEvaluated(rel string) (string, error) {
return rooted(rel, f.rootSymlinkEvaluated)
}
func rooted(rel, root string) (string, error) { func rooted(rel, root string) (string, error) {
// The root must not be empty. // The root must not be empty.
if root == "" { if root == "" {
@ -138,10 +113,6 @@ func (f *BasicFilesystem) unrooted(path string) string {
return rel(path, f.root) return rel(path, f.root)
} }
func (f *BasicFilesystem) unrootedSymlinkEvaluated(path string) string {
return rel(path, f.rootSymlinkEvaluated)
}
func rel(path, prefix string) string { func rel(path, prefix string) string {
return strings.TrimPrefix(strings.TrimPrefix(path, prefix), string(PathSeparator)) return strings.TrimPrefix(strings.TrimPrefix(path, prefix), string(PathSeparator))
} }
@ -372,3 +343,13 @@ func (e fsFileInfo) IsRegular() bool {
// Must use fsFileInfo.Mode() because it may apply magic. // Must use fsFileInfo.Mode() because it may apply magic.
return e.Mode()&ModeType == 0 return e.Mode()&ModeType == 0
} }
// longFilenameSupport adds the necessary prefix to the path to enable long
// filename support on windows if necessary.
// This does NOT check the current system, i.e. will also take effect on unix paths.
func longFilenameSupport(path string) string {
if filepath.IsAbs(path) && !strings.HasPrefix(path, `\\`) {
return `\\?\` + path
}
return path
}

View File

@ -12,6 +12,7 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"sort" "sort"
"strings"
"testing" "testing"
"time" "time"
) )
@ -449,3 +450,35 @@ func TestRooted(t *testing.T) {
} }
} }
} }
func TestNewBasicFilesystem(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("non-windows root paths")
}
testCases := []struct {
input string
expectedRoot string
expectedURI string
}{
{"/foo/bar/baz", "/foo/bar/baz/", "/foo/bar/baz/"},
{"/foo/bar/baz/", "/foo/bar/baz/", "/foo/bar/baz/"},
{"", "/", "/"},
{"/", "/", "/"},
}
for _, testCase := range testCases {
fs := newBasicFilesystem(testCase.input)
if fs.root != testCase.expectedRoot {
t.Errorf("root %q != %q", fs.root, testCase.expectedRoot)
}
if fs.URI() != testCase.expectedURI {
t.Errorf("uri %q != %q", fs.URI(), testCase.expectedURI)
}
}
fs := newBasicFilesystem("relative/path")
if fs.root == "relative/path" || !strings.HasPrefix(fs.root, string(PathSeparator)) {
t.Errorf(`newBasicFilesystem("relative/path").root == %q, expected absolutification`, fs.root)
}
}

View File

@ -13,6 +13,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"path/filepath" "path/filepath"
"runtime"
"strings" "strings"
"github.com/syncthing/notify" "github.com/syncthing/notify"
@ -24,7 +25,15 @@ import (
var backendBuffer = 500 var backendBuffer = 500
func (f *BasicFilesystem) Watch(name string, ignore Matcher, ctx context.Context, ignorePerms bool) (<-chan Event, error) { func (f *BasicFilesystem) Watch(name string, ignore Matcher, ctx context.Context, ignorePerms bool) (<-chan Event, error) {
absName, err := f.rootedSymlinkEvaluated(name) evalRoot, err := filepath.EvalSymlinks(f.root)
if err != nil {
return nil, err
}
if runtime.GOOS == "windows" {
evalRoot = longFilenameSupport(evalRoot)
}
absName, err := rooted(name, evalRoot)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -39,7 +48,7 @@ func (f *BasicFilesystem) Watch(name string, ignore Matcher, ctx context.Context
if ignore.SkipIgnoredDirs() { if ignore.SkipIgnoredDirs() {
absShouldIgnore := func(absPath string) bool { absShouldIgnore := func(absPath string) bool {
return ignore.ShouldIgnore(f.unrootedChecked(absPath)) return ignore.ShouldIgnore(f.unrootedChecked(absPath, evalRoot))
} }
err = notify.WatchWithFilter(filepath.Join(absName, "..."), backendChan, absShouldIgnore, eventMask) err = notify.WatchWithFilter(filepath.Join(absName, "..."), backendChan, absShouldIgnore, eventMask)
} else { } else {
@ -53,12 +62,12 @@ func (f *BasicFilesystem) Watch(name string, ignore Matcher, ctx context.Context
return nil, err return nil, err
} }
go f.watchLoop(name, backendChan, outChan, ignore, ctx) go f.watchLoop(name, evalRoot, backendChan, outChan, ignore, ctx)
return outChan, nil return outChan, nil
} }
func (f *BasicFilesystem) watchLoop(name string, backendChan chan notify.EventInfo, outChan chan<- Event, ignore Matcher, ctx context.Context) { func (f *BasicFilesystem) watchLoop(name, evalRoot string, backendChan chan notify.EventInfo, outChan chan<- Event, ignore Matcher, ctx context.Context) {
for { for {
// Detect channel overflow // Detect channel overflow
if len(backendChan) == backendBuffer { if len(backendChan) == backendBuffer {
@ -77,7 +86,7 @@ func (f *BasicFilesystem) watchLoop(name string, backendChan chan notify.EventIn
select { select {
case ev := <-backendChan: case ev := <-backendChan:
relPath := f.unrootedChecked(ev.Path()) relPath := f.unrootedChecked(ev.Path(), evalRoot)
if ignore.ShouldIgnore(relPath) { if ignore.ShouldIgnore(relPath) {
l.Debugln(f.Type(), f.URI(), "Watch: Ignoring", relPath) l.Debugln(f.Type(), f.URI(), "Watch: Ignoring", relPath)
continue continue
@ -110,12 +119,13 @@ func (f *BasicFilesystem) eventType(notifyType notify.Event) EventType {
// unrooted). It panics if the given path is not a subpath and handles the // unrooted). It panics if the given path is not a subpath and handles the
// special case when the given path is the folder root without a trailing // special case when the given path is the folder root without a trailing
// pathseparator. // pathseparator.
func (f *BasicFilesystem) unrootedChecked(absPath string) string { func (f *BasicFilesystem) unrootedChecked(absPath, root string) string {
if absPath+string(PathSeparator) == f.rootSymlinkEvaluated { absPath = f.resolveWin83(absPath)
if absPath+string(PathSeparator) == root {
return "." return "."
} }
if !strings.HasPrefix(absPath, f.rootSymlinkEvaluated) { if !strings.HasPrefix(absPath, root) {
panic(fmt.Sprintf("bug: Notify backend is processing a change outside of the filesystem root: root==%v, rootSymEval==%v, path==%v", f.root, f.rootSymlinkEvaluated, absPath)) panic(fmt.Sprintf("bug: Notify backend is processing a change outside of the filesystem root: f.root==%v, root==%v, path==%v", f.root, root, absPath))
} }
return f.unrootedSymlinkEvaluated(f.resolveWin83(absPath)) return rel(absPath, root)
} }

View File

@ -33,11 +33,17 @@ func TestMain(m *testing.M) {
if err != nil { if err != nil {
panic("Cannot get absolute path to working dir") panic("Cannot get absolute path to working dir")
} }
dir, err = filepath.EvalSymlinks(dir) dir, err = filepath.EvalSymlinks(dir)
if err != nil { if err != nil {
panic("Cannot get real path to working dir") panic("Cannot get real path to working dir")
} }
testDirAbs = filepath.Join(dir, testDir) testDirAbs = filepath.Join(dir, testDir)
if runtime.GOOS == "windows" {
testDirAbs = longFilenameSupport(testDirAbs)
}
testFs = NewFilesystem(FilesystemTypeBasic, testDirAbs) testFs = NewFilesystem(FilesystemTypeBasic, testDirAbs)
backendBuffer = 10 backendBuffer = 10
@ -154,7 +160,7 @@ func TestWatchOutside(t *testing.T) {
} }
cancel() cancel()
}() }()
fs.watchLoop(".", backendChan, outChan, fakeMatcher{}, ctx) fs.watchLoop(".", testDirAbs, backendChan, outChan, fakeMatcher{}, ctx)
}() }()
backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(testDirAbs), "outside")) backendChan <- fakeEventInfo(filepath.Join(filepath.Dir(testDirAbs), "outside"))
@ -177,7 +183,7 @@ func TestWatchSubpath(t *testing.T) {
fs := newBasicFilesystem(testDirAbs) fs := newBasicFilesystem(testDirAbs)
abs, _ := fs.rooted("sub") abs, _ := fs.rooted("sub")
go fs.watchLoop("sub", backendChan, outChan, fakeMatcher{}, ctx) go fs.watchLoop("sub", testDirAbs, backendChan, outChan, fakeMatcher{}, ctx)
backendChan <- fakeEventInfo(filepath.Join(abs, "file")) backendChan <- fakeEventInfo(filepath.Join(abs, "file"))
@ -291,7 +297,7 @@ func TestUnrootedChecked(t *testing.T) {
} }
}() }()
fs := newBasicFilesystem(testDirAbs) fs := newBasicFilesystem(testDirAbs)
unrooted = fs.unrootedChecked("/random/other/path") unrooted = fs.unrootedChecked("/random/other/path", testDirAbs)
} }
func TestWatchIssue4877(t *testing.T) { func TestWatchIssue4877(t *testing.T) {

View File

@ -170,12 +170,12 @@ func (f *BasicFilesystem) resolveWin83(absPath string) string {
} }
// Failed getting the long path. Return the part of the path which is // Failed getting the long path. Return the part of the path which is
// already a long path. // already a long path.
for absPath = filepath.Dir(absPath); strings.HasPrefix(absPath, f.rootSymlinkEvaluated); absPath = filepath.Dir(absPath) { for absPath = filepath.Dir(absPath); strings.HasPrefix(absPath, f.root); absPath = filepath.Dir(absPath) {
if !isMaybeWin83(absPath) { if !isMaybeWin83(absPath) {
return absPath return absPath
} }
} }
return f.rootSymlinkEvaluated return f.root
} }
func isMaybeWin83(absPath string) bool { func isMaybeWin83(absPath string) bool {