From e97ed216f29fa66450cfc385abc3b2166b7453e2 Mon Sep 17 00:00:00 2001 From: HFO4 <912394456@qq.com> Date: Fri, 20 Dec 2019 15:08:04 +0800 Subject: [PATCH] Feat: finish WebDAV adaptation --- models/file.go | 5 + models/folder.go | 3 + pkg/filesystem/manage.go | 2 +- pkg/webdav/file.go | 172 +---- pkg/webdav/file_test.go | 1183 --------------------------------- pkg/webdav/if_test.go | 322 --------- pkg/webdav/lock_test.go | 735 -------------------- pkg/webdav/mem.go | 483 -------------- pkg/webdav/prop.go | 1 + pkg/webdav/prop_test.go | 716 -------------------- pkg/webdav/webdav.go | 11 +- pkg/webdav/webdav_test.go | 349 ---------- pkg/webdav/xml_test.go | 906 ------------------------- routers/controllers/webdav.go | 1 - routers/router.go | 1 + 15 files changed, 43 insertions(+), 4847 deletions(-) delete mode 100644 pkg/webdav/file_test.go delete mode 100644 pkg/webdav/if_test.go delete mode 100644 pkg/webdav/lock_test.go delete mode 100644 pkg/webdav/mem.go delete mode 100644 pkg/webdav/prop_test.go delete mode 100644 pkg/webdav/webdav_test.go delete mode 100644 pkg/webdav/xml_test.go diff --git a/models/file.go b/models/file.go index a72bb53..7045374 100644 --- a/models/file.go +++ b/models/file.go @@ -183,6 +183,11 @@ func (file *File) GetSize() uint64 { func (file *File) ModTime() time.Time { return file.UpdatedAt } + func (file *File) IsDir() bool { return false } + +func (file *File) GetPosition() string { + return file.Position +} diff --git a/models/folder.go b/models/folder.go index 18aaf01..efc3dd0 100644 --- a/models/folder.go +++ b/models/folder.go @@ -280,3 +280,6 @@ func (folder *Folder) ModTime() time.Time { func (folder *Folder) IsDir() bool { return true } +func (folder *Folder) GetPosition() string { + return folder.Position +} diff --git a/pkg/filesystem/manage.go b/pkg/filesystem/manage.go index 697fc01..8226060 100644 --- a/pkg/filesystem/manage.go +++ b/pkg/filesystem/manage.go @@ -100,7 +100,7 @@ func (fs *FileSystem) Copy(ctx context.Context, dirs, files []uint, src, dst str return nil } -// Move 移动文件和目录 +// Move 移动文件和目录, 将id列表dirs和files从src移动至dst func (fs *FileSystem) Move(ctx context.Context, dirs, files []uint, src, dst string) error { // 获取目的目录 isDstExist, dstFolder := fs.IsPathExist(dst) diff --git a/pkg/webdav/file.go b/pkg/webdav/file.go index 4f06802..cb20e23 100644 --- a/pkg/webdav/file.go +++ b/pkg/webdav/file.go @@ -8,12 +8,9 @@ import ( "context" model "github.com/HFO4/cloudreve/models" "github.com/HFO4/cloudreve/pkg/filesystem" - "io" "net/http" - "os" "path" "path/filepath" - "strings" ) // slashClean is equivalent to but slightly more efficient than @@ -25,156 +22,43 @@ func slashClean(name string) string { return path.Clean(name) } -// A FileSystem implements access to a collection of named files. The elements -// in a file path are separated by slash ('/', U+002F) characters, regardless -// of host operating system convention. -// -// Each method has the same semantics as the os package's function of the same -// name. -// -// Note that the os.Rename documentation says that "OS-specific restrictions -// might apply". In particular, whether or not renaming a file or directory -// overwriting another existing file or directory is an error is OS-dependent. -type FileSystem interface { - Mkdir(ctx context.Context, name string, perm os.FileMode) error - OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) - RemoveAll(ctx context.Context, name string) error - Rename(ctx context.Context, oldName, newName string) error - Stat(ctx context.Context, name string) (os.FileInfo, error) -} - -// A File is returned by a FileSystem's OpenFile method and can be served by a -// Handler. -// -// A File may optionally implement the DeadPropsHolder interface, if it can -// load and save dead properties. -type File interface { - http.File - io.Writer -} - -// A AdapterFS implements FileSystem using the native file system restricted to a -// specific directory tree. -// -// While the FileSystem.OpenFile method takes '/'-separated paths, a AdapterFS's -// string value is a filename on the native file system, not a URL, so it is -// separated by filepath.Separator, which isn't necessarily '/'. -// -// An empty AdapterFS is treated as ".". -type AdapterFS string - -func (d AdapterFS) resolve(name string) string { - // This implementation is based on AdapterFS.Open's code in the standard net/http package. - if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || - strings.Contains(name, "\x00") { - return "" - } - dir := string(d) - if dir == "" { - dir = "." - } - return filepath.Join(dir, filepath.FromSlash(slashClean(name))) -} - -func (d AdapterFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error { - if name = d.resolve(name); name == "" { - return os.ErrNotExist - } - return os.Mkdir(name, perm) -} - -func (d AdapterFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { - if name = d.resolve(name); name == "" { - return nil, os.ErrNotExist - } - f, err := os.OpenFile(name, flag, perm) - if err != nil { - return nil, err - } - return f, nil -} - -func (d AdapterFS) RemoveAll(ctx context.Context, name string) error { - if name = d.resolve(name); name == "" { - return os.ErrNotExist - } - if name == filepath.Clean(string(d)) { - // Prohibit removing the virtual root directory. - return os.ErrInvalid - } - return os.RemoveAll(name) -} - -func (d AdapterFS) Rename(ctx context.Context, oldName, newName string) error { - if oldName = d.resolve(oldName); oldName == "" { - return os.ErrNotExist - } - if newName = d.resolve(newName); newName == "" { - return os.ErrNotExist - } - if root := filepath.Clean(string(d)); root == oldName || root == newName { - // Prohibit renaming from or to the virtual root directory. - return os.ErrInvalid - } - return os.Rename(oldName, newName) -} - -func (d AdapterFS) Stat(ctx context.Context, name string) (os.FileInfo, error) { - if name = d.resolve(name); name == "" { - return nil, os.ErrNotExist - } - return os.Stat(name) -} - // moveFiles moves files and/or directories from src to dst. // // See section 9.9.4 for when various HTTP status codes apply. -func moveFiles(ctx context.Context, fs FileSystem, src, dst string, overwrite bool) (status int, err error) { - created := false - if _, err := fs.Stat(ctx, dst); err != nil { - if !os.IsNotExist(err) { - return http.StatusForbidden, err - } - created = true - } else if overwrite { - // Section 9.9.3 says that "If a resource exists at the destination - // and the Overwrite header is "T", then prior to performing the move, - // the server must perform a DELETE with "Depth: infinity" on the - // destination resource. - if err := fs.RemoveAll(ctx, dst); err != nil { - return http.StatusForbidden, err - } +func moveFiles(ctx context.Context, fs *filesystem.FileSystem, src FileInfo, dst string, overwrite bool) (status int, err error) { + + var ( + fileIDs []uint + folderIDs []uint + ) + if src.IsDir() { + fileIDs = []uint{src.(*model.Folder).ID} } else { - return http.StatusPreconditionFailed, os.ErrExist - } - if err := fs.Rename(ctx, src, dst); err != nil { - return http.StatusForbidden, err + folderIDs = []uint{src.(*model.File).ID} } - if created { - return http.StatusCreated, nil - } - return http.StatusNoContent, nil -} -func copyProps(dst, src File) error { - d, ok := dst.(DeadPropsHolder) - if !ok { - return nil - } - s, ok := src.(DeadPropsHolder) - if !ok { - return nil + // 判断是否为重命名 + if src.GetPosition() == path.Dir(dst) { + err = fs.Rename( + ctx, + fileIDs, + folderIDs, + path.Base(dst), + ) + } else { + err = fs.Move( + ctx, + fileIDs, + folderIDs, + src.GetPosition(), + path.Dir(dst), + ) } - m, err := s.DeadProps() + if err != nil { - return err - } - props := make([]Property, 0, len(m)) - for _, prop := range m { - props = append(props, prop) + return http.StatusInternalServerError, err } - _, err = d.Patch([]Proppatch{{Props: props}}) - return err + return http.StatusNoContent, nil } // copyFiles copies files and/or directories from src to dst. diff --git a/pkg/webdav/file_test.go b/pkg/webdav/file_test.go deleted file mode 100644 index f192167..0000000 --- a/pkg/webdav/file_test.go +++ /dev/null @@ -1,1183 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package webdav - -import ( - "context" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "os" - "path" - "path/filepath" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "testing" -) - -func TestSlashClean(t *testing.T) { - testCases := []string{ - "", - ".", - "/", - "/./", - "//", - "//.", - "//a", - "/a", - "/a/b/c", - "/a//b/./../c/d/", - "a", - "a/b/c", - } - for _, tc := range testCases { - got := slashClean(tc) - want := path.Clean("/" + tc) - if got != want { - t.Errorf("tc=%q: got %q, want %q", tc, got, want) - } - } -} - -func TestDirResolve(t *testing.T) { - testCases := []struct { - dir, name, want string - }{ - {"/", "", "/"}, - {"/", "/", "/"}, - {"/", ".", "/"}, - {"/", "./a", "/a"}, - {"/", "..", "/"}, - {"/", "..", "/"}, - {"/", "../", "/"}, - {"/", "../.", "/"}, - {"/", "../a", "/a"}, - {"/", "../..", "/"}, - {"/", "../bar/a", "/bar/a"}, - {"/", "../baz/a", "/baz/a"}, - {"/", "...", "/..."}, - {"/", ".../a", "/.../a"}, - {"/", ".../..", "/"}, - {"/", "a", "/a"}, - {"/", "a/./b", "/a/b"}, - {"/", "a/../../b", "/b"}, - {"/", "a/../b", "/b"}, - {"/", "a/b", "/a/b"}, - {"/", "a/b/c/../../d", "/a/d"}, - {"/", "a/b/c/../../../d", "/d"}, - {"/", "a/b/c/../../../../d", "/d"}, - {"/", "a/b/c/d", "/a/b/c/d"}, - - {"/foo/bar", "", "/foo/bar"}, - {"/foo/bar", "/", "/foo/bar"}, - {"/foo/bar", ".", "/foo/bar"}, - {"/foo/bar", "./a", "/foo/bar/a"}, - {"/foo/bar", "..", "/foo/bar"}, - {"/foo/bar", "../", "/foo/bar"}, - {"/foo/bar", "../.", "/foo/bar"}, - {"/foo/bar", "../a", "/foo/bar/a"}, - {"/foo/bar", "../..", "/foo/bar"}, - {"/foo/bar", "../bar/a", "/foo/bar/bar/a"}, - {"/foo/bar", "../baz/a", "/foo/bar/baz/a"}, - {"/foo/bar", "...", "/foo/bar/..."}, - {"/foo/bar", ".../a", "/foo/bar/.../a"}, - {"/foo/bar", ".../..", "/foo/bar"}, - {"/foo/bar", "a", "/foo/bar/a"}, - {"/foo/bar", "a/./b", "/foo/bar/a/b"}, - {"/foo/bar", "a/../../b", "/foo/bar/b"}, - {"/foo/bar", "a/../b", "/foo/bar/b"}, - {"/foo/bar", "a/b", "/foo/bar/a/b"}, - {"/foo/bar", "a/b/c/../../d", "/foo/bar/a/d"}, - {"/foo/bar", "a/b/c/../../../d", "/foo/bar/d"}, - {"/foo/bar", "a/b/c/../../../../d", "/foo/bar/d"}, - {"/foo/bar", "a/b/c/d", "/foo/bar/a/b/c/d"}, - - {"/foo/bar/", "", "/foo/bar"}, - {"/foo/bar/", "/", "/foo/bar"}, - {"/foo/bar/", ".", "/foo/bar"}, - {"/foo/bar/", "./a", "/foo/bar/a"}, - {"/foo/bar/", "..", "/foo/bar"}, - - {"/foo//bar///", "", "/foo/bar"}, - {"/foo//bar///", "/", "/foo/bar"}, - {"/foo//bar///", ".", "/foo/bar"}, - {"/foo//bar///", "./a", "/foo/bar/a"}, - {"/foo//bar///", "..", "/foo/bar"}, - - {"/x/y/z", "ab/c\x00d/ef", ""}, - - {".", "", "."}, - {".", "/", "."}, - {".", ".", "."}, - {".", "./a", "a"}, - {".", "..", "."}, - {".", "..", "."}, - {".", "../", "."}, - {".", "../.", "."}, - {".", "../a", "a"}, - {".", "../..", "."}, - {".", "../bar/a", "bar/a"}, - {".", "../baz/a", "baz/a"}, - {".", "...", "..."}, - {".", ".../a", ".../a"}, - {".", ".../..", "."}, - {".", "a", "a"}, - {".", "a/./b", "a/b"}, - {".", "a/../../b", "b"}, - {".", "a/../b", "b"}, - {".", "a/b", "a/b"}, - {".", "a/b/c/../../d", "a/d"}, - {".", "a/b/c/../../../d", "d"}, - {".", "a/b/c/../../../../d", "d"}, - {".", "a/b/c/d", "a/b/c/d"}, - - {"", "", "."}, - {"", "/", "."}, - {"", ".", "."}, - {"", "./a", "a"}, - {"", "..", "."}, - } - - for _, tc := range testCases { - d := AdapterFS(filepath.FromSlash(tc.dir)) - if got := filepath.ToSlash(d.resolve(tc.name)); got != tc.want { - t.Errorf("dir=%q, name=%q: got %q, want %q", tc.dir, tc.name, got, tc.want) - } - } -} - -func TestWalk(t *testing.T) { - type walkStep struct { - name, frag string - final bool - } - - testCases := []struct { - dir string - want []walkStep - }{ - {"", []walkStep{ - {"", "", true}, - }}, - {"/", []walkStep{ - {"", "", true}, - }}, - {"/a", []walkStep{ - {"", "a", true}, - }}, - {"/a/", []walkStep{ - {"", "a", true}, - }}, - {"/a/b", []walkStep{ - {"", "a", false}, - {"a", "b", true}, - }}, - {"/a/b/", []walkStep{ - {"", "a", false}, - {"a", "b", true}, - }}, - {"/a/b/c", []walkStep{ - {"", "a", false}, - {"a", "b", false}, - {"b", "c", true}, - }}, - // The following test case is the one mentioned explicitly - // in the method description. - {"/foo/bar/x", []walkStep{ - {"", "foo", false}, - {"foo", "bar", false}, - {"bar", "x", true}, - }}, - } - - ctx := context.Background() - - for _, tc := range testCases { - fs := NewMemFS().(*memFS) - - parts := strings.Split(tc.dir, "/") - for p := 2; p < len(parts); p++ { - d := strings.Join(parts[:p], "/") - if err := fs.Mkdir(ctx, d, 0666); err != nil { - t.Errorf("tc.dir=%q: mkdir: %q: %v", tc.dir, d, err) - } - } - - i, prevFrag := 0, "" - err := fs.walk("test", tc.dir, func(dir *memFSNode, frag string, final bool) error { - got := walkStep{ - name: prevFrag, - frag: frag, - final: final, - } - want := tc.want[i] - - if got != want { - return fmt.Errorf("got %+v, want %+v", got, want) - } - i, prevFrag = i+1, frag - return nil - }) - if err != nil { - t.Errorf("tc.dir=%q: %v", tc.dir, err) - } - } -} - -// find appends to ss the names of the named file and its children. It is -// analogous to the Unix find command. -// -// The returned strings are not guaranteed to be in any particular order. -func find(ctx context.Context, ss []string, fs FileSystem, name string) ([]string, error) { - stat, err := fs.Stat(ctx, name) - if err != nil { - return nil, err - } - ss = append(ss, name) - if stat.IsDir() { - f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0) - if err != nil { - return nil, err - } - defer f.Close() - children, err := f.Readdir(-1) - if err != nil { - return nil, err - } - for _, c := range children { - ss, err = find(ctx, ss, fs, path.Join(name, c.Name())) - if err != nil { - return nil, err - } - } - } - return ss, nil -} - -func testFS(t *testing.T, fs FileSystem) { - errStr := func(err error) string { - switch { - case os.IsExist(err): - return "errExist" - case os.IsNotExist(err): - return "errNotExist" - case err != nil: - return "err" - } - return "ok" - } - - // The non-"find" non-"stat" test cases should change the file system state. The - // indentation of the "find"s and "stat"s helps distinguish such test cases. - testCases := []string{ - " stat / want dir", - " stat /a want errNotExist", - " stat /d want errNotExist", - " stat /d/e want errNotExist", - "create /a A want ok", - " stat /a want 1", - "create /d/e EEE want errNotExist", - "mk-dir /a want errExist", - "mk-dir /d/m want errNotExist", - "mk-dir /d want ok", - " stat /d want dir", - "create /d/e EEE want ok", - " stat /d/e want 3", - " find / /a /d /d/e", - "create /d/f FFFF want ok", - "create /d/g GGGGGGG want ok", - "mk-dir /d/m want ok", - "mk-dir /d/m want errExist", - "create /d/m/p PPPPP want ok", - " stat /d/e want 3", - " stat /d/f want 4", - " stat /d/g want 7", - " stat /d/h want errNotExist", - " stat /d/m want dir", - " stat /d/m/p want 5", - " find / /a /d /d/e /d/f /d/g /d/m /d/m/p", - "rm-all /d want ok", - " stat /a want 1", - " stat /d want errNotExist", - " stat /d/e want errNotExist", - " stat /d/f want errNotExist", - " stat /d/g want errNotExist", - " stat /d/m want errNotExist", - " stat /d/m/p want errNotExist", - " find / /a", - "mk-dir /d/m want errNotExist", - "mk-dir /d want ok", - "create /d/f FFFF want ok", - "rm-all /d/f want ok", - "mk-dir /d/m want ok", - "rm-all /z want ok", - "rm-all / want err", - "create /b BB want ok", - " stat / want dir", - " stat /a want 1", - " stat /b want 2", - " stat /c want errNotExist", - " stat /d want dir", - " stat /d/m want dir", - " find / /a /b /d /d/m", - "move__ o=F /b /c want ok", - " stat /b want errNotExist", - " stat /c want 2", - " stat /d/m want dir", - " stat /d/n want errNotExist", - " find / /a /c /d /d/m", - "move__ o=F /d/m /d/n want ok", - "create /d/n/q QQQQ want ok", - " stat /d/m want errNotExist", - " stat /d/n want dir", - " stat /d/n/q want 4", - "move__ o=F /d /d/n/z want err", - "move__ o=T /c /d/n/q want ok", - " stat /c want errNotExist", - " stat /d/n/q want 2", - " find / /a /d /d/n /d/n/q", - "create /d/n/r RRRRR want ok", - "mk-dir /u want ok", - "mk-dir /u/v want ok", - "move__ o=F /d/n /u want errExist", - "create /t TTTTTT want ok", - "move__ o=F /d/n /t want errExist", - "rm-all /t want ok", - "move__ o=F /d/n /t want ok", - " stat /d want dir", - " stat /d/n want errNotExist", - " stat /d/n/r want errNotExist", - " stat /t want dir", - " stat /t/q want 2", - " stat /t/r want 5", - " find / /a /d /t /t/q /t/r /u /u/v", - "move__ o=F /t / want errExist", - "move__ o=T /t /u/v want ok", - " stat /u/v/r want 5", - "move__ o=F / /z want err", - " find / /a /d /u /u/v /u/v/q /u/v/r", - " stat /a want 1", - " stat /b want errNotExist", - " stat /c want errNotExist", - " stat /u/v/r want 5", - "copy__ o=F d=0 /a /b want ok", - "copy__ o=T d=0 /a /c want ok", - " stat /a want 1", - " stat /b want 1", - " stat /c want 1", - " stat /u/v/r want 5", - "copy__ o=F d=0 /u/v/r /b want errExist", - " stat /b want 1", - "copy__ o=T d=0 /u/v/r /b want ok", - " stat /a want 1", - " stat /b want 5", - " stat /u/v/r want 5", - "rm-all /a want ok", - "rm-all /b want ok", - "mk-dir /u/v/w want ok", - "create /u/v/w/s SSSSSSSS want ok", - " stat /d want dir", - " stat /d/x want errNotExist", - " stat /d/y want errNotExist", - " stat /u/v/r want 5", - " stat /u/v/w/s want 8", - " find / /c /d /u /u/v /u/v/q /u/v/r /u/v/w /u/v/w/s", - "copy__ o=T d=0 /u/v /d/x want ok", - "copy__ o=T d=∞ /u/v /d/y want ok", - "rm-all /u want ok", - " stat /d/x want dir", - " stat /d/x/q want errNotExist", - " stat /d/x/r want errNotExist", - " stat /d/x/w want errNotExist", - " stat /d/x/w/s want errNotExist", - " stat /d/y want dir", - " stat /d/y/q want 2", - " stat /d/y/r want 5", - " stat /d/y/w want dir", - " stat /d/y/w/s want 8", - " stat /u want errNotExist", - " find / /c /d /d/x /d/y /d/y/q /d/y/r /d/y/w /d/y/w/s", - "copy__ o=F d=∞ /d/y /d/x want errExist", - } - - ctx := context.Background() - - for i, tc := range testCases { - tc = strings.TrimSpace(tc) - j := strings.IndexByte(tc, ' ') - if j < 0 { - t.Fatalf("test case #%d %q: invalid command", i, tc) - } - op, arg := tc[:j], tc[j+1:] - - switch op { - default: - t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) - - case "create": - parts := strings.Split(arg, " ") - if len(parts) != 4 || parts[2] != "want" { - t.Fatalf("test case #%d %q: invalid write", i, tc) - } - f, opErr := fs.OpenFile(ctx, parts[0], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if got := errStr(opErr); got != parts[3] { - t.Fatalf("test case #%d %q: OpenFile: got %q (%v), want %q", i, tc, got, opErr, parts[3]) - } - if f != nil { - if _, err := f.Write([]byte(parts[1])); err != nil { - t.Fatalf("test case #%d %q: Write: %v", i, tc, err) - } - if err := f.Close(); err != nil { - t.Fatalf("test case #%d %q: Close: %v", i, tc, err) - } - } - - case "find": - got, err := find(ctx, nil, fs, "/") - if err != nil { - t.Fatalf("test case #%d %q: find: %v", i, tc, err) - } - sort.Strings(got) - want := strings.Split(arg, " ") - if !reflect.DeepEqual(got, want) { - t.Fatalf("test case #%d %q:\ngot %s\nwant %s", i, tc, got, want) - } - - case "copy__", "mk-dir", "move__", "rm-all", "stat": - nParts := 3 - switch op { - case "copy__": - nParts = 6 - case "move__": - nParts = 5 - } - parts := strings.Split(arg, " ") - if len(parts) != nParts { - t.Fatalf("test case #%d %q: invalid %s", i, tc, op) - } - - got, opErr := "", error(nil) - switch op { - case "copy__": - depth := 0 - if parts[1] == "d=∞" { - depth = infiniteDepth - } - _, opErr = copyFiles(ctx, fs, parts[2], parts[3], parts[0] == "o=T", depth, 0) - case "mk-dir": - opErr = fs.Mkdir(ctx, parts[0], 0777) - case "move__": - _, opErr = moveFiles(ctx, fs, parts[1], parts[2], parts[0] == "o=T") - case "rm-all": - opErr = fs.RemoveAll(ctx, parts[0]) - case "stat": - var stat os.FileInfo - fileName := parts[0] - if stat, opErr = fs.Stat(ctx, fileName); opErr == nil { - if stat.IsDir() { - got = "dir" - } else { - got = strconv.Itoa(int(stat.Size())) - } - - if fileName == "/" { - // For a AdapterFS FileSystem, the virtual file system root maps to a - // real file system name like "/tmp/webdav-test012345", which does - // not end with "/". We skip such cases. - } else if statName := stat.Name(); path.Base(fileName) != statName { - t.Fatalf("test case #%d %q: file name %q inconsistent with stat name %q", - i, tc, fileName, statName) - } - } - } - if got == "" { - got = errStr(opErr) - } - - if parts[len(parts)-2] != "want" { - t.Fatalf("test case #%d %q: invalid %s", i, tc, op) - } - if want := parts[len(parts)-1]; got != want { - t.Fatalf("test case #%d %q: got %q (%v), want %q", i, tc, got, opErr, want) - } - } - } -} - -func TestDir(t *testing.T) { - switch runtime.GOOS { - case "nacl": - t.Skip("see golang.org/issue/12004") - case "plan9": - t.Skip("see golang.org/issue/11453") - } - - td, err := ioutil.TempDir("", "webdav-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(td) - testFS(t, AdapterFS(td)) -} - -func TestMemFS(t *testing.T) { - testFS(t, NewMemFS()) -} - -func TestMemFSRoot(t *testing.T) { - ctx := context.Background() - fs := NewMemFS() - for i := 0; i < 5; i++ { - stat, err := fs.Stat(ctx, "/") - if err != nil { - t.Fatalf("i=%d: Stat: %v", i, err) - } - if !stat.IsDir() { - t.Fatalf("i=%d: Stat.IsDir is false, want true", i) - } - - f, err := fs.OpenFile(ctx, "/", os.O_RDONLY, 0) - if err != nil { - t.Fatalf("i=%d: OpenFile: %v", i, err) - } - defer f.Close() - children, err := f.Readdir(-1) - if err != nil { - t.Fatalf("i=%d: Readdir: %v", i, err) - } - if len(children) != i { - t.Fatalf("i=%d: got %d children, want %d", i, len(children), i) - } - - if _, err := f.Write(make([]byte, 1)); err == nil { - t.Fatalf("i=%d: Write: got nil error, want non-nil", i) - } - - if err := fs.Mkdir(ctx, fmt.Sprintf("/dir%d", i), 0777); err != nil { - t.Fatalf("i=%d: Mkdir: %v", i, err) - } - } -} - -func TestMemFileReaddir(t *testing.T) { - ctx := context.Background() - fs := NewMemFS() - if err := fs.Mkdir(ctx, "/foo", 0777); err != nil { - t.Fatalf("Mkdir: %v", err) - } - readdir := func(count int) ([]os.FileInfo, error) { - f, err := fs.OpenFile(ctx, "/foo", os.O_RDONLY, 0) - if err != nil { - t.Fatalf("OpenFile: %v", err) - } - defer f.Close() - return f.Readdir(count) - } - if got, err := readdir(-1); len(got) != 0 || err != nil { - t.Fatalf("readdir(-1): got %d fileInfos with err=%v, want 0, ", len(got), err) - } - if got, err := readdir(+1); len(got) != 0 || err != io.EOF { - t.Fatalf("readdir(+1): got %d fileInfos with err=%v, want 0, EOF", len(got), err) - } -} - -func TestMemFile(t *testing.T) { - testCases := []string{ - "wantData ", - "wantSize 0", - "write abc", - "wantData abc", - "write de", - "wantData abcde", - "wantSize 5", - "write 5*x", - "write 4*y+2*z", - "write 3*st", - "wantData abcdexxxxxyyyyzzststst", - "wantSize 22", - "seek set 4 want 4", - "write EFG", - "wantData abcdEFGxxxyyyyzzststst", - "wantSize 22", - "seek set 2 want 2", - "read cdEF", - "read Gx", - "seek cur 0 want 8", - "seek cur 2 want 10", - "seek cur -1 want 9", - "write J", - "wantData abcdEFGxxJyyyyzzststst", - "wantSize 22", - "seek cur -4 want 6", - "write ghijk", - "wantData abcdEFghijkyyyzzststst", - "wantSize 22", - "read yyyz", - "seek cur 0 want 15", - "write ", - "seek cur 0 want 15", - "read ", - "seek cur 0 want 15", - "seek end -3 want 19", - "write ZZ", - "wantData abcdEFghijkyyyzzstsZZt", - "wantSize 22", - "write 4*A", - "wantData abcdEFghijkyyyzzstsZZAAAA", - "wantSize 25", - "seek end 0 want 25", - "seek end -5 want 20", - "read Z+4*A", - "write 5*B", - "wantData abcdEFghijkyyyzzstsZZAAAABBBBB", - "wantSize 30", - "seek end 10 want 40", - "write C", - "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........C", - "wantSize 41", - "write D", - "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD", - "wantSize 42", - "seek set 43 want 43", - "write E", - "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD.E", - "wantSize 44", - "seek set 0 want 0", - "write 5*123456789_", - "wantData 123456789_123456789_123456789_123456789_123456789_", - "wantSize 50", - "seek cur 0 want 50", - "seek cur -99 want err", - } - - ctx := context.Background() - - const filename = "/foo" - fs := NewMemFS() - f, err := fs.OpenFile(ctx, filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - t.Fatalf("OpenFile: %v", err) - } - defer f.Close() - - for i, tc := range testCases { - j := strings.IndexByte(tc, ' ') - if j < 0 { - t.Fatalf("test case #%d %q: invalid command", i, tc) - } - op, arg := tc[:j], tc[j+1:] - - // Expand an arg like "3*a+2*b" to "aaabb". - parts := strings.Split(arg, "+") - for j, part := range parts { - if k := strings.IndexByte(part, '*'); k >= 0 { - repeatCount, repeatStr := part[:k], part[k+1:] - n, err := strconv.Atoi(repeatCount) - if err != nil { - t.Fatalf("test case #%d %q: invalid repeat count %q", i, tc, repeatCount) - } - parts[j] = strings.Repeat(repeatStr, n) - } - } - arg = strings.Join(parts, "") - - switch op { - default: - t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) - - case "read": - buf := make([]byte, len(arg)) - if _, err := io.ReadFull(f, buf); err != nil { - t.Fatalf("test case #%d %q: ReadFull: %v", i, tc, err) - } - if got := string(buf); got != arg { - t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) - } - - case "seek": - parts := strings.Split(arg, " ") - if len(parts) != 4 { - t.Fatalf("test case #%d %q: invalid seek", i, tc) - } - - whence := 0 - switch parts[0] { - default: - t.Fatalf("test case #%d %q: invalid seek whence", i, tc) - case "set": - whence = os.SEEK_SET - case "cur": - whence = os.SEEK_CUR - case "end": - whence = os.SEEK_END - } - offset, err := strconv.Atoi(parts[1]) - if err != nil { - t.Fatalf("test case #%d %q: invalid offset %q", i, tc, parts[1]) - } - - if parts[2] != "want" { - t.Fatalf("test case #%d %q: invalid seek", i, tc) - } - if parts[3] == "err" { - _, err := f.Seek(int64(offset), whence) - if err == nil { - t.Fatalf("test case #%d %q: Seek returned nil error, want non-nil", i, tc) - } - } else { - got, err := f.Seek(int64(offset), whence) - if err != nil { - t.Fatalf("test case #%d %q: Seek: %v", i, tc, err) - } - want, err := strconv.Atoi(parts[3]) - if err != nil { - t.Fatalf("test case #%d %q: invalid want %q", i, tc, parts[3]) - } - if got != int64(want) { - t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) - } - } - - case "write": - n, err := f.Write([]byte(arg)) - if err != nil { - t.Fatalf("test case #%d %q: write: %v", i, tc, err) - } - if n != len(arg) { - t.Fatalf("test case #%d %q: write returned %d bytes, want %d", i, tc, n, len(arg)) - } - - case "wantData": - g, err := fs.OpenFile(ctx, filename, os.O_RDONLY, 0666) - if err != nil { - t.Fatalf("test case #%d %q: OpenFile: %v", i, tc, err) - } - gotBytes, err := ioutil.ReadAll(g) - if err != nil { - t.Fatalf("test case #%d %q: ReadAll: %v", i, tc, err) - } - for i, c := range gotBytes { - if c == '\x00' { - gotBytes[i] = '.' - } - } - got := string(gotBytes) - if got != arg { - t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) - } - if err := g.Close(); err != nil { - t.Fatalf("test case #%d %q: Close: %v", i, tc, err) - } - - case "wantSize": - n, err := strconv.Atoi(arg) - if err != nil { - t.Fatalf("test case #%d %q: invalid size %q", i, tc, arg) - } - fi, err := fs.Stat(ctx, filename) - if err != nil { - t.Fatalf("test case #%d %q: Stat: %v", i, tc, err) - } - if got, want := fi.Size(), int64(n); got != want { - t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) - } - } - } -} - -// TestMemFileWriteAllocs tests that writing N consecutive 1KiB chunks to a -// memFile doesn't allocate a new buffer for each of those N times. Otherwise, -// calling io.Copy(aMemFile, src) is likely to have quadratic complexity. -func TestMemFileWriteAllocs(t *testing.T) { - if runtime.Compiler == "gccgo" { - t.Skip("gccgo allocates here") - } - ctx := context.Background() - fs := NewMemFS() - f, err := fs.OpenFile(ctx, "/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - t.Fatalf("OpenFile: %v", err) - } - defer f.Close() - - xxx := make([]byte, 1024) - for i := range xxx { - xxx[i] = 'x' - } - - a := testing.AllocsPerRun(100, func() { - f.Write(xxx) - }) - // AllocsPerRun returns an integral value, so we compare the rounded-down - // number to zero. - if a > 0 { - t.Fatalf("%v allocs per run, want 0", a) - } -} - -func BenchmarkMemFileWrite(b *testing.B) { - ctx := context.Background() - fs := NewMemFS() - xxx := make([]byte, 1024) - for i := range xxx { - xxx[i] = 'x' - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - f, err := fs.OpenFile(ctx, "/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - b.Fatalf("OpenFile: %v", err) - } - for j := 0; j < 100; j++ { - f.Write(xxx) - } - if err := f.Close(); err != nil { - b.Fatalf("Close: %v", err) - } - if err := fs.RemoveAll(ctx, "/xxx"); err != nil { - b.Fatalf("RemoveAll: %v", err) - } - } -} - -func TestCopyMoveProps(t *testing.T) { - ctx := context.Background() - fs := NewMemFS() - create := func(name string) error { - f, err := fs.OpenFile(ctx, name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - return err - } - _, wErr := f.Write([]byte("contents")) - cErr := f.Close() - if wErr != nil { - return wErr - } - return cErr - } - patch := func(name string, patches ...Proppatch) error { - f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0666) - if err != nil { - return err - } - _, pErr := f.(DeadPropsHolder).Patch(patches) - cErr := f.Close() - if pErr != nil { - return pErr - } - return cErr - } - props := func(name string) (map[xml.Name]Property, error) { - f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0666) - if err != nil { - return nil, err - } - m, pErr := f.(DeadPropsHolder).DeadProps() - cErr := f.Close() - if pErr != nil { - return nil, pErr - } - if cErr != nil { - return nil, cErr - } - return m, nil - } - - p0 := Property{ - XMLName: xml.Name{Space: "x:", Local: "boat"}, - InnerXML: []byte("pea-green"), - } - p1 := Property{ - XMLName: xml.Name{Space: "x:", Local: "ring"}, - InnerXML: []byte("1 shilling"), - } - p2 := Property{ - XMLName: xml.Name{Space: "x:", Local: "spoon"}, - InnerXML: []byte("runcible"), - } - p3 := Property{ - XMLName: xml.Name{Space: "x:", Local: "moon"}, - InnerXML: []byte("light"), - } - - if err := create("/src"); err != nil { - t.Fatalf("create /src: %v", err) - } - if err := patch("/src", Proppatch{Props: []Property{p0, p1}}); err != nil { - t.Fatalf("patch /src +p0 +p1: %v", err) - } - if _, err := copyFiles(ctx, fs, "/src", "/tmp", true, infiniteDepth, 0); err != nil { - t.Fatalf("copyFiles /src /tmp: %v", err) - } - if _, err := moveFiles(ctx, fs, "/tmp", "/dst", true); err != nil { - t.Fatalf("moveFiles /tmp /dst: %v", err) - } - if err := patch("/src", Proppatch{Props: []Property{p0}, Remove: true}); err != nil { - t.Fatalf("patch /src -p0: %v", err) - } - if err := patch("/src", Proppatch{Props: []Property{p2}}); err != nil { - t.Fatalf("patch /src +p2: %v", err) - } - if err := patch("/dst", Proppatch{Props: []Property{p1}, Remove: true}); err != nil { - t.Fatalf("patch /dst -p1: %v", err) - } - if err := patch("/dst", Proppatch{Props: []Property{p3}}); err != nil { - t.Fatalf("patch /dst +p3: %v", err) - } - - gotSrc, err := props("/src") - if err != nil { - t.Fatalf("props /src: %v", err) - } - wantSrc := map[xml.Name]Property{ - p1.XMLName: p1, - p2.XMLName: p2, - } - if !reflect.DeepEqual(gotSrc, wantSrc) { - t.Fatalf("props /src:\ngot %v\nwant %v", gotSrc, wantSrc) - } - - gotDst, err := props("/dst") - if err != nil { - t.Fatalf("props /dst: %v", err) - } - wantDst := map[xml.Name]Property{ - p0.XMLName: p0, - p3.XMLName: p3, - } - if !reflect.DeepEqual(gotDst, wantDst) { - t.Fatalf("props /dst:\ngot %v\nwant %v", gotDst, wantDst) - } -} - -func TestWalkFS(t *testing.T) { - testCases := []struct { - desc string - buildfs []string - startAt string - depth int - walkFn filepath.WalkFunc - want []string - }{{ - "just root", - []string{}, - "/", - infiniteDepth, - nil, - []string{ - "/", - }, - }, { - "infinite walk from root", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/d", - "mkdir /e", - "touch /f", - }, - "/", - infiniteDepth, - nil, - []string{ - "/", - "/a", - "/a/b", - "/a/b/c", - "/a/d", - "/e", - "/f", - }, - }, { - "infinite walk from subdir", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/d", - "mkdir /e", - "touch /f", - }, - "/a", - infiniteDepth, - nil, - []string{ - "/a", - "/a/b", - "/a/b/c", - "/a/d", - }, - }, { - "depth 1 walk from root", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/d", - "mkdir /e", - "touch /f", - }, - "/", - 1, - nil, - []string{ - "/", - "/a", - "/e", - "/f", - }, - }, { - "depth 1 walk from subdir", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/b/g", - "mkdir /a/b/g/h", - "touch /a/b/g/i", - "touch /a/b/g/h/j", - }, - "/a/b", - 1, - nil, - []string{ - "/a/b", - "/a/b/c", - "/a/b/g", - }, - }, { - "depth 0 walk from subdir", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/b/g", - "mkdir /a/b/g/h", - "touch /a/b/g/i", - "touch /a/b/g/h/j", - }, - "/a/b", - 0, - nil, - []string{ - "/a/b", - }, - }, { - "infinite walk from file", - []string{ - "mkdir /a", - "touch /a/b", - "touch /a/c", - }, - "/a/b", - 0, - nil, - []string{ - "/a/b", - }, - }, { - "infinite walk with skipped subdir", - []string{ - "mkdir /a", - "mkdir /a/b", - "touch /a/b/c", - "mkdir /a/b/g", - "mkdir /a/b/g/h", - "touch /a/b/g/i", - "touch /a/b/g/h/j", - "touch /a/b/z", - }, - "/", - infiniteDepth, - func(path string, info os.FileInfo, err error) error { - if path == "/a/b/g" { - return filepath.SkipDir - } - return nil - }, - []string{ - "/", - "/a", - "/a/b", - "/a/b/c", - "/a/b/z", - }, - }} - ctx := context.Background() - for _, tc := range testCases { - fs, err := buildTestFS(tc.buildfs) - if err != nil { - t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) - } - var got []string - traceFn := func(path string, info os.FileInfo, err error) error { - if tc.walkFn != nil { - err = tc.walkFn(path, info, err) - if err != nil { - return err - } - } - got = append(got, path) - return nil - } - fi, err := fs.Stat(ctx, tc.startAt) - if err != nil { - t.Fatalf("%s: cannot stat: %v", tc.desc, err) - } - err = walkFS(ctx, fs, tc.depth, tc.startAt, fi, traceFn) - if err != nil { - t.Errorf("%s:\ngot error %v, want nil", tc.desc, err) - continue - } - sort.Strings(got) - sort.Strings(tc.want) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("%s:\ngot %q\nwant %q", tc.desc, got, tc.want) - continue - } - } -} - -func buildTestFS(buildfs []string) (FileSystem, error) { - // TODO: Could this be merged with the build logic in TestFS? - - ctx := context.Background() - fs := NewMemFS() - for _, b := range buildfs { - op := strings.Split(b, " ") - switch op[0] { - case "mkdir": - err := fs.Mkdir(ctx, op[1], os.ModeDir|0777) - if err != nil { - return nil, err - } - case "touch": - f, err := fs.OpenFile(ctx, op[1], os.O_RDWR|os.O_CREATE, 0666) - if err != nil { - return nil, err - } - f.Close() - case "write": - f, err := fs.OpenFile(ctx, op[1], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) - if err != nil { - return nil, err - } - _, err = f.Write([]byte(op[2])) - f.Close() - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("unknown file operation %q", op[0]) - } - } - return fs, nil -} diff --git a/pkg/webdav/if_test.go b/pkg/webdav/if_test.go deleted file mode 100644 index aad61a4..0000000 --- a/pkg/webdav/if_test.go +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package webdav - -import ( - "reflect" - "strings" - "testing" -) - -func TestParseIfHeader(t *testing.T) { - // The "section x.y.z" test cases come from section x.y.z of the spec at - // http://www.webdav.org/specs/rfc4918.html - testCases := []struct { - desc string - input string - want ifHeader - }{{ - "bad: empty", - ``, - ifHeader{}, - }, { - "bad: no parens", - `foobar`, - ifHeader{}, - }, { - "bad: empty list #1", - `()`, - ifHeader{}, - }, { - "bad: empty list #2", - `(a) (b c) () (d)`, - ifHeader{}, - }, { - "bad: no list after resource #1", - ``, - ifHeader{}, - }, { - "bad: no list after resource #2", - ` (a)`, - ifHeader{}, - }, { - "bad: no list after resource #3", - ` (a) (b) `, - ifHeader{}, - }, { - "bad: no-tag-list followed by tagged-list", - `(a) (b) (c)`, - ifHeader{}, - }, { - "bad: unfinished list", - `(a`, - ifHeader{}, - }, { - "bad: unfinished ETag", - `([b`, - ifHeader{}, - }, { - "bad: unfinished Notted list", - `(Not a`, - ifHeader{}, - }, { - "bad: double Not", - `(Not Not a)`, - ifHeader{}, - }, { - "good: one list with a Token", - `(a)`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `a`, - }}, - }}, - }, - }, { - "good: one list with an ETag", - `([a])`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - ETag: `a`, - }}, - }}, - }, - }, { - "good: one list with three Nots", - `(Not a Not b Not [d])`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Not: true, - Token: `a`, - }, { - Not: true, - Token: `b`, - }, { - Not: true, - ETag: `d`, - }}, - }}, - }, - }, { - "good: two lists", - `(a) (b)`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `a`, - }}, - }, { - conditions: []Condition{{ - Token: `b`, - }}, - }}, - }, - }, { - "good: two Notted lists", - `(Not a) (Not b)`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Not: true, - Token: `a`, - }}, - }, { - conditions: []Condition{{ - Not: true, - Token: `b`, - }}, - }}, - }, - }, { - "section 7.5.1", - ` - ()`, - ifHeader{ - lists: []ifList{{ - resourceTag: `http://www.example.com/users/f/fielding/index.html`, - conditions: []Condition{{ - Token: `urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6`, - }}, - }}, - }, - }, { - "section 7.5.2 #1", - `()`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, - }}, - }}, - }, - }, { - "section 7.5.2 #2", - ` - ()`, - ifHeader{ - lists: []ifList{{ - resourceTag: `http://example.com/locked/`, - conditions: []Condition{{ - Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, - }}, - }}, - }, - }, { - "section 7.5.2 #3", - ` - ()`, - ifHeader{ - lists: []ifList{{ - resourceTag: `http://example.com/locked/member`, - conditions: []Condition{{ - Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, - }}, - }}, - }, - }, { - "section 9.9.6", - `() - ()`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `urn:uuid:fe184f2e-6eec-41d0-c765-01adc56e6bb4`, - }}, - }, { - conditions: []Condition{{ - Token: `urn:uuid:e454f3f3-acdc-452a-56c7-00a5c91e4b77`, - }}, - }}, - }, - }, { - "section 9.10.8", - `()`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4`, - }}, - }}, - }, - }, { - "section 10.4.6", - `( - ["I am an ETag"]) - (["I am another ETag"])`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, - }, { - ETag: `"I am an ETag"`, - }}, - }, { - conditions: []Condition{{ - ETag: `"I am another ETag"`, - }}, - }}, - }, - }, { - "section 10.4.7", - `(Not - )`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Not: true, - Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, - }, { - Token: `urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092`, - }}, - }}, - }, - }, { - "section 10.4.8", - `() - (Not )`, - ifHeader{ - lists: []ifList{{ - conditions: []Condition{{ - Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, - }}, - }, { - conditions: []Condition{{ - Not: true, - Token: `DAV:no-lock`, - }}, - }}, - }, - }, { - "section 10.4.9", - ` - ( - [W/"A weak ETag"]) (["strong ETag"])`, - ifHeader{ - lists: []ifList{{ - resourceTag: `/resource1`, - conditions: []Condition{{ - Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, - }, { - ETag: `W/"A weak ETag"`, - }}, - }, { - resourceTag: `/resource1`, - conditions: []Condition{{ - ETag: `"strong ETag"`, - }}, - }}, - }, - }, { - "section 10.4.10", - ` - ()`, - ifHeader{ - lists: []ifList{{ - resourceTag: `http://www.example.com/specs/`, - conditions: []Condition{{ - Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, - }}, - }}, - }, - }, { - "section 10.4.11 #1", - ` (["4217"])`, - ifHeader{ - lists: []ifList{{ - resourceTag: `/specs/rfc2518.doc`, - conditions: []Condition{{ - ETag: `"4217"`, - }}, - }}, - }, - }, { - "section 10.4.11 #2", - ` (Not ["4217"])`, - ifHeader{ - lists: []ifList{{ - resourceTag: `/specs/rfc2518.doc`, - conditions: []Condition{{ - Not: true, - ETag: `"4217"`, - }}, - }}, - }, - }} - - for _, tc := range testCases { - got, ok := parseIfHeader(strings.Replace(tc.input, "\n", "", -1)) - if gotEmpty := reflect.DeepEqual(got, ifHeader{}); gotEmpty == ok { - t.Errorf("%s: should be different: empty header == %t, ok == %t", tc.desc, gotEmpty, ok) - continue - } - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("%s:\ngot %v\nwant %v", tc.desc, got, tc.want) - continue - } - } -} diff --git a/pkg/webdav/lock_test.go b/pkg/webdav/lock_test.go deleted file mode 100644 index 561ada4..0000000 --- a/pkg/webdav/lock_test.go +++ /dev/null @@ -1,735 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package webdav - -import ( - "fmt" - "math/rand" - "path" - "reflect" - "sort" - "strconv" - "strings" - "testing" - "time" -) - -func TestWalkToRoot(t *testing.T) { - testCases := []struct { - name string - want []string - }{{ - "/a/b/c/d", - []string{ - "/a/b/c/d", - "/a/b/c", - "/a/b", - "/a", - "/", - }, - }, { - "/a", - []string{ - "/a", - "/", - }, - }, { - "/", - []string{ - "/", - }, - }} - - for _, tc := range testCases { - var got []string - if !walkToRoot(tc.name, func(name0 string, first bool) bool { - if first != (len(got) == 0) { - t.Errorf("name=%q: first=%t but len(got)==%d", tc.name, first, len(got)) - return false - } - got = append(got, name0) - return true - }) { - continue - } - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("name=%q:\ngot %q\nwant %q", tc.name, got, tc.want) - } - } -} - -var lockTestDurations = []time.Duration{ - infiniteTimeout, // infiniteTimeout means to never expire. - 0, // A zero duration means to expire immediately. - 100 * time.Hour, // A very large duration will not expire in these tests. -} - -// lockTestNames are the names of a set of mutually compatible locks. For each -// name fragment: -// - _ means no explicit lock. -// - i means an infinite-depth lock, -// - z means a zero-depth lock, -var lockTestNames = []string{ - "/_/_/_/_/z", - "/_/_/i", - "/_/z", - "/_/z/i", - "/_/z/z", - "/_/z/_/i", - "/_/z/_/z", - "/i", - "/z", - "/z/_/i", - "/z/_/z", -} - -func lockTestZeroDepth(name string) bool { - switch name[len(name)-1] { - case 'i': - return false - case 'z': - return true - } - panic(fmt.Sprintf("lock name %q did not end with 'i' or 'z'", name)) -} - -func TestMemLSCanCreate(t *testing.T) { - now := time.Unix(0, 0) - m := NewMemLS().(*memLS) - - for _, name := range lockTestNames { - _, err := m.Create(now, LockDetails{ - Root: name, - Duration: infiniteTimeout, - ZeroDepth: lockTestZeroDepth(name), - }) - if err != nil { - t.Fatalf("creating lock for %q: %v", name, err) - } - } - - wantCanCreate := func(name string, zeroDepth bool) bool { - for _, n := range lockTestNames { - switch { - case n == name: - // An existing lock has the same name as the proposed lock. - return false - case strings.HasPrefix(n, name): - // An existing lock would be a child of the proposed lock, - // which conflicts if the proposed lock has infinite depth. - if !zeroDepth { - return false - } - case strings.HasPrefix(name, n): - // An existing lock would be an ancestor of the proposed lock, - // which conflicts if the ancestor has infinite depth. - if n[len(n)-1] == 'i' { - return false - } - } - } - return true - } - - var check func(int, string) - check = func(recursion int, name string) { - for _, zeroDepth := range []bool{false, true} { - got := m.canCreate(name, zeroDepth) - want := wantCanCreate(name, zeroDepth) - if got != want { - t.Errorf("canCreate name=%q zeroDepth=%t: got %t, want %t", name, zeroDepth, got, want) - } - } - if recursion == 6 { - return - } - if name != "/" { - name += "/" - } - for _, c := range "_iz" { - check(recursion+1, name+string(c)) - } - } - check(0, "/") -} - -func TestMemLSLookup(t *testing.T) { - now := time.Unix(0, 0) - m := NewMemLS().(*memLS) - - badToken := m.nextToken() - t.Logf("badToken=%q", badToken) - - for _, name := range lockTestNames { - token, err := m.Create(now, LockDetails{ - Root: name, - Duration: infiniteTimeout, - ZeroDepth: lockTestZeroDepth(name), - }) - if err != nil { - t.Fatalf("creating lock for %q: %v", name, err) - } - t.Logf("%-15q -> node=%p token=%q", name, m.byName[name], token) - } - - baseNames := append([]string{"/a", "/b/c"}, lockTestNames...) - for _, baseName := range baseNames { - for _, suffix := range []string{"", "/0", "/1/2/3"} { - name := baseName + suffix - - goodToken := "" - base := m.byName[baseName] - if base != nil && (suffix == "" || !lockTestZeroDepth(baseName)) { - goodToken = base.token - } - - for _, token := range []string{badToken, goodToken} { - if token == "" { - continue - } - - got := m.lookup(name, Condition{Token: token}) - want := base - if token == badToken { - want = nil - } - if got != want { - t.Errorf("name=%-20qtoken=%q (bad=%t): got %p, want %p", - name, token, token == badToken, got, want) - } - } - } - } -} - -func TestMemLSConfirm(t *testing.T) { - now := time.Unix(0, 0) - m := NewMemLS().(*memLS) - alice, err := m.Create(now, LockDetails{ - Root: "/alice", - Duration: infiniteTimeout, - ZeroDepth: false, - }) - if err != nil { - t.Fatalf("Create: %v", err) - } - - tweedle, err := m.Create(now, LockDetails{ - Root: "/tweedle", - Duration: infiniteTimeout, - ZeroDepth: false, - }) - if err != nil { - t.Fatalf("Create: %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Create: inconsistent state: %v", err) - } - - // Test a mismatch between name and condition. - _, err = m.Confirm(now, "/tweedle/dee", "", Condition{Token: alice}) - if err != ErrConfirmationFailed { - t.Fatalf("Confirm (mismatch): got %v, want ErrConfirmationFailed", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Confirm (mismatch): inconsistent state: %v", err) - } - - // Test two names (that fall under the same lock) in the one Confirm call. - release, err := m.Confirm(now, "/tweedle/dee", "/tweedle/dum", Condition{Token: tweedle}) - if err != nil { - t.Fatalf("Confirm (twins): %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Confirm (twins): inconsistent state: %v", err) - } - release() - if err := m.consistent(); err != nil { - t.Fatalf("release (twins): inconsistent state: %v", err) - } - - // Test the same two names in overlapping Confirm / release calls. - releaseDee, err := m.Confirm(now, "/tweedle/dee", "", Condition{Token: tweedle}) - if err != nil { - t.Fatalf("Confirm (sequence #0): %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Confirm (sequence #0): inconsistent state: %v", err) - } - - _, err = m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) - if err != ErrConfirmationFailed { - t.Fatalf("Confirm (sequence #1): got %v, want ErrConfirmationFailed", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Confirm (sequence #1): inconsistent state: %v", err) - } - - releaseDee() - if err := m.consistent(); err != nil { - t.Fatalf("release (sequence #2): inconsistent state: %v", err) - } - - releaseDum, err := m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) - if err != nil { - t.Fatalf("Confirm (sequence #3): %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Confirm (sequence #3): inconsistent state: %v", err) - } - - // Test that you can't unlock a held lock. - err = m.Unlock(now, tweedle) - if err != ErrLocked { - t.Fatalf("Unlock (sequence #4): got %v, want ErrLocked", err) - } - - releaseDum() - if err := m.consistent(); err != nil { - t.Fatalf("release (sequence #5): inconsistent state: %v", err) - } - - err = m.Unlock(now, tweedle) - if err != nil { - t.Fatalf("Unlock (sequence #6): %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Unlock (sequence #6): inconsistent state: %v", err) - } -} - -func TestMemLSNonCanonicalRoot(t *testing.T) { - now := time.Unix(0, 0) - m := NewMemLS().(*memLS) - token, err := m.Create(now, LockDetails{ - Root: "/foo/./bar//", - Duration: 1 * time.Second, - }) - if err != nil { - t.Fatalf("Create: %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Create: inconsistent state: %v", err) - } - if err := m.Unlock(now, token); err != nil { - t.Fatalf("Unlock: %v", err) - } - if err := m.consistent(); err != nil { - t.Fatalf("Unlock: inconsistent state: %v", err) - } -} - -func TestMemLSExpiry(t *testing.T) { - m := NewMemLS().(*memLS) - testCases := []string{ - "setNow 0", - "create /a.5", - "want /a.5", - "create /c.6", - "want /a.5 /c.6", - "create /a/b.7", - "want /a.5 /a/b.7 /c.6", - "setNow 4", - "want /a.5 /a/b.7 /c.6", - "setNow 5", - "want /a/b.7 /c.6", - "setNow 6", - "want /a/b.7", - "setNow 7", - "want ", - "setNow 8", - "want ", - "create /a.12", - "create /b.13", - "create /c.15", - "create /a/d.16", - "want /a.12 /a/d.16 /b.13 /c.15", - "refresh /a.14", - "want /a.14 /a/d.16 /b.13 /c.15", - "setNow 12", - "want /a.14 /a/d.16 /b.13 /c.15", - "setNow 13", - "want /a.14 /a/d.16 /c.15", - "setNow 14", - "want /a/d.16 /c.15", - "refresh /a/d.20", - "refresh /c.20", - "want /a/d.20 /c.20", - "setNow 20", - "want ", - } - - tokens := map[string]string{} - zTime := time.Unix(0, 0) - now := zTime - for i, tc := range testCases { - j := strings.IndexByte(tc, ' ') - if j < 0 { - t.Fatalf("test case #%d %q: invalid command", i, tc) - } - op, arg := tc[:j], tc[j+1:] - switch op { - default: - t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) - - case "create", "refresh": - parts := strings.Split(arg, ".") - if len(parts) != 2 { - t.Fatalf("test case #%d %q: invalid create", i, tc) - } - root := parts[0] - d, err := strconv.Atoi(parts[1]) - if err != nil { - t.Fatalf("test case #%d %q: invalid duration", i, tc) - } - dur := time.Unix(0, 0).Add(time.Duration(d) * time.Second).Sub(now) - - switch op { - case "create": - token, err := m.Create(now, LockDetails{ - Root: root, - Duration: dur, - ZeroDepth: true, - }) - if err != nil { - t.Fatalf("test case #%d %q: Create: %v", i, tc, err) - } - tokens[root] = token - - case "refresh": - token := tokens[root] - if token == "" { - t.Fatalf("test case #%d %q: no token for %q", i, tc, root) - } - got, err := m.Refresh(now, token, dur) - if err != nil { - t.Fatalf("test case #%d %q: Refresh: %v", i, tc, err) - } - want := LockDetails{ - Root: root, - Duration: dur, - ZeroDepth: true, - } - if got != want { - t.Fatalf("test case #%d %q:\ngot %v\nwant %v", i, tc, got, want) - } - } - - case "setNow": - d, err := strconv.Atoi(arg) - if err != nil { - t.Fatalf("test case #%d %q: invalid duration", i, tc) - } - now = time.Unix(0, 0).Add(time.Duration(d) * time.Second) - - case "want": - m.mu.Lock() - m.collectExpiredNodes(now) - got := make([]string, 0, len(m.byToken)) - for _, n := range m.byToken { - got = append(got, fmt.Sprintf("%s.%d", - n.details.Root, n.expiry.Sub(zTime)/time.Second)) - } - m.mu.Unlock() - sort.Strings(got) - want := []string{} - if arg != "" { - want = strings.Split(arg, " ") - } - if !reflect.DeepEqual(got, want) { - t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, want) - } - } - - if err := m.consistent(); err != nil { - t.Fatalf("test case #%d %q: inconsistent state: %v", i, tc, err) - } - } -} - -func TestMemLS(t *testing.T) { - now := time.Unix(0, 0) - m := NewMemLS().(*memLS) - rng := rand.New(rand.NewSource(0)) - tokens := map[string]string{} - nConfirm, nCreate, nRefresh, nUnlock := 0, 0, 0, 0 - const N = 2000 - - for i := 0; i < N; i++ { - name := lockTestNames[rng.Intn(len(lockTestNames))] - duration := lockTestDurations[rng.Intn(len(lockTestDurations))] - confirmed, unlocked := false, false - - // If the name was already locked, we randomly confirm/release, refresh - // or unlock it. Otherwise, we create a lock. - token := tokens[name] - if token != "" { - switch rng.Intn(3) { - case 0: - confirmed = true - nConfirm++ - release, err := m.Confirm(now, name, "", Condition{Token: token}) - if err != nil { - t.Fatalf("iteration #%d: Confirm %q: %v", i, name, err) - } - if err := m.consistent(); err != nil { - t.Fatalf("iteration #%d: inconsistent state: %v", i, err) - } - release() - - case 1: - nRefresh++ - if _, err := m.Refresh(now, token, duration); err != nil { - t.Fatalf("iteration #%d: Refresh %q: %v", i, name, err) - } - - case 2: - unlocked = true - nUnlock++ - if err := m.Unlock(now, token); err != nil { - t.Fatalf("iteration #%d: Unlock %q: %v", i, name, err) - } - } - - } else { - nCreate++ - var err error - token, err = m.Create(now, LockDetails{ - Root: name, - Duration: duration, - ZeroDepth: lockTestZeroDepth(name), - }) - if err != nil { - t.Fatalf("iteration #%d: Create %q: %v", i, name, err) - } - } - - if !confirmed { - if duration == 0 || unlocked { - // A zero-duration lock should expire immediately and is - // effectively equivalent to being unlocked. - tokens[name] = "" - } else { - tokens[name] = token - } - } - - if err := m.consistent(); err != nil { - t.Fatalf("iteration #%d: inconsistent state: %v", i, err) - } - } - - if nConfirm < N/10 { - t.Fatalf("too few Confirm calls: got %d, want >= %d", nConfirm, N/10) - } - if nCreate < N/10 { - t.Fatalf("too few Create calls: got %d, want >= %d", nCreate, N/10) - } - if nRefresh < N/10 { - t.Fatalf("too few Refresh calls: got %d, want >= %d", nRefresh, N/10) - } - if nUnlock < N/10 { - t.Fatalf("too few Unlock calls: got %d, want >= %d", nUnlock, N/10) - } -} - -func (m *memLS) consistent() error { - m.mu.Lock() - defer m.mu.Unlock() - - // If m.byName is non-empty, then it must contain an entry for the root "/", - // and its refCount should equal the number of locked nodes. - if len(m.byName) > 0 { - n := m.byName["/"] - if n == nil { - return fmt.Errorf(`non-empty m.byName does not contain the root "/"`) - } - if n.refCount != len(m.byToken) { - return fmt.Errorf("root node refCount=%d, differs from len(m.byToken)=%d", n.refCount, len(m.byToken)) - } - } - - for name, n := range m.byName { - // The map keys should be consistent with the node's copy of the key. - if n.details.Root != name { - return fmt.Errorf("node name %q != byName map key %q", n.details.Root, name) - } - - // A name must be clean, and start with a "/". - if len(name) == 0 || name[0] != '/' { - return fmt.Errorf(`node name %q does not start with "/"`, name) - } - if name != path.Clean(name) { - return fmt.Errorf(`node name %q is not clean`, name) - } - - // A node's refCount should be positive. - if n.refCount <= 0 { - return fmt.Errorf("non-positive refCount for node at name %q", name) - } - - // A node's refCount should be the number of self-or-descendents that - // are locked (i.e. have a non-empty token). - var list []string - for name0, n0 := range m.byName { - // All of lockTestNames' name fragments are one byte long: '_', 'i' or 'z', - // so strings.HasPrefix is equivalent to self-or-descendent name match. - // We don't have to worry about "/foo/bar" being a false positive match - // for "/foo/b". - if strings.HasPrefix(name0, name) && n0.token != "" { - list = append(list, name0) - } - } - if n.refCount != len(list) { - sort.Strings(list) - return fmt.Errorf("node at name %q has refCount %d but locked self-or-descendents are %q (len=%d)", - name, n.refCount, list, len(list)) - } - - // A node n is in m.byToken if it has a non-empty token. - if n.token != "" { - if _, ok := m.byToken[n.token]; !ok { - return fmt.Errorf("node at name %q has token %q but not in m.byToken", name, n.token) - } - } - - // A node n is in m.byExpiry if it has a non-negative byExpiryIndex. - if n.byExpiryIndex >= 0 { - if n.byExpiryIndex >= len(m.byExpiry) { - return fmt.Errorf("node at name %q has byExpiryIndex %d but m.byExpiry has length %d", name, n.byExpiryIndex, len(m.byExpiry)) - } - if n != m.byExpiry[n.byExpiryIndex] { - return fmt.Errorf("node at name %q has byExpiryIndex %d but that indexes a different node", name, n.byExpiryIndex) - } - } - } - - for token, n := range m.byToken { - // The map keys should be consistent with the node's copy of the key. - if n.token != token { - return fmt.Errorf("node token %q != byToken map key %q", n.token, token) - } - - // Every node in m.byToken is in m.byName. - if _, ok := m.byName[n.details.Root]; !ok { - return fmt.Errorf("node at name %q in m.byToken but not in m.byName", n.details.Root) - } - } - - for i, n := range m.byExpiry { - // The slice indices should be consistent with the node's copy of the index. - if n.byExpiryIndex != i { - return fmt.Errorf("node byExpiryIndex %d != byExpiry slice index %d", n.byExpiryIndex, i) - } - - // Every node in m.byExpiry is in m.byName. - if _, ok := m.byName[n.details.Root]; !ok { - return fmt.Errorf("node at name %q in m.byExpiry but not in m.byName", n.details.Root) - } - - // No node in m.byExpiry should be held. - if n.held { - return fmt.Errorf("node at name %q in m.byExpiry is held", n.details.Root) - } - } - return nil -} - -func TestParseTimeout(t *testing.T) { - testCases := []struct { - s string - want time.Duration - wantErr error - }{{ - "", - infiniteTimeout, - nil, - }, { - "Infinite", - infiniteTimeout, - nil, - }, { - "Infinitesimal", - 0, - errInvalidTimeout, - }, { - "infinite", - 0, - errInvalidTimeout, - }, { - "Second-0", - 0 * time.Second, - nil, - }, { - "Second-123", - 123 * time.Second, - nil, - }, { - " Second-456 ", - 456 * time.Second, - nil, - }, { - "Second-4100000000", - 4100000000 * time.Second, - nil, - }, { - "junk", - 0, - errInvalidTimeout, - }, { - "Second-", - 0, - errInvalidTimeout, - }, { - "Second--1", - 0, - errInvalidTimeout, - }, { - "Second--123", - 0, - errInvalidTimeout, - }, { - "Second-+123", - 0, - errInvalidTimeout, - }, { - "Second-0x123", - 0, - errInvalidTimeout, - }, { - "second-123", - 0, - errInvalidTimeout, - }, { - "Second-4294967295", - 4294967295 * time.Second, - nil, - }, { - // Section 10.7 says that "The timeout value for TimeType "Second" - // must not be greater than 2^32-1." - "Second-4294967296", - 0, - errInvalidTimeout, - }, { - // This test case comes from section 9.10.9 of the spec. It says, - // - // "In this request, the client has specified that it desires an - // infinite-length lock, if available, otherwise a timeout of 4.1 - // billion seconds, if available." - // - // The Go WebDAV package always supports infinite length locks, - // and ignores the fallback after the comma. - "Infinite, Second-4100000000", - infiniteTimeout, - nil, - }} - - for _, tc := range testCases { - got, gotErr := parseTimeout(tc.s) - if got != tc.want || gotErr != tc.wantErr { - t.Errorf("parsing %q:\ngot %v, %v\nwant %v, %v", tc.s, got, gotErr, tc.want, tc.wantErr) - } - } -} diff --git a/pkg/webdav/mem.go b/pkg/webdav/mem.go deleted file mode 100644 index 98eba73..0000000 --- a/pkg/webdav/mem.go +++ /dev/null @@ -1,483 +0,0 @@ -package webdav - -import ( - "context" - "encoding/xml" - "io" - "net/http" - "os" - "path" - "strings" - "sync" - "time" -) - -// NewMemFS returns a new in-memory FileSystem implementation. -func NewMemFS() FileSystem { - return &memFS{ - root: memFSNode{ - children: make(map[string]*memFSNode), - mode: 0660 | os.ModeDir, - modTime: time.Now(), - }, - } -} - -// A memFS implements FileSystem, storing all metadata and actual file data -// in-memory. No limits on filesystem size are used, so it is not recommended -// this be used where the clients are untrusted. -// -// Concurrent access is permitted. The tree structure is protected by a mutex, -// and each node's contents and metadata are protected by a per-node mutex. -// -// TODO: Enforce file permissions. -type memFS struct { - mu sync.Mutex - root memFSNode -} - -// TODO: clean up and rationalize the walk/find code. - -// walk walks the directory tree for the fullname, calling f at each step. If f -// returns an error, the walk will be aborted and return that same error. -// -// dir is the directory at that step, frag is the name fragment, and final is -// whether it is the final step. For example, walking "/foo/bar/x" will result -// in 3 calls to f: -// - "/", "foo", false -// - "/foo/", "bar", false -// - "/foo/bar/", "x", true -// The frag argument will be empty only if dir is the root node and the walk -// ends at that root node. -func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error { - original := fullname - fullname = slashClean(fullname) - - // Strip any leading "/"s to make fullname a relative path, as the walk - // starts at fs.root. - if fullname[0] == '/' { - fullname = fullname[1:] - } - dir := &fs.root - - for { - frag, remaining := fullname, "" - i := strings.IndexRune(fullname, '/') - final := i < 0 - if !final { - frag, remaining = fullname[:i], fullname[i+1:] - } - if frag == "" && dir != &fs.root { - panic("webdav: empty path fragment for a clean path") - } - if err := f(dir, frag, final); err != nil { - return &os.PathError{ - Op: op, - Path: original, - Err: err, - } - } - if final { - break - } - child := dir.children[frag] - if child == nil { - return &os.PathError{ - Op: op, - Path: original, - Err: os.ErrNotExist, - } - } - if !child.mode.IsDir() { - return &os.PathError{ - Op: op, - Path: original, - Err: os.ErrInvalid, - } - } - dir, fullname = child, remaining - } - return nil -} - -// find returns the parent of the named node and the relative name fragment -// from the parent to the child. For example, if finding "/foo/bar/baz" then -// parent will be the node for "/foo/bar" and frag will be "baz". -// -// If the fullname names the root node, then parent, frag and err will be zero. -// -// find returns an error if the parent does not already exist or the parent -// isn't a directory, but it will not return an error per se if the child does -// not already exist. The error returned is either nil or an *os.PathError -// whose Op is op. -func (fs *memFS) find(op, fullname string) (parent *memFSNode, frag string, err error) { - err = fs.walk(op, fullname, func(parent0 *memFSNode, frag0 string, final bool) error { - if !final { - return nil - } - if frag0 != "" { - parent, frag = parent0, frag0 - } - return nil - }) - return parent, frag, err -} - -func (fs *memFS) Mkdir(ctx context.Context, name string, perm os.FileMode) error { - fs.mu.Lock() - defer fs.mu.Unlock() - - dir, frag, err := fs.find("mkdir", name) - if err != nil { - return err - } - if dir == nil { - // We can't create the root. - return os.ErrInvalid - } - if _, ok := dir.children[frag]; ok { - return os.ErrExist - } - dir.children[frag] = &memFSNode{ - children: make(map[string]*memFSNode), - mode: perm.Perm() | os.ModeDir, - modTime: time.Now(), - } - return nil -} - -func (fs *memFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { - fs.mu.Lock() - defer fs.mu.Unlock() - - dir, frag, err := fs.find("open", name) - if err != nil { - return nil, err - } - var n *memFSNode - if dir == nil { - // We're opening the root. - if flag&(os.O_WRONLY|os.O_RDWR) != 0 { - return nil, os.ErrPermission - } - n, frag = &fs.root, "/" - - } else { - n = dir.children[frag] - if flag&(os.O_SYNC|os.O_APPEND) != 0 { - // memFile doesn't support these flags yet. - return nil, os.ErrInvalid - } - if flag&os.O_CREATE != 0 { - if flag&os.O_EXCL != 0 && n != nil { - return nil, os.ErrExist - } - if n == nil { - n = &memFSNode{ - mode: perm.Perm(), - } - dir.children[frag] = n - } - } - if n == nil { - return nil, os.ErrNotExist - } - if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 { - n.mu.Lock() - n.data = nil - n.mu.Unlock() - } - } - - children := make([]os.FileInfo, 0, len(n.children)) - for cName, c := range n.children { - children = append(children, c.stat(cName)) - } - return &memFile{ - n: n, - nameSnapshot: frag, - childrenSnapshot: children, - }, nil -} - -func (fs *memFS) RemoveAll(ctx context.Context, name string) error { - fs.mu.Lock() - defer fs.mu.Unlock() - - dir, frag, err := fs.find("remove", name) - if err != nil { - return err - } - if dir == nil { - // We can't remove the root. - return os.ErrInvalid - } - delete(dir.children, frag) - return nil -} - -func (fs *memFS) Rename(ctx context.Context, oldName, newName string) error { - fs.mu.Lock() - defer fs.mu.Unlock() - - oldName = slashClean(oldName) - newName = slashClean(newName) - if oldName == newName { - return nil - } - if strings.HasPrefix(newName, oldName+"/") { - // We can't rename oldName to be a sub-directory of itself. - return os.ErrInvalid - } - - oDir, oFrag, err := fs.find("rename", oldName) - if err != nil { - return err - } - if oDir == nil { - // We can't rename from the root. - return os.ErrInvalid - } - - nDir, nFrag, err := fs.find("rename", newName) - if err != nil { - return err - } - if nDir == nil { - // We can't rename to the root. - return os.ErrInvalid - } - - oNode, ok := oDir.children[oFrag] - if !ok { - return os.ErrNotExist - } - if oNode.children != nil { - if nNode, ok := nDir.children[nFrag]; ok { - if nNode.children == nil { - return errNotADirectory - } - if len(nNode.children) != 0 { - return errDirectoryNotEmpty - } - } - } - delete(oDir.children, oFrag) - nDir.children[nFrag] = oNode - return nil -} - -func (fs *memFS) Stat(ctx context.Context, name string) (os.FileInfo, error) { - fs.mu.Lock() - defer fs.mu.Unlock() - - dir, frag, err := fs.find("stat", name) - if err != nil { - return nil, err - } - if dir == nil { - // We're stat'ting the root. - return fs.root.stat("/"), nil - } - if n, ok := dir.children[frag]; ok { - return n.stat(path.Base(name)), nil - } - return nil, os.ErrNotExist -} - -// A memFSNode represents a single entry in the in-memory filesystem and also -// implements os.FileInfo. -type memFSNode struct { - // children is protected by memFS.mu. - children map[string]*memFSNode - - mu sync.Mutex - data []byte - mode os.FileMode - modTime time.Time - deadProps map[xml.Name]Property -} - -func (n *memFSNode) stat(name string) *memFileInfo { - n.mu.Lock() - defer n.mu.Unlock() - return &memFileInfo{ - name: name, - size: int64(len(n.data)), - mode: n.mode, - modTime: n.modTime, - } -} - -func (n *memFSNode) DeadProps() (map[xml.Name]Property, error) { - n.mu.Lock() - defer n.mu.Unlock() - if len(n.deadProps) == 0 { - return nil, nil - } - ret := make(map[xml.Name]Property, len(n.deadProps)) - for k, v := range n.deadProps { - ret[k] = v - } - return ret, nil -} - -func (n *memFSNode) Patch(patches []Proppatch) ([]Propstat, error) { - n.mu.Lock() - defer n.mu.Unlock() - pstat := Propstat{Status: http.StatusOK} - for _, patch := range patches { - for _, p := range patch.Props { - pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName}) - if patch.Remove { - delete(n.deadProps, p.XMLName) - continue - } - if n.deadProps == nil { - n.deadProps = map[xml.Name]Property{} - } - n.deadProps[p.XMLName] = p - } - } - return []Propstat{pstat}, nil -} - -type memFileInfo struct { - name string - size int64 - mode os.FileMode - modTime time.Time -} - -func (f *memFileInfo) Name() string { return f.name } -func (f *memFileInfo) Size() int64 { return f.size } -func (f *memFileInfo) Mode() os.FileMode { return f.mode } -func (f *memFileInfo) ModTime() time.Time { return f.modTime } -func (f *memFileInfo) IsDir() bool { return f.mode.IsDir() } -func (f *memFileInfo) Sys() interface{} { return nil } - -// A memFile is a File implementation for a memFSNode. It is a per-file (not -// per-node) read/write position, and a snapshot of the memFS' tree structure -// (a node's name and children) for that node. -type memFile struct { - n *memFSNode - nameSnapshot string - childrenSnapshot []os.FileInfo - // pos is protected by n.mu. - pos int -} - -// A *memFile implements the optional DeadPropsHolder interface. -var _ DeadPropsHolder = (*memFile)(nil) - -func (f *memFile) DeadProps() (map[xml.Name]Property, error) { return f.n.DeadProps() } -func (f *memFile) Patch(patches []Proppatch) ([]Propstat, error) { return f.n.Patch(patches) } - -func (f *memFile) Close() error { - return nil -} - -func (f *memFile) Read(p []byte) (int, error) { - f.n.mu.Lock() - defer f.n.mu.Unlock() - if f.n.mode.IsDir() { - return 0, os.ErrInvalid - } - if f.pos >= len(f.n.data) { - return 0, io.EOF - } - n := copy(p, f.n.data[f.pos:]) - f.pos += n - return n, nil -} - -func (f *memFile) Readdir(count int) ([]os.FileInfo, error) { - f.n.mu.Lock() - defer f.n.mu.Unlock() - if !f.n.mode.IsDir() { - return nil, os.ErrInvalid - } - old := f.pos - if old >= len(f.childrenSnapshot) { - // The os.File Readdir docs say that at the end of a directory, - // the error is io.EOF if count > 0 and nil if count <= 0. - if count > 0 { - return nil, io.EOF - } - return nil, nil - } - if count > 0 { - f.pos += count - if f.pos > len(f.childrenSnapshot) { - f.pos = len(f.childrenSnapshot) - } - } else { - f.pos = len(f.childrenSnapshot) - old = 0 - } - return f.childrenSnapshot[old:f.pos], nil -} - -func (f *memFile) Seek(offset int64, whence int) (int64, error) { - f.n.mu.Lock() - defer f.n.mu.Unlock() - npos := f.pos - // TODO: How to handle offsets greater than the size of system int? - switch whence { - case os.SEEK_SET: - npos = int(offset) - case os.SEEK_CUR: - npos += int(offset) - case os.SEEK_END: - npos = len(f.n.data) + int(offset) - default: - npos = -1 - } - if npos < 0 { - return 0, os.ErrInvalid - } - f.pos = npos - return int64(f.pos), nil -} - -func (f *memFile) Stat() (os.FileInfo, error) { - return f.n.stat(f.nameSnapshot), nil -} - -func (f *memFile) Write(p []byte) (int, error) { - lenp := len(p) - f.n.mu.Lock() - defer f.n.mu.Unlock() - - if f.n.mode.IsDir() { - return 0, os.ErrInvalid - } - if f.pos < len(f.n.data) { - n := copy(f.n.data[f.pos:], p) - f.pos += n - p = p[n:] - } else if f.pos > len(f.n.data) { - // Write permits the creation of holes, if we've seek'ed past the - // existing end of file. - if f.pos <= cap(f.n.data) { - oldLen := len(f.n.data) - f.n.data = f.n.data[:f.pos] - hole := f.n.data[oldLen:] - for i := range hole { - hole[i] = 0 - } - } else { - d := make([]byte, f.pos, f.pos+len(p)) - copy(d, f.n.data) - f.n.data = d - } - } - - if len(p) > 0 { - // We should only get here if f.pos == len(f.n.data). - f.n.data = append(f.n.data, p...) - f.pos = len(f.n.data) - } - f.n.modTime = time.Now() - return lenp, nil -} diff --git a/pkg/webdav/prop.go b/pkg/webdav/prop.go index f73dc40..7921d9a 100644 --- a/pkg/webdav/prop.go +++ b/pkg/webdav/prop.go @@ -21,6 +21,7 @@ type FileInfo interface { GetName() string ModTime() time.Time IsDir() bool + GetPosition() string } // Proppatch describes a property update instruction as defined in RFC 4918. diff --git a/pkg/webdav/prop_test.go b/pkg/webdav/prop_test.go deleted file mode 100644 index 855446b..0000000 --- a/pkg/webdav/prop_test.go +++ /dev/null @@ -1,716 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package webdav - -import ( - "context" - "encoding/xml" - "fmt" - "net/http" - "os" - "reflect" - "regexp" - "sort" - "testing" -) - -func TestMemPS(t *testing.T) { - ctx := context.Background() - // calcProps calculates the getlastmodified and getetag DAV: property - // values in pstats for resource name in file-system fs. - calcProps := func(name string, fs FileSystem, ls LockSystem, pstats []Propstat) error { - fi, err := fs.Stat(ctx, name) - if err != nil { - return err - } - for _, pst := range pstats { - for i, p := range pst.Props { - switch p.XMLName { - case xml.Name{Space: "DAV:", Local: "getlastmodified"}: - p.InnerXML = []byte(fi.ModTime().UTC().Format(http.TimeFormat)) - pst.Props[i] = p - case xml.Name{Space: "DAV:", Local: "getetag"}: - if fi.IsDir() { - continue - } - etag, err := findETag(ctx, fs, ls, name, fi) - if err != nil { - return err - } - p.InnerXML = []byte(etag) - pst.Props[i] = p - } - } - } - return nil - } - - const ( - lockEntry = `` + - `` + - `` + - `` + - `` - statForbiddenError = `` - ) - - type propOp struct { - op string - name string - pnames []xml.Name - patches []Proppatch - wantPnames []xml.Name - wantPropstats []Propstat - } - - testCases := []struct { - desc string - noDeadProps bool - buildfs []string - propOp []propOp - }{{ - desc: "propname", - buildfs: []string{"mkdir /dir", "touch /file"}, - propOp: []propOp{{ - op: "propname", - name: "/dir", - wantPnames: []xml.Name{ - {Space: "DAV:", Local: "resourcetype"}, - {Space: "DAV:", Local: "displayname"}, - {Space: "DAV:", Local: "supportedlock"}, - {Space: "DAV:", Local: "getlastmodified"}, - }, - }, { - op: "propname", - name: "/file", - wantPnames: []xml.Name{ - {Space: "DAV:", Local: "resourcetype"}, - {Space: "DAV:", Local: "displayname"}, - {Space: "DAV:", Local: "getcontentlength"}, - {Space: "DAV:", Local: "getlastmodified"}, - {Space: "DAV:", Local: "getcontenttype"}, - {Space: "DAV:", Local: "getetag"}, - {Space: "DAV:", Local: "supportedlock"}, - }, - }}, - }, { - desc: "allprop dir and file", - buildfs: []string{"mkdir /dir", "write /file foobarbaz"}, - propOp: []propOp{{ - op: "allprop", - name: "/dir", - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, - InnerXML: []byte(``), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, - InnerXML: []byte("dir"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, - InnerXML: nil, // Calculated during test. - }, { - XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, - InnerXML: []byte(lockEntry), - }}, - }}, - }, { - op: "allprop", - name: "/file", - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, - InnerXML: []byte(""), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, - InnerXML: []byte("file"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, - InnerXML: []byte("9"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, - InnerXML: nil, // Calculated during test. - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, - InnerXML: []byte("text/plain; charset=utf-8"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - InnerXML: nil, // Calculated during test. - }, { - XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, - InnerXML: []byte(lockEntry), - }}, - }}, - }, { - op: "allprop", - name: "/file", - pnames: []xml.Name{ - {"DAV:", "resourcetype"}, - {"foo", "bar"}, - }, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, - InnerXML: []byte(""), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, - InnerXML: []byte("file"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, - InnerXML: []byte("9"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, - InnerXML: nil, // Calculated during test. - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, - InnerXML: []byte("text/plain; charset=utf-8"), - }, { - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - InnerXML: nil, // Calculated during test. - }, { - XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, - InnerXML: []byte(lockEntry), - }}}, { - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}}, - }, - }}, - }, { - desc: "propfind DAV:resourcetype", - buildfs: []string{"mkdir /dir", "touch /file"}, - propOp: []propOp{{ - op: "propfind", - name: "/dir", - pnames: []xml.Name{{"DAV:", "resourcetype"}}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, - InnerXML: []byte(``), - }}, - }}, - }, { - op: "propfind", - name: "/file", - pnames: []xml.Name{{"DAV:", "resourcetype"}}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, - InnerXML: []byte(""), - }}, - }}, - }}, - }, { - desc: "propfind unsupported DAV properties", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "propfind", - name: "/dir", - pnames: []xml.Name{{"DAV:", "getcontentlanguage"}}, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "getcontentlanguage"}, - }}, - }}, - }, { - op: "propfind", - name: "/dir", - pnames: []xml.Name{{"DAV:", "creationdate"}}, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "creationdate"}, - }}, - }}, - }}, - }, { - desc: "propfind getetag for files but not for directories", - buildfs: []string{"mkdir /dir", "touch /file"}, - propOp: []propOp{{ - op: "propfind", - name: "/dir", - pnames: []xml.Name{{"DAV:", "getetag"}}, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - }}, - }}, - }, { - op: "propfind", - name: "/file", - pnames: []xml.Name{{"DAV:", "getetag"}}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - InnerXML: nil, // Calculated during test. - }}, - }}, - }}, - }, { - desc: "proppatch property on no-dead-properties file system", - buildfs: []string{"mkdir /dir"}, - noDeadProps: true, - propOp: []propOp{{ - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusForbidden, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }, { - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusForbidden, - XMLError: statForbiddenError, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, - }}, - }}, - }}, - }, { - desc: "proppatch dead property", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }, { - op: "propfind", - name: "/dir", - pnames: []xml.Name{{Space: "foo", Local: "bar"}}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }}, - }}, - }}, - }, { - desc: "proppatch dead property with failed dependency", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }}, - }, { - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, - InnerXML: []byte("xxx"), - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusForbidden, - XMLError: statForbiddenError, - Props: []Property{{ - XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, - }}, - }, { - Status: StatusFailedDependency, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }, { - op: "propfind", - name: "/dir", - pnames: []xml.Name{{Space: "foo", Local: "bar"}}, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }}, - }, { - desc: "proppatch remove dead property", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }, { - XMLName: xml.Name{Space: "spam", Local: "ham"}, - InnerXML: []byte("eggs"), - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }, { - XMLName: xml.Name{Space: "spam", Local: "ham"}, - }}, - }}, - }, { - op: "propfind", - name: "/dir", - pnames: []xml.Name{ - {Space: "foo", Local: "bar"}, - {Space: "spam", Local: "ham"}, - }, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }, { - XMLName: xml.Name{Space: "spam", Local: "ham"}, - InnerXML: []byte("eggs"), - }}, - }}, - }, { - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Remove: true, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }, { - op: "propfind", - name: "/dir", - pnames: []xml.Name{ - {Space: "foo", Local: "bar"}, - {Space: "spam", Local: "ham"}, - }, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }, { - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "spam", Local: "ham"}, - InnerXML: []byte("eggs"), - }}, - }}, - }}, - }, { - desc: "propname with dead property", - buildfs: []string{"touch /file"}, - propOp: []propOp{{ - op: "proppatch", - name: "/file", - patches: []Proppatch{{ - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - InnerXML: []byte("baz"), - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }, { - op: "propname", - name: "/file", - wantPnames: []xml.Name{ - {Space: "DAV:", Local: "resourcetype"}, - {Space: "DAV:", Local: "displayname"}, - {Space: "DAV:", Local: "getcontentlength"}, - {Space: "DAV:", Local: "getlastmodified"}, - {Space: "DAV:", Local: "getcontenttype"}, - {Space: "DAV:", Local: "getetag"}, - {Space: "DAV:", Local: "supportedlock"}, - {Space: "foo", Local: "bar"}, - }, - }}, - }, { - desc: "proppatch remove unknown dead property", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "proppatch", - name: "/dir", - patches: []Proppatch{{ - Remove: true, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - wantPropstats: []Propstat{{ - Status: http.StatusOK, - Props: []Property{{ - XMLName: xml.Name{Space: "foo", Local: "bar"}, - }}, - }}, - }}, - }, { - desc: "bad: propfind unknown property", - buildfs: []string{"mkdir /dir"}, - propOp: []propOp{{ - op: "propfind", - name: "/dir", - pnames: []xml.Name{{"foo:", "bar"}}, - wantPropstats: []Propstat{{ - Status: http.StatusNotFound, - Props: []Property{{ - XMLName: xml.Name{Space: "foo:", Local: "bar"}, - }}, - }}, - }}, - }} - - for _, tc := range testCases { - fs, err := buildTestFS(tc.buildfs) - if err != nil { - t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) - } - if tc.noDeadProps { - fs = noDeadPropsFS{fs} - } - ls := NewMemLS() - for _, op := range tc.propOp { - desc := fmt.Sprintf("%s: %s %s", tc.desc, op.op, op.name) - if err = calcProps(op.name, fs, ls, op.wantPropstats); err != nil { - t.Fatalf("%s: calcProps: %v", desc, err) - } - - // Call property system. - var propstats []Propstat - switch op.op { - case "propname": - pnames, err := propnames(ctx, fs, ls, op.name) - if err != nil { - t.Errorf("%s: got error %v, want nil", desc, err) - continue - } - sort.Sort(byXMLName(pnames)) - sort.Sort(byXMLName(op.wantPnames)) - if !reflect.DeepEqual(pnames, op.wantPnames) { - t.Errorf("%s: pnames\ngot %q\nwant %q", desc, pnames, op.wantPnames) - } - continue - case "allprop": - propstats, err = allprop(ctx, fs, ls, op.name, op.pnames) - case "propfind": - propstats, err = props(ctx, fs, ls, op.name, op.pnames) - case "proppatch": - propstats, err = patch(ctx, fs, ls, op.name, op.patches) - default: - t.Fatalf("%s: %s not implemented", desc, op.op) - } - if err != nil { - t.Errorf("%s: got error %v, want nil", desc, err) - continue - } - // Compare return values from allprop, propfind or proppatch. - for _, pst := range propstats { - sort.Sort(byPropname(pst.Props)) - } - for _, pst := range op.wantPropstats { - sort.Sort(byPropname(pst.Props)) - } - sort.Sort(byStatus(propstats)) - sort.Sort(byStatus(op.wantPropstats)) - if !reflect.DeepEqual(propstats, op.wantPropstats) { - t.Errorf("%s: propstat\ngot %q\nwant %q", desc, propstats, op.wantPropstats) - } - } - } -} - -func cmpXMLName(a, b xml.Name) bool { - if a.Space != b.Space { - return a.Space < b.Space - } - return a.Local < b.Local -} - -type byXMLName []xml.Name - -func (b byXMLName) Len() int { return len(b) } -func (b byXMLName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b byXMLName) Less(i, j int) bool { return cmpXMLName(b[i], b[j]) } - -type byPropname []Property - -func (b byPropname) Len() int { return len(b) } -func (b byPropname) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b byPropname) Less(i, j int) bool { return cmpXMLName(b[i].XMLName, b[j].XMLName) } - -type byStatus []Propstat - -func (b byStatus) Len() int { return len(b) } -func (b byStatus) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b byStatus) Less(i, j int) bool { return b[i].Status < b[j].Status } - -type noDeadPropsFS struct { - FileSystem -} - -func (fs noDeadPropsFS) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (File, error) { - f, err := fs.FileSystem.OpenFile(ctx, name, flag, perm) - if err != nil { - return nil, err - } - return noDeadPropsFile{f}, nil -} - -// noDeadPropsFile wraps a File but strips any optional DeadPropsHolder methods -// provided by the underlying File implementation. -type noDeadPropsFile struct { - f File -} - -func (f noDeadPropsFile) Close() error { return f.f.Close() } -func (f noDeadPropsFile) Read(p []byte) (int, error) { return f.f.Read(p) } -func (f noDeadPropsFile) Readdir(count int) ([]os.FileInfo, error) { return f.f.Readdir(count) } -func (f noDeadPropsFile) Seek(off int64, whence int) (int64, error) { return f.f.Seek(off, whence) } -func (f noDeadPropsFile) Stat() (os.FileInfo, error) { return f.f.Stat() } -func (f noDeadPropsFile) Write(p []byte) (int, error) { return f.f.Write(p) } - -type overrideContentType struct { - os.FileInfo - contentType string - err error -} - -func (o *overrideContentType) ContentType(ctx context.Context) (string, error) { - return o.contentType, o.err -} - -func TestFindContentTypeOverride(t *testing.T) { - fs, err := buildTestFS([]string{"touch /file"}) - if err != nil { - t.Fatalf("cannot create test filesystem: %v", err) - } - ctx := context.Background() - fi, err := fs.Stat(ctx, "/file") - if err != nil { - t.Fatalf("cannot Stat /file: %v", err) - } - - // Check non overridden case - originalContentType, err := findContentType(ctx, fs, nil, "/file", fi) - if err != nil { - t.Fatalf("findContentType /file failed: %v", err) - } - if originalContentType != "text/plain; charset=utf-8" { - t.Fatalf("ContentType wrong want %q got %q", "text/plain; charset=utf-8", originalContentType) - } - - // Now try overriding the ContentType - o := &overrideContentType{fi, "OverriddenContentType", nil} - ContentType, err := findContentType(ctx, fs, nil, "/file", o) - if err != nil { - t.Fatalf("findContentType /file failed: %v", err) - } - if ContentType != o.contentType { - t.Fatalf("ContentType wrong want %q got %q", o.contentType, ContentType) - } - - // Now return ErrNotImplemented and check we get the original content type - o = &overrideContentType{fi, "OverriddenContentType", ErrNotImplemented} - ContentType, err = findContentType(ctx, fs, nil, "/file", o) - if err != nil { - t.Fatalf("findContentType /file failed: %v", err) - } - if ContentType != originalContentType { - t.Fatalf("ContentType wrong want %q got %q", originalContentType, ContentType) - } -} - -type overrideETag struct { - os.FileInfo - eTag string - err error -} - -func (o *overrideETag) ETag(ctx context.Context) (string, error) { - return o.eTag, o.err -} - -func TestFindETagOverride(t *testing.T) { - fs, err := buildTestFS([]string{"touch /file"}) - if err != nil { - t.Fatalf("cannot create test filesystem: %v", err) - } - ctx := context.Background() - fi, err := fs.Stat(ctx, "/file") - if err != nil { - t.Fatalf("cannot Stat /file: %v", err) - } - - // Check non overridden case - originalETag, err := findETag(ctx, fs, nil, "/file", fi) - if err != nil { - t.Fatalf("findETag /file failed: %v", err) - } - matchETag := regexp.MustCompile(`^"-?[0-9a-f]{6,}"$`) - if !matchETag.MatchString(originalETag) { - t.Fatalf("ETag wrong, wanted something matching %v got %q", matchETag, originalETag) - } - - // Now try overriding the ETag - o := &overrideETag{fi, `"OverriddenETag"`, nil} - ETag, err := findETag(ctx, fs, nil, "/file", o) - if err != nil { - t.Fatalf("findETag /file failed: %v", err) - } - if ETag != o.eTag { - t.Fatalf("ETag wrong want %q got %q", o.eTag, ETag) - } - - // Now return ErrNotImplemented and check we get the original Etag - o = &overrideETag{fi, `"OverriddenETag"`, ErrNotImplemented} - ETag, err = findETag(ctx, fs, nil, "/file", o) - if err != nil { - t.Fatalf("findETag /file failed: %v", err) - } - if ETag != originalETag { - t.Fatalf("ETag wrong want %q got %q", originalETag, ETag) - } -} diff --git a/pkg/webdav/webdav.go b/pkg/webdav/webdav.go index 87ab564..8396fe7 100644 --- a/pkg/webdav/webdav.go +++ b/pkg/webdav/webdav.go @@ -24,8 +24,6 @@ import ( type Handler struct { // Prefix is the URL path prefix to strip from WebDAV resource paths. Prefix string - // FileSystem is the virtual file system. - FileSystem FileSystem // LockSystem is the lock management system. LockSystem map[uint]LockSystem // Logger is an optional error logger. If non-nil, it will be called @@ -58,9 +56,7 @@ func isPathExist(ctx context.Context, fs *filesystem.FileSystem, path string) (b func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) { status, err := http.StatusBadRequest, errUnsupportedMethod - if h.FileSystem == nil { - status, err = http.StatusInternalServerError, errNoFileSystem - } else if h.LockSystem == nil { + if h.LockSystem == nil { status, err = http.StatusInternalServerError, errNoLockSystem } else { // 检查并新建LockSystem @@ -205,7 +201,7 @@ func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request, fs *file } ctx := r.Context() allow := "OPTIONS, LOCK, PUT, MKCOL" - if fi, err := h.FileSystem.Stat(ctx, reqPath); err == nil { + if exist, fi := isPathExist(ctx, fs, reqPath); exist { if fi.IsDir() { allow = "OPTIONS, LOCK, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND" } else { @@ -375,6 +371,7 @@ func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request, fs *filesy return http.StatusCreated, nil } +// OK func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request, fs *filesystem.FileSystem) (status int, err error) { hdr := r.Header.Get("Destination") if hdr == "" { @@ -453,7 +450,7 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request, fs *fil return http.StatusBadRequest, errInvalidDepth } } - return moveFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T") + return moveFiles(ctx, fs, target, dst, r.Header.Get("Overwrite") == "T") } // OK diff --git a/pkg/webdav/webdav_test.go b/pkg/webdav/webdav_test.go deleted file mode 100644 index 2baebe3..0000000 --- a/pkg/webdav/webdav_test.go +++ /dev/null @@ -1,349 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package webdav - -import ( - "context" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "regexp" - "sort" - "strings" - "testing" -) - -// TODO: add tests to check XML responses with the expected prefix path -func TestPrefix(t *testing.T) { - const dst, blah = "Destination", "blah blah blah" - - // createLockBody comes from the example in Section 9.10.7. - const createLockBody = ` - - - - - http://example.org/~ejw/contact.html - - - ` - - do := func(method, urlStr string, body string, wantStatusCode int, headers ...string) (http.Header, error) { - var bodyReader io.Reader - if body != "" { - bodyReader = strings.NewReader(body) - } - req, err := http.NewRequest(method, urlStr, bodyReader) - if err != nil { - return nil, err - } - for len(headers) >= 2 { - req.Header.Add(headers[0], headers[1]) - headers = headers[2:] - } - res, err := http.DefaultTransport.RoundTrip(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode != wantStatusCode { - return nil, fmt.Errorf("got status code %d, want %d", res.StatusCode, wantStatusCode) - } - return res.Header, nil - } - - prefixes := []string{ - "/", - "/a/", - "/a/b/", - "/a/b/c/", - } - ctx := context.Background() - for _, prefix := range prefixes { - fs := NewMemFS() - h := &Handler{ - FileSystem: fs, - LockSystem: NewMemLS(), - } - mux := http.NewServeMux() - if prefix != "/" { - h.Prefix = prefix - } - mux.Handle(prefix, h) - srv := httptest.NewServer(mux) - defer srv.Close() - - // The script is: - // MKCOL /a - // MKCOL /a/b - // PUT /a/b/c - // COPY /a/b/c /a/b/d - // MKCOL /a/b/e - // MOVE /a/b/d /a/b/e/f - // LOCK /a/b/e/g - // PUT /a/b/e/g - // which should yield the (possibly stripped) filenames /a/b/c, - // /a/b/e/f and /a/b/e/g, plus their parent directories. - - wantA := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusMovedPermanently, - "/a/b/": http.StatusNotFound, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if _, err := do("MKCOL", srv.URL+"/a", "", wantA); err != nil { - t.Errorf("prefix=%-9q MKCOL /a: %v", prefix, err) - continue - } - - wantB := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusMovedPermanently, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if _, err := do("MKCOL", srv.URL+"/a/b", "", wantB); err != nil { - t.Errorf("prefix=%-9q MKCOL /a/b: %v", prefix, err) - continue - } - - wantC := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusMovedPermanently, - }[prefix] - if _, err := do("PUT", srv.URL+"/a/b/c", blah, wantC); err != nil { - t.Errorf("prefix=%-9q PUT /a/b/c: %v", prefix, err) - continue - } - - wantD := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusMovedPermanently, - }[prefix] - if _, err := do("COPY", srv.URL+"/a/b/c", "", wantD, dst, srv.URL+"/a/b/d"); err != nil { - t.Errorf("prefix=%-9q COPY /a/b/c /a/b/d: %v", prefix, err) - continue - } - - wantE := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if _, err := do("MKCOL", srv.URL+"/a/b/e", "", wantE); err != nil { - t.Errorf("prefix=%-9q MKCOL /a/b/e: %v", prefix, err) - continue - } - - wantF := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if _, err := do("MOVE", srv.URL+"/a/b/d", "", wantF, dst, srv.URL+"/a/b/e/f"); err != nil { - t.Errorf("prefix=%-9q MOVE /a/b/d /a/b/e/f: %v", prefix, err) - continue - } - - var lockToken string - wantG := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if h, err := do("LOCK", srv.URL+"/a/b/e/g", createLockBody, wantG); err != nil { - t.Errorf("prefix=%-9q LOCK /a/b/e/g: %v", prefix, err) - continue - } else { - lockToken = h.Get("Lock-Token") - } - - ifHeader := fmt.Sprintf("<%s/a/b/e/g> (%s)", srv.URL, lockToken) - wantH := map[string]int{ - "/": http.StatusCreated, - "/a/": http.StatusCreated, - "/a/b/": http.StatusCreated, - "/a/b/c/": http.StatusNotFound, - }[prefix] - if _, err := do("PUT", srv.URL+"/a/b/e/g", blah, wantH, "If", ifHeader); err != nil { - t.Errorf("prefix=%-9q PUT /a/b/e/g: %v", prefix, err) - continue - } - - got, err := find(ctx, nil, fs, "/") - if err != nil { - t.Errorf("prefix=%-9q find: %v", prefix, err) - continue - } - sort.Strings(got) - want := map[string][]string{ - "/": {"/", "/a", "/a/b", "/a/b/c", "/a/b/e", "/a/b/e/f", "/a/b/e/g"}, - "/a/": {"/", "/b", "/b/c", "/b/e", "/b/e/f", "/b/e/g"}, - "/a/b/": {"/", "/c", "/e", "/e/f", "/e/g"}, - "/a/b/c/": {"/"}, - }[prefix] - if !reflect.DeepEqual(got, want) { - t.Errorf("prefix=%-9q find:\ngot %v\nwant %v", prefix, got, want) - continue - } - } -} - -func TestEscapeXML(t *testing.T) { - // These test cases aren't exhaustive, and there is more than one way to - // escape e.g. a quot (as """ or """) or an apos. We presume that - // the encoding/xml package tests xml.EscapeText more thoroughly. This test - // here is just a sanity check for this package's escapeXML function, and - // its attempt to provide a fast path (and avoid a bytes.Buffer allocation) - // when escaping filenames is obviously a no-op. - testCases := map[string]string{ - "": "", - " ": " ", - "&": "&", - "*": "*", - "+": "+", - ",": ",", - "-": "-", - ".": ".", - "/": "/", - "0": "0", - "9": "9", - ":": ":", - "<": "<", - ">": ">", - "A": "A", - "_": "_", - "a": "a", - "~": "~", - "\u0201": "\u0201", - "&": "&amp;", - "foo&baz": "foo&<b/ar>baz", - } - - for in, want := range testCases { - if got := escapeXML(in); got != want { - t.Errorf("in=%q: got %q, want %q", in, got, want) - } - } -} - -func TestFilenameEscape(t *testing.T) { - hrefRe := regexp.MustCompile(`([^<]*)`) - displayNameRe := regexp.MustCompile(`([^<]*)`) - do := func(method, urlStr string) (string, string, error) { - req, err := http.NewRequest(method, urlStr, nil) - if err != nil { - return "", "", err - } - res, err := http.DefaultClient.Do(req) - if err != nil { - return "", "", err - } - defer res.Body.Close() - - b, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - hrefMatch := hrefRe.FindStringSubmatch(string(b)) - if len(hrefMatch) != 2 { - return "", "", errors.New("D:href not found") - } - displayNameMatch := displayNameRe.FindStringSubmatch(string(b)) - if len(displayNameMatch) != 2 { - return "", "", errors.New("D:displayname not found") - } - - return hrefMatch[1], displayNameMatch[1], nil - } - - testCases := []struct { - name, wantHref, wantDisplayName string - }{{ - name: `/foo%bar`, - wantHref: `/foo%25bar`, - wantDisplayName: `foo%bar`, - }, { - name: `/こんにちわ世界`, - wantHref: `/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%82%8F%E4%B8%96%E7%95%8C`, - wantDisplayName: `こんにちわ世界`, - }, { - name: `/Program Files/`, - wantHref: `/Program%20Files/`, - wantDisplayName: `Program Files`, - }, { - name: `/go+lang`, - wantHref: `/go+lang`, - wantDisplayName: `go+lang`, - }, { - name: `/go&lang`, - wantHref: `/go&lang`, - wantDisplayName: `go&lang`, - }, { - name: `/go\n" + - " \n" + - " \n" + - " \n" + - " no end tag \n" + - " \n" + - "", - lockInfo{}, - http.StatusBadRequest, - }, { - "bad: invalid UTF-8", - "" + - "\n" + - " \n" + - " \n" + - " \n" + - " \xff \n" + - " \n" + - "", - lockInfo{}, - http.StatusBadRequest, - }, { - "bad: unfinished XML #1", - "" + - "\n" + - " \n" + - " \n", - lockInfo{}, - http.StatusBadRequest, - }, { - "bad: unfinished XML #2", - "" + - "\n" + - " \n" + - " \n" + - " \n", - lockInfo{}, - http.StatusBadRequest, - }, { - "good: empty", - "", - lockInfo{}, - 0, - }, { - "good: plain-text owner", - "" + - "\n" + - " \n" + - " \n" + - " gopher\n" + - "", - lockInfo{ - XMLName: ixml.Name{Space: "DAV:", Local: "lockinfo"}, - Exclusive: new(struct{}), - Write: new(struct{}), - Owner: owner{ - InnerXML: "gopher", - }, - }, - 0, - }, { - "section 9.10.7", - "" + - "\n" + - " \n" + - " \n" + - " \n" + - " http://example.org/~ejw/contact.html\n" + - " \n" + - "", - lockInfo{ - XMLName: ixml.Name{Space: "DAV:", Local: "lockinfo"}, - Exclusive: new(struct{}), - Write: new(struct{}), - Owner: owner{ - InnerXML: "\n http://example.org/~ejw/contact.html\n ", - }, - }, - 0, - }} - - for _, tc := range testCases { - li, status, err := readLockInfo(strings.NewReader(tc.input)) - if tc.wantStatus != 0 { - if err == nil { - t.Errorf("%s: got nil error, want non-nil", tc.desc) - continue - } - } else if err != nil { - t.Errorf("%s: %v", tc.desc, err) - continue - } - if !reflect.DeepEqual(li, tc.wantLI) || status != tc.wantStatus { - t.Errorf("%s:\ngot lockInfo=%v, status=%v\nwant lockInfo=%v, status=%v", - tc.desc, li, status, tc.wantLI, tc.wantStatus) - continue - } - } -} - -func TestReadPropfind(t *testing.T) { - testCases := []struct { - desc string - input string - wantPF propfind - wantStatus int - }{{ - desc: "propfind: propname", - input: "" + - "\n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Propname: new(struct{}), - }, - }, { - desc: "propfind: empty body means allprop", - input: "", - wantPF: propfind{ - Allprop: new(struct{}), - }, - }, { - desc: "propfind: allprop", - input: "" + - "\n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Allprop: new(struct{}), - }, - }, { - desc: "propfind: allprop followed by include", - input: "" + - "\n" + - " \n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Allprop: new(struct{}), - Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: include followed by allprop", - input: "" + - "\n" + - " \n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Allprop: new(struct{}), - Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: propfind", - input: "" + - "\n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: prop with ignored comments", - input: "" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: propfind with ignored whitespace", - input: "" + - "\n" + - " \n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: propfind with ignored mixed-content", - input: "" + - "\n" + - " foobar\n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, - }, - }, { - desc: "propfind: propname with ignored element (section A.4)", - input: "" + - "\n" + - " \n" + - " *boss*\n" + - "", - wantPF: propfind{ - XMLName: ixml.Name{Space: "DAV:", Local: "propfind"}, - Propname: new(struct{}), - }, - }, { - desc: "propfind: bad: junk", - input: "xxx", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: propname and allprop (section A.3)", - input: "" + - "\n" + - " " + - " " + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: propname and prop", - input: "" + - "\n" + - " \n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: allprop and prop", - input: "" + - "\n" + - " \n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: empty propfind with ignored element (section A.4)", - input: "" + - "\n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: empty prop", - input: "" + - "\n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: prop with just chardata", - input: "" + - "\n" + - " foo\n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "bad: interrupted prop", - input: "" + - "\n" + - " \n", - wantStatus: http.StatusBadRequest, - }, { - desc: "bad: malformed end element prop", - input: "" + - "\n" + - " \n", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: property with chardata value", - input: "" + - "\n" + - " bar\n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: property with whitespace value", - input: "" + - "\n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }, { - desc: "propfind: bad: include without allprop", - input: "" + - "\n" + - " \n" + - "", - wantStatus: http.StatusBadRequest, - }} - - for _, tc := range testCases { - pf, status, err := readPropfind(strings.NewReader(tc.input)) - if tc.wantStatus != 0 { - if err == nil { - t.Errorf("%s: got nil error, want non-nil", tc.desc) - continue - } - } else if err != nil { - t.Errorf("%s: %v", tc.desc, err) - continue - } - if !reflect.DeepEqual(pf, tc.wantPF) || status != tc.wantStatus { - t.Errorf("%s:\ngot propfind=%v, status=%v\nwant propfind=%v, status=%v", - tc.desc, pf, status, tc.wantPF, tc.wantStatus) - continue - } - } -} - -func TestMultistatusWriter(t *testing.T) { - ///The "section x.y.z" test cases come from section x.y.z of the spec at - // http://www.webdav.org/specs/rfc4918.html - testCases := []struct { - desc string - responses []response - respdesc string - writeHeader bool - wantXML string - wantCode int - wantErr error - }{{ - desc: "section 9.2.2 (failed dependency)", - responses: []response{{ - Href: []string{"http://example.com/foo"}, - Propstat: []propstat{{ - Prop: []Property{{ - XMLName: xml.Name{ - Space: "http://ns.example.com/", - Local: "Authors", - }, - }}, - Status: "HTTP/1.1 424 Failed Dependency", - }, { - Prop: []Property{{ - XMLName: xml.Name{ - Space: "http://ns.example.com/", - Local: "Copyright-Owner", - }, - }}, - Status: "HTTP/1.1 409 Conflict", - }}, - ResponseDescription: "Copyright Owner cannot be deleted or altered.", - }}, - wantXML: `` + - `` + - `` + - ` ` + - ` http://example.com/foo` + - ` ` + - ` ` + - ` ` + - ` ` + - ` HTTP/1.1 424 Failed Dependency` + - ` ` + - ` ` + - ` ` + - ` ` + - ` ` + - ` HTTP/1.1 409 Conflict` + - ` ` + - ` Copyright Owner cannot be deleted or altered.` + - `` + - ``, - wantCode: StatusMulti, - }, { - desc: "section 9.6.2 (lock-token-submitted)", - responses: []response{{ - Href: []string{"http://example.com/foo"}, - Status: "HTTP/1.1 423 Locked", - Error: &xmlError{ - InnerXML: []byte(``), - }, - }}, - wantXML: `` + - `` + - `` + - ` ` + - ` http://example.com/foo` + - ` HTTP/1.1 423 Locked` + - ` ` + - ` ` + - ``, - wantCode: StatusMulti, - }, { - desc: "section 9.1.3", - responses: []response{{ - Href: []string{"http://example.com/foo"}, - Propstat: []propstat{{ - Prop: []Property{{ - XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "bigbox"}, - InnerXML: []byte(`` + - `` + - `Box type A` + - ``), - }, { - XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "author"}, - InnerXML: []byte(`` + - `` + - `J.J. Johnson` + - ``), - }}, - Status: "HTTP/1.1 200 OK", - }, { - Prop: []Property{{ - XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "DingALing"}, - }, { - XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "Random"}, - }}, - Status: "HTTP/1.1 403 Forbidden", - ResponseDescription: "The user does not have access to the DingALing property.", - }}, - }}, - respdesc: "There has been an access violation error.", - wantXML: `` + - `` + - `` + - ` ` + - ` http://example.com/foo` + - ` ` + - ` ` + - ` Box type A` + - ` J.J. Johnson` + - ` ` + - ` HTTP/1.1 200 OK` + - ` ` + - ` ` + - ` ` + - ` ` + - ` ` + - ` ` + - ` HTTP/1.1 403 Forbidden` + - ` The user does not have access to the DingALing property.` + - ` ` + - ` ` + - ` There has been an access violation error.` + - ``, - wantCode: StatusMulti, - }, { - desc: "no response written", - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "no response written (with description)", - respdesc: "too bad", - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "empty multistatus with header", - writeHeader: true, - wantXML: ``, - wantCode: StatusMulti, - }, { - desc: "bad: no href", - responses: []response{{ - Propstat: []propstat{{ - Prop: []Property{{ - XMLName: xml.Name{ - Space: "http://example.com/", - Local: "foo", - }, - }}, - Status: "HTTP/1.1 200 OK", - }}, - }}, - wantErr: errInvalidResponse, - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "bad: multiple hrefs and no status", - responses: []response{{ - Href: []string{"http://example.com/foo", "http://example.com/bar"}, - }}, - wantErr: errInvalidResponse, - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "bad: one href and no propstat", - responses: []response{{ - Href: []string{"http://example.com/foo"}, - }}, - wantErr: errInvalidResponse, - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "bad: status with one href and propstat", - responses: []response{{ - Href: []string{"http://example.com/foo"}, - Propstat: []propstat{{ - Prop: []Property{{ - XMLName: xml.Name{ - Space: "http://example.com/", - Local: "foo", - }, - }}, - Status: "HTTP/1.1 200 OK", - }}, - Status: "HTTP/1.1 200 OK", - }}, - wantErr: errInvalidResponse, - // default of http.responseWriter - wantCode: http.StatusOK, - }, { - desc: "bad: multiple hrefs and propstat", - responses: []response{{ - Href: []string{ - "http://example.com/foo", - "http://example.com/bar", - }, - Propstat: []propstat{{ - Prop: []Property{{ - XMLName: xml.Name{ - Space: "http://example.com/", - Local: "foo", - }, - }}, - Status: "HTTP/1.1 200 OK", - }}, - }}, - wantErr: errInvalidResponse, - // default of http.responseWriter - wantCode: http.StatusOK, - }} - - n := xmlNormalizer{omitWhitespace: true} -loop: - for _, tc := range testCases { - rec := httptest.NewRecorder() - w := multistatusWriter{w: rec, responseDescription: tc.respdesc} - if tc.writeHeader { - if err := w.writeHeader(); err != nil { - t.Errorf("%s: got writeHeader error %v, want nil", tc.desc, err) - continue - } - } - for _, r := range tc.responses { - if err := w.write(&r); err != nil { - if err != tc.wantErr { - t.Errorf("%s: got write error %v, want %v", - tc.desc, err, tc.wantErr) - } - continue loop - } - } - if err := w.close(); err != tc.wantErr { - t.Errorf("%s: got close error %v, want %v", - tc.desc, err, tc.wantErr) - continue - } - if rec.Code != tc.wantCode { - t.Errorf("%s: got HTTP status code %d, want %d\n", - tc.desc, rec.Code, tc.wantCode) - continue - } - gotXML := rec.Body.String() - eq, err := n.equalXML(strings.NewReader(gotXML), strings.NewReader(tc.wantXML)) - if err != nil { - t.Errorf("%s: equalXML: %v", tc.desc, err) - continue - } - if !eq { - t.Errorf("%s: XML body\ngot %s\nwant %s", tc.desc, gotXML, tc.wantXML) - } - } -} - -func TestReadProppatch(t *testing.T) { - ppStr := func(pps []Proppatch) string { - var outer []string - for _, pp := range pps { - var inner []string - for _, p := range pp.Props { - inner = append(inner, fmt.Sprintf("{XMLName: %q, Lang: %q, InnerXML: %q}", - p.XMLName, p.Lang, p.InnerXML)) - } - outer = append(outer, fmt.Sprintf("{Remove: %t, Props: [%s]}", - pp.Remove, strings.Join(inner, ", "))) - } - return "[" + strings.Join(outer, ", ") + "]" - } - - testCases := []struct { - desc string - input string - wantPP []Proppatch - wantStatus int - }{{ - desc: "proppatch: section 9.2 (with simple property value)", - input: `` + - `` + - `` + - ` ` + - ` somevalue` + - ` ` + - ` ` + - ` ` + - ` ` + - ``, - wantPP: []Proppatch{{ - Props: []Property{{ - xml.Name{Space: "http://ns.example.com/z/", Local: "Authors"}, - "", - []byte(`somevalue`), - }}, - }, { - Remove: true, - Props: []Property{{ - xml.Name{Space: "http://ns.example.com/z/", Local: "Copyright-Owner"}, - "", - nil, - }}, - }}, - }, { - desc: "proppatch: lang attribute on prop", - input: `` + - `` + - `` + - ` ` + - ` ` + - ` ` + - ` ` + - ` ` + - ``, - wantPP: []Proppatch{{ - Props: []Property{{ - xml.Name{Space: "http://example.com/ns", Local: "foo"}, - "en", - nil, - }}, - }}, - }, { - desc: "bad: remove with value", - input: `` + - `` + - `` + - ` ` + - ` ` + - ` ` + - ` Jim Whitehead` + - ` ` + - ` ` + - ` ` + - ``, - wantStatus: http.StatusBadRequest, - }, { - desc: "bad: empty propertyupdate", - input: `` + - `` + - ``, - wantStatus: http.StatusBadRequest, - }, { - desc: "bad: empty prop", - input: `` + - `` + - `` + - ` ` + - ` ` + - ` ` + - ``, - wantStatus: http.StatusBadRequest, - }} - - for _, tc := range testCases { - pp, status, err := readProppatch(strings.NewReader(tc.input)) - if tc.wantStatus != 0 { - if err == nil { - t.Errorf("%s: got nil error, want non-nil", tc.desc) - continue - } - } else if err != nil { - t.Errorf("%s: %v", tc.desc, err) - continue - } - if status != tc.wantStatus { - t.Errorf("%s: got status %d, want %d", tc.desc, status, tc.wantStatus) - continue - } - if !reflect.DeepEqual(pp, tc.wantPP) || status != tc.wantStatus { - t.Errorf("%s: proppatch\ngot %v\nwant %v", tc.desc, ppStr(pp), ppStr(tc.wantPP)) - } - } -} - -func TestUnmarshalXMLValue(t *testing.T) { - testCases := []struct { - desc string - input string - wantVal string - }{{ - desc: "simple char data", - input: "foo", - wantVal: "foo", - }, { - desc: "empty element", - input: "", - wantVal: "", - }, { - desc: "preserve namespace", - input: ``, - wantVal: ``, - }, { - desc: "preserve root element namespace", - input: ``, - wantVal: ``, - }, { - desc: "preserve whitespace", - input: " \t ", - wantVal: " \t ", - }, { - desc: "preserve mixed content", - input: ` a `, - wantVal: ` a `, - }, { - desc: "section 9.2", - input: `` + - `` + - ` Jim Whitehead` + - ` Roy Fielding` + - ``, - wantVal: `` + - ` Jim Whitehead` + - ` Roy Fielding`, - }, { - desc: "section 4.3.1 (mixed content)", - input: `` + - `` + - ` Jane Doe` + - ` ` + - ` mailto:jane.doe@example.com` + - ` http://www.example.com` + - ` ` + - ` Jane has been working way too long on the` + - ` long-awaited revision of ]]>.` + - ` ` + - ``, - wantVal: `` + - ` Jane Doe` + - ` ` + - ` mailto:jane.doe@example.com` + - ` http://www.example.com` + - ` ` + - ` Jane has been working way too long on the` + - ` long-awaited revision of <RFC2518>.` + - ` `, - }} - - var n xmlNormalizer - for _, tc := range testCases { - d := ixml.NewDecoder(strings.NewReader(tc.input)) - var v xmlValue - if err := d.Decode(&v); err != nil { - t.Errorf("%s: got error %v, want nil", tc.desc, err) - continue - } - eq, err := n.equalXML(bytes.NewReader(v), strings.NewReader(tc.wantVal)) - if err != nil { - t.Errorf("%s: equalXML: %v", tc.desc, err) - continue - } - if !eq { - t.Errorf("%s:\ngot %s\nwant %s", tc.desc, string(v), tc.wantVal) - } - } -} - -// xmlNormalizer normalizes XML. -type xmlNormalizer struct { - // omitWhitespace instructs to ignore whitespace between element tags. - omitWhitespace bool - // omitComments instructs to ignore XML comments. - omitComments bool -} - -// normalize writes the normalized XML content of r to w. It applies the -// following rules -// -// * Rename namespace prefixes according to an internal heuristic. -// * Remove unnecessary namespace declarations. -// * Sort attributes in XML start elements in lexical order of their -// fully qualified name. -// * Remove XML directives and processing instructions. -// * Remove CDATA between XML tags that only contains whitespace, if -// instructed to do so. -// * Remove comments, if instructed to do so. -// -func (n *xmlNormalizer) normalize(w io.Writer, r io.Reader) error { - d := ixml.NewDecoder(r) - e := ixml.NewEncoder(w) - for { - t, err := d.Token() - if err != nil { - if t == nil && err == io.EOF { - break - } - return err - } - switch val := t.(type) { - case ixml.Directive, ixml.ProcInst: - continue - case ixml.Comment: - if n.omitComments { - continue - } - case ixml.CharData: - if n.omitWhitespace && len(bytes.TrimSpace(val)) == 0 { - continue - } - case ixml.StartElement: - start, _ := ixml.CopyToken(val).(ixml.StartElement) - attr := start.Attr[:0] - for _, a := range start.Attr { - if a.Name.Space == "xmlns" || a.Name.Local == "xmlns" { - continue - } - attr = append(attr, a) - } - sort.Sort(byName(attr)) - start.Attr = attr - t = start - } - err = e.EncodeToken(t) - if err != nil { - return err - } - } - return e.Flush() -} - -// equalXML tests for equality of the normalized XML contents of a and b. -func (n *xmlNormalizer) equalXML(a, b io.Reader) (bool, error) { - var buf bytes.Buffer - if err := n.normalize(&buf, a); err != nil { - return false, err - } - normA := buf.String() - buf.Reset() - if err := n.normalize(&buf, b); err != nil { - return false, err - } - normB := buf.String() - return normA == normB, nil -} - -type byName []ixml.Attr - -func (a byName) Len() int { return len(a) } -func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byName) Less(i, j int) bool { - if a[i].Name.Space != a[j].Name.Space { - return a[i].Name.Space < a[j].Name.Space - } - return a[i].Name.Local < a[j].Name.Local -} diff --git a/routers/controllers/webdav.go b/routers/controllers/webdav.go index cc8068a..1f2c785 100644 --- a/routers/controllers/webdav.go +++ b/routers/controllers/webdav.go @@ -13,7 +13,6 @@ var handler *webdav.Handler func init() { handler = &webdav.Handler{ Prefix: "/dav/", - FileSystem: webdav.AdapterFS(""), LockSystem: make(map[uint]webdav.LockSystem), } } diff --git a/routers/router.go b/routers/router.go index 5e6908d..4d364bd 100644 --- a/routers/router.go +++ b/routers/router.go @@ -25,6 +25,7 @@ func initWebDAV(group *gin.RouterGroup) { group.Handle("UNLOCK", ":uid/*path", controllers.ServeWebDAV) group.Handle("PROPPATCH", ":uid/*path", controllers.ServeWebDAV) group.Handle("COPY", ":uid/*path", controllers.ServeWebDAV) + group.Handle("MOVE", ":uid/*path", controllers.ServeWebDAV) } }