Parcourir la source

Serve all storages under one WebDAV root

WebDAV now exposes a single endpoint at /webdav/ whose root is a read-only virtual listing with one folder per storage, named by its UUID. This mirrors the FTP server. Paths below a storage folder go to that storage's adapter, so the old /webdav/{vroot_name} URLs still work.

Add RootFsWebDAVAdapter. It blocks create, delete and rename at the root level, and supports moves between storages by copying then removing the source. Lock systems are now shared per user instead of per user and root. The bare /webdav path is served as the root instead of returning 404. WebDavGetEndpoints returns one endpoint, and the setup instructions are updated. Add tests for the root adapter, endpoints and root handling.
Toby Chui il y a 4 semaines
Parent
commit
eeeac039ed

+ 5 - 6
src/mod/fileservers/servers/webdavserv/webdavserv.go

@@ -84,19 +84,18 @@ func (m *Manager) WebDavToogle(enabled bool) error {
 }
 
 func (m *Manager) WebDavGetEndpoints(userinfo *user.User) []*fileservers.Endpoint {
-	eps := []*fileservers.Endpoint{}
 	protocolName := "http://"
 	if m.option.UseTls {
 		protocolName = "https://"
 	}
-	for _, fsh := range userinfo.GetAllAccessibleFileSystemHandler() {
-		eps = append(eps, &fileservers.Endpoint{
+	//One endpoint for every storage, which shows up as a folder in its root
+	return []*fileservers.Endpoint{
+		{
 			ProtocolName: protocolName,
 			Port:         m.option.Port,
-			Subpath:      "/webdav/" + fsh.UUID,
-		})
+			Subpath:      "/webdav/",
+		},
 	}
-	return eps
 }
 
 func (m *Manager) GetWebDavEnabled() bool {

+ 25 - 0
src/mod/fileservers/servers/webdavserv/webdavserv_test.go

@@ -0,0 +1,25 @@
+package webdavserv
+
+import "testing"
+
+// Every storage is a folder under one virtual root, so only the root
+// endpoint is listed.
+func TestWebDavGetEndpoints(t *testing.T) {
+	tests := []struct {
+		useTls       bool
+		wantProtocol string
+	}{
+		{false, "http://"},
+		{true, "https://"},
+	}
+	for _, tt := range tests {
+		m := &Manager{option: &ManagerOption{Port: 8080, UseTls: tt.useTls}}
+		eps := m.WebDavGetEndpoints(nil)
+		if len(eps) != 1 {
+			t.Fatalf("UseTls=%v: expected 1 endpoint, got %d", tt.useTls, len(eps))
+		}
+		if eps[0].ProtocolName != tt.wantProtocol || eps[0].Port != 8080 || eps[0].Subpath != "/webdav/" {
+			t.Errorf("UseTls=%v: got %+v, want %s port 8080 at /webdav/", tt.useTls, eps[0], tt.wantProtocol)
+		}
+	}
+}

+ 1 - 1
src/mod/fileservers/typedef.go

@@ -9,7 +9,7 @@ import user "imuslab.com/arozos/mod/user"
 type Endpoint struct {
 	ProtocolName string //Protocol name of the endpoint, e.g. ftp
 	Port         int    //Port for the endpoint, e.g. 21
-	Subpath      string //Subpath of the endpoint, e.g. /webdav/user
+	Subpath      string //Subpath of the endpoint, e.g. /fileview
 }
 
 type Server struct {

+ 254 - 0
src/mod/storage/webdav/rootfs.go

@@ -0,0 +1,254 @@
+package webdav
+
+/*
+	WebDAV virtual root
+
+	Serves every storage a user can reach under one WebDAV endpoint, the
+	same way the FTP server does: the root is a read-only in-memory listing
+	with one folder per storage (named by its UUID), and every path below
+	such a folder is handed to that storage's FshWebDAVAdapter. So
+	/webdav/user/Video maps to user:/Video, which also keeps the old
+	per-root URLs (/webdav/{vroot_name}) working.
+*/
+
+import (
+	"context"
+	"os"
+	"path"
+	"strings"
+
+	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/network/webdav"
+)
+
+type RootFsWebDAVAdapter struct {
+	fshs     []*filesystem.FileSystemHandler
+	adapters map[string]*FshWebDAVAdapter
+}
+
+// NewRootFsWebDAVAdapter builds the virtual root over the given storages.
+// It is built per request, so newly mounted or closed storages show up
+// immediately.
+func NewRootFsWebDAVAdapter(fshs []*filesystem.FileSystemHandler, username string) *RootFsWebDAVAdapter {
+	adapters := map[string]*FshWebDAVAdapter{}
+	for _, fsh := range fshs {
+		adapters[fsh.UUID] = NewFshWebDAVAdapter(fsh, username)
+	}
+	return &RootFsWebDAVAdapter{
+		fshs:     fshs,
+		adapters: adapters,
+	}
+}
+
+// splitRootPath cleans a request path and splits it into the storage UUID
+// and the path inside that storage. An empty UUID means the root itself.
+func splitRootPath(name string) (string, string) {
+	name = path.Clean("/" + name)
+	if name == "/" {
+		return "", "/"
+	}
+	parts := strings.SplitN(name[1:], "/", 2)
+	if len(parts) == 1 {
+		return parts[0], "/"
+	}
+	return parts[0], "/" + parts[1]
+}
+
+// isRootLevel reports whether name is the root or an entry directly inside
+// it. Those entries are the storages themselves and cannot be changed.
+func isRootLevel(name string) bool {
+	_, subpath := splitRootPath(name)
+	return subpath == "/"
+}
+
+// resolve returns the adapter of the storage that holds name and the path
+// inside it. adapter is nil (with a nil error) for the root itself.
+func (a *RootFsWebDAVAdapter) resolve(name string) (*FshWebDAVAdapter, string, error) {
+	uuid, subpath := splitRootPath(name)
+	if uuid == "" {
+		return nil, "/", nil
+	}
+	adapter, ok := a.adapters[uuid]
+	if !ok {
+		return nil, "", os.ErrNotExist
+	}
+	return adapter, subpath, nil
+}
+
+// rootFs builds the root listing as an in-memory file system holding one
+// folder per storage.
+func (a *RootFsWebDAVAdapter) rootFs(ctx context.Context) webdav.FileSystem {
+	memfs := webdav.NewMemFS()
+	for _, fsh := range a.fshs {
+		memfs.Mkdir(ctx, "/"+fsh.UUID, 0555)
+	}
+	return memfs
+}
+
+// VirtualPath maps a request path to an arozos virtual path (e.g. user:/Video)
+// and its storage. It fails for the root, which has no virtual path.
+func (a *RootFsWebDAVAdapter) VirtualPath(name string) (*filesystem.FileSystemHandler, string, error) {
+	adapter, subpath, err := a.resolve(name)
+	if err != nil {
+		return nil, "", err
+	}
+	if adapter == nil {
+		return nil, "", os.ErrInvalid
+	}
+	return adapter.fsh, adapter.fsh.UUID + ":" + subpath, nil
+}
+
+func (a *RootFsWebDAVAdapter) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
+	if isRootLevel(name) {
+		return os.ErrPermission
+	}
+	adapter, subpath, err := a.resolve(name)
+	if err != nil {
+		return err
+	}
+	return adapter.Mkdir(ctx, subpath, perm)
+}
+
+func (a *RootFsWebDAVAdapter) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
+	if isRootLevel(name) && flag&(os.O_WRONLY|os.O_RDWR|os.O_CREATE|os.O_TRUNC|os.O_APPEND) != 0 {
+		return nil, os.ErrPermission
+	}
+	adapter, subpath, err := a.resolve(name)
+	if err != nil {
+		return nil, err
+	}
+	if adapter == nil {
+		return a.rootFs(ctx).OpenFile(ctx, "/", os.O_RDONLY, 0)
+	}
+
+	f, err := adapter.OpenFile(ctx, subpath, flag, perm)
+	if err != nil || subpath != "/" {
+		return f, err
+	}
+	return renamedFile{f, adapter.fsh.UUID}, nil
+}
+
+func (a *RootFsWebDAVAdapter) RemoveAll(ctx context.Context, name string) error {
+	if isRootLevel(name) {
+		return os.ErrPermission
+	}
+	adapter, subpath, err := a.resolve(name)
+	if err != nil {
+		return err
+	}
+	return adapter.RemoveAll(ctx, subpath)
+}
+
+func (a *RootFsWebDAVAdapter) Rename(ctx context.Context, oldName, newName string) error {
+	if isRootLevel(oldName) || isRootLevel(newName) {
+		return os.ErrPermission
+	}
+	srcAdapter, srcPath, err := a.resolve(oldName)
+	if err != nil {
+		return err
+	}
+	destAdapter, destPath, err := a.resolve(newName)
+	if err != nil {
+		return err
+	}
+
+	if srcAdapter == destAdapter {
+		//Renaming in same fsh
+		return srcAdapter.Rename(ctx, srcPath, destPath)
+	}
+
+	//Cross fsh move. Copy everything over, then remove the source
+	realSrc, err := srcAdapter.requestPathToRealPath(srcPath)
+	if err != nil {
+		return err
+	}
+	realDest, err := destAdapter.requestPathToRealPath(destPath)
+	if err != nil {
+		return err
+	}
+	srcFsa := srcAdapter.fsh.FileSystemAbstraction
+	err = copyAcrossFsh(srcFsa, realSrc, destAdapter.fsh.FileSystemAbstraction, realDest)
+	if err != nil {
+		return err
+	}
+	return srcFsa.RemoveAll(realSrc)
+}
+
+func (a *RootFsWebDAVAdapter) Stat(ctx context.Context, name string) (os.FileInfo, error) {
+	adapter, subpath, err := a.resolve(name)
+	if err != nil {
+		return nil, err
+	}
+	if adapter == nil {
+		return a.rootFs(ctx).Stat(ctx, "/")
+	}
+
+	s, err := adapter.Stat(ctx, subpath)
+	if err != nil {
+		return nil, err
+	}
+	if subpath == "/" {
+		//Show the storage folder under its UUID instead of the name of its
+		//folder on disk
+		return renamedFileInfo{s, adapter.fsh.UUID}, nil
+	}
+	return s, nil
+}
+
+// copyAcrossFsh copies a file or folder tree from one storage to another.
+func copyAcrossFsh(srcFsa filesystem.FileSystemAbstraction, src string, destFsa filesystem.FileSystemAbstraction, dest string) error {
+	s, err := srcFsa.Stat(src)
+	if err != nil {
+		return err
+	}
+
+	if !s.IsDir() {
+		f, err := srcFsa.ReadStream(src)
+		if err != nil {
+			return err
+		}
+		defer f.Close()
+		return destFsa.WriteStream(dest, f, 0775)
+	}
+
+	err = destFsa.MkdirAll(dest, 0775)
+	if err != nil {
+		return err
+	}
+	entries, err := srcFsa.ReadDir(src)
+	if err != nil {
+		return err
+	}
+	for _, entry := range entries {
+		err = copyAcrossFsh(srcFsa, path.Join(src, entry.Name()), destFsa, path.Join(dest, entry.Name()))
+		if err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// renamedFileInfo reports a different name for an existing FileInfo.
+type renamedFileInfo struct {
+	os.FileInfo
+	name string
+}
+
+func (r renamedFileInfo) Name() string {
+	return r.name
+}
+
+// renamedFile is the root folder of a storage opened through the virtual
+// root, which reports the storage UUID as its name like Stat does.
+type renamedFile struct {
+	webdav.File
+	name string
+}
+
+func (r renamedFile) Stat() (os.FileInfo, error) {
+	s, err := r.File.Stat()
+	if err != nil {
+		return nil, err
+	}
+	return renamedFileInfo{s, r.name}, nil
+}

+ 214 - 0
src/mod/storage/webdav/rootfs_test.go

@@ -0,0 +1,214 @@
+package webdav
+
+import (
+	"context"
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"imuslab.com/arozos/mod/filesystem"
+	"imuslab.com/arozos/mod/filesystem/abstractions/localfs"
+)
+
+// newLocalTestFsh builds a public local storage named uuid over a temp dir.
+func newLocalTestFsh(t *testing.T, uuid string) (*filesystem.FileSystemHandler, string) {
+	t.Helper()
+	dir := t.TempDir()
+	return &filesystem.FileSystemHandler{
+		Name:                  uuid,
+		UUID:                  uuid,
+		Hierarchy:             "public",
+		FileSystemAbstraction: localfs.NewLocalFileSystemAbstraction(uuid, dir, "public", false),
+	}, dir
+}
+
+// newRootFsTestHandler serves two local storages, "user" and "tmp", under
+// the virtual root of /webdav.
+func newRootFsTestHandler(t *testing.T) (http.Handler, string, string) {
+	t.Helper()
+	userFsh, userDir := newLocalTestFsh(t, "user")
+	tmpFsh, tmpDir := newLocalTestFsh(t, "tmp")
+	s := newTestServer()
+	h := s.getRootFs([]*filesystem.FileSystemHandler{userFsh, tmpFsh}, "alice")
+	return h, userDir, tmpDir
+}
+
+func serveTestRequest(h http.Handler, method, target, body string, headers map[string]string) *httptest.ResponseRecorder {
+	req := httptest.NewRequest(method, target, strings.NewReader(body))
+	for k, v := range headers {
+		req.Header.Set(k, v)
+	}
+	w := httptest.NewRecorder()
+	h.ServeHTTP(w, req)
+	return w
+}
+
+func TestSplitRootPath(t *testing.T) {
+	tests := []struct {
+		name        string
+		wantUUID    string
+		wantSubpath string
+	}{
+		{"/", "", "/"},
+		{"", "", "/"},
+		{"/user", "user", "/"},
+		{"/user/", "user", "/"},
+		{"/user/Video/a.mp4", "user", "/Video/a.mp4"},
+		{"user/Video", "user", "/Video"},
+		{"/user/../tmp/a", "tmp", "/a"},
+		{"/../../etc", "etc", "/"},
+	}
+	for _, tt := range tests {
+		uuid, subpath := splitRootPath(tt.name)
+		if uuid != tt.wantUUID || subpath != tt.wantSubpath {
+			t.Errorf("splitRootPath(%q) = (%q, %q), want (%q, %q)", tt.name, uuid, subpath, tt.wantUUID, tt.wantSubpath)
+		}
+	}
+}
+
+func TestRootFs_ListsEveryStorage(t *testing.T) {
+	h, _, _ := newRootFsTestHandler(t)
+	w := serveTestRequest(h, "PROPFIND", "/webdav/", "", map[string]string{"Depth": "1"})
+	if w.Code != http.StatusMultiStatus {
+		t.Fatalf("PROPFIND root: expected 207, got %d", w.Code)
+	}
+	body := w.Body.String()
+	for _, href := range []string{"/webdav/", "/webdav/user/", "/webdav/tmp/"} {
+		if !strings.Contains(body, "<D:href>"+href+"</D:href>") {
+			t.Errorf("root listing is missing %s:\n%s", href, body)
+		}
+	}
+	if !strings.Contains(body, "<D:displayname>user</D:displayname>") {
+		t.Errorf("expected the storage folder to be named by its UUID:\n%s", body)
+	}
+}
+
+func TestRootFs_StatStorageUsesUUID(t *testing.T) {
+	userFsh, _ := newLocalTestFsh(t, "user")
+	rootfs := NewRootFsWebDAVAdapter([]*filesystem.FileSystemHandler{userFsh}, "alice")
+	s, err := rootfs.Stat(context.Background(), "/user")
+	if err != nil {
+		t.Fatalf("Stat /user: %v", err)
+	}
+	if s.Name() != "user" || !s.IsDir() {
+		t.Errorf("Stat /user = (%q, dir %v), want (\"user\", dir true)", s.Name(), s.IsDir())
+	}
+	if _, err := rootfs.Stat(context.Background(), "/missing"); !os.IsNotExist(err) {
+		t.Errorf("Stat /missing: expected not exist, got %v", err)
+	}
+}
+
+func TestRootFs_ReadWriteInsideStorage(t *testing.T) {
+	h, userDir, _ := newRootFsTestHandler(t)
+
+	w := serveTestRequest(h, http.MethodPut, "/webdav/user/a.txt", "hello", nil)
+	if w.Code != http.StatusCreated {
+		t.Fatalf("PUT: expected 201, got %d", w.Code)
+	}
+	got, err := os.ReadFile(filepath.Join(userDir, "a.txt"))
+	if err != nil || string(got) != "hello" {
+		t.Fatalf("uploaded file = %q, %v; want \"hello\"", got, err)
+	}
+
+	w = serveTestRequest(h, http.MethodGet, "/webdav/user/a.txt", "", nil)
+	if w.Code != http.StatusOK || w.Body.String() != "hello" {
+		t.Errorf("GET: got %d %q, want 200 \"hello\"", w.Code, w.Body.String())
+	}
+
+	w = serveTestRequest(h, "MKCOL", "/webdav/user/folder", "", nil)
+	if w.Code != http.StatusCreated {
+		t.Errorf("MKCOL in storage: expected 201, got %d", w.Code)
+	}
+}
+
+func TestRootFs_RootIsReadOnly(t *testing.T) {
+	h, userDir, _ := newRootFsTestHandler(t)
+	tests := []struct {
+		method  string
+		target  string
+		headers map[string]string
+	}{
+		{http.MethodPut, "/webdav/a.txt", nil},
+		{"MKCOL", "/webdav/newfolder", nil},
+		{http.MethodDelete, "/webdav/user", nil},
+		{"MOVE", "/webdav/user", map[string]string{"Destination": "/webdav/renamed"}},
+		{"COPY", "/webdav/user", map[string]string{"Destination": "/webdav/copied"}},
+	}
+	for _, tt := range tests {
+		w := serveTestRequest(h, tt.method, tt.target, "", tt.headers)
+		if w.Code < 400 {
+			t.Errorf("%s %s: expected an error status, got %d", tt.method, tt.target, w.Code)
+		}
+	}
+	if _, err := os.Stat(userDir); err != nil {
+		t.Errorf("storage folder should be untouched: %v", err)
+	}
+}
+
+func TestRootFs_UnknownStorage(t *testing.T) {
+	h, _, _ := newRootFsTestHandler(t)
+	w := serveTestRequest(h, http.MethodGet, "/webdav/missing/a.txt", "", nil)
+	if w.Code != http.StatusNotFound {
+		t.Errorf("GET on unknown storage: expected 404, got %d", w.Code)
+	}
+}
+
+func TestRootFs_MoveAcrossStorages(t *testing.T) {
+	h, userDir, tmpDir := newRootFsTestHandler(t)
+	os.WriteFile(filepath.Join(userDir, "a.txt"), []byte("file"), 0644)
+	os.MkdirAll(filepath.Join(userDir, "dir", "sub"), 0755)
+	os.WriteFile(filepath.Join(userDir, "dir", "sub", "b.txt"), []byte("nested"), 0644)
+
+	tests := []struct {
+		src, dest string
+		check     string
+		want      string
+	}{
+		{"/webdav/user/a.txt", "/webdav/tmp/a.txt", filepath.Join(tmpDir, "a.txt"), "file"},
+		{"/webdav/user/dir", "/webdav/tmp/dir", filepath.Join(tmpDir, "dir", "sub", "b.txt"), "nested"},
+	}
+	for _, tt := range tests {
+		w := serveTestRequest(h, "MOVE", tt.src, "", map[string]string{"Destination": tt.dest})
+		if w.Code != http.StatusCreated {
+			t.Errorf("MOVE %s: expected 201, got %d", tt.src, w.Code)
+			continue
+		}
+		got, err := os.ReadFile(tt.check)
+		if err != nil || string(got) != tt.want {
+			t.Errorf("MOVE %s: moved content = %q, %v; want %q", tt.src, got, err, tt.want)
+		}
+	}
+	for _, gone := range []string{"a.txt", "dir"} {
+		if _, err := os.Stat(filepath.Join(userDir, gone)); !os.IsNotExist(err) {
+			t.Errorf("source %s should be removed after the move, got %v", gone, err)
+		}
+	}
+}
+
+func TestRootFs_VirtualPath(t *testing.T) {
+	userFsh, _ := newLocalTestFsh(t, "user")
+	rootfs := NewRootFsWebDAVAdapter([]*filesystem.FileSystemHandler{userFsh}, "alice")
+	tests := []struct {
+		name    string
+		want    string
+		wantErr bool
+	}{
+		{"/", "", true},
+		{"/user", "user:/", false},
+		{"/user/Video", "user:/Video", false},
+		{"/missing/Video", "", true},
+	}
+	for _, tt := range tests {
+		fsh, vpath, err := rootfs.VirtualPath(tt.name)
+		if (err != nil) != tt.wantErr {
+			t.Errorf("VirtualPath(%q) error = %v, wantErr %v", tt.name, err, tt.wantErr)
+			continue
+		}
+		if !tt.wantErr && (vpath != tt.want || fsh != userFsh) {
+			t.Errorf("VirtualPath(%q) = %q, want %q", tt.name, vpath, tt.want)
+		}
+	}
+}

+ 26 - 53
src/mod/storage/webdav/webdav.go

@@ -10,12 +10,10 @@ package webdav
 */
 import (
 	"encoding/json"
-	"fmt"
 	"net/http"
 	"os"
 	"path/filepath"
 	"sort"
-	"strings"
 	"sync"
 	"time"
 
@@ -32,7 +30,7 @@ import (
 type Server struct {
 	hostname    string            //The hostname of this devices
 	userHandler *user.UserHandler //The central userHandler
-	filesystems sync.Map          //Lock system per user and root, shared across requests
+	filesystems sync.Map          //Lock system per user, shared across requests
 	prefix      string            //The prefix to strip away from filepath
 	tlsMode     bool              //Bypass tls windows mode if enabled
 	Enabled     bool              //If the server is enabled. Set this to false for disable this service
@@ -202,29 +200,16 @@ func (s *Server) HandleRequest(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	if r.URL.Path == "/webdav" {
-		//No vRoot defined. Reject connection
-		http.NotFound(w, r)
-		return
-	}
-
-	reqInfo := strings.Split(r.URL.RequestURI()[1:], "/")
-	reqRoot := "user"
-	if len(reqInfo) > 1 {
-		reqRoot = reqInfo[1]
-	}
-
-	if strings.TrimSpace(reqRoot) == "" {
-		//No vroot defined.
-		http.NotFound(w, r)
-		return
+	if r.URL.Path == s.prefix {
+		//The virtual root, served the same as its trailing slash form
+		r.URL.Path = s.prefix + "/"
 	}
 
 	//Windows File Explorer. Handle with special case
 	/*
 		if r.Header["User-Agent"] != nil && strings.Contains(r.Header["User-Agent"][0], "Microsoft-WebDAV-MiniRedir") && r.TLS == nil {
 			logger.PrintAndLog("Webdav", "Windows File Explorer Connection. Routing using alternative handler", nil)
-			s.HandleWindowClientAccess(w, r, reqRoot)
+			s.HandleWindowClientAccess(w, r)
 			return
 		}
 	*/
@@ -283,25 +268,8 @@ func (s *Server) HandleRequest(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(reqRoot + ":/")
-	if err != nil {
-		logger.PrintAndLog("Webdav", fmt.Sprint("[WebDAV] Failed to load File System Handler from request root: ", reqRoot+":/", err.Error()), nil)
-		http.Error(w, "Invalid ", http.StatusInternalServerError)
-		return
-	}
-
-	//Try to resolve the realpath of the vroot
-	/*
-		realRoot, err := userinfo.VirtualPathToRealPath(reqRoot + ":/")
-		if err != nil {
-			logger.PrintAndLog("Webdav", err.Error(), nil)
-			http.Error(w, "Invalid ", http.StatusUnauthorized)
-			return
-		}
-	*/
-
-	//Ok. Check if the file server of this root already exists
-	fs := s.getFsFromRealRoot(fsh, userinfo.Username, filepath.ToSlash(filepath.Join(s.prefix, reqRoot)))
+	//Serve all storages of the user under one virtual root, like the FTP server
+	fs := s.getRootFs(userinfo.GetAllFileSystemHandler(), userinfo.Username)
 
 	//Serve the content
 	fs.ServeHTTP(w, r)
@@ -344,29 +312,34 @@ func (s *Server) serveReadOnlyWebDav(w http.ResponseWriter, r *http.Request) {
 	}
 }
 
-// getLockSystem returns the lock system shared by every request of a user on
-// one root. The handler is rebuilt per request, but locks must outlive it:
-// macOS Finder LOCKs a file and then PUTs the content with the lock token in
-// an If header, which fails with 412 against a fresh lock system and leaves
-// a 0 byte file behind.
-func (s *Server) getLockSystem(username string, prefix string) webdav.LockSystem {
-	ls, _ := s.filesystems.LoadOrStore(username+"\x00"+prefix, webdav.NewMemLS())
+// getLockSystem returns the lock system shared by every request of a user.
+// The handler is rebuilt per request, but locks must outlive it: macOS
+// Finder LOCKs a file and then PUTs the content with the lock token in an If
+// header, which fails with 412 against a fresh lock system and leaves a 0
+// byte file behind.
+func (s *Server) getLockSystem(username string) webdav.LockSystem {
+	ls, _ := s.filesystems.LoadOrStore(username, webdav.NewMemLS())
 	return ls.(webdav.LockSystem)
 }
 
-func (s *Server) getFsFromRealRoot(fsh *filesystem.FileSystemHandler, username string, prefix string) *webdav.Handler {
-	//Create a webdav adapter from the fsh
-	fshadapter := NewFshWebDAVAdapter(fsh, username)
+// getRootFs builds the WebDAV handler of a user, with the virtual root
+// listing every given storage (see RootFsWebDAVAdapter).
+func (s *Server) getRootFs(fshs []*filesystem.FileSystemHandler, username string) *webdav.Handler {
+	rootfs := NewRootFsWebDAVAdapter(fshs, username)
 	fs := &webdav.Handler{
-		Prefix:     prefix,
-		FileSystem: fshadapter,
-		LockSystem: s.getLockSystem(username, prefix),
+		Prefix:     s.prefix,
+		FileSystem: rootfs,
+		LockSystem: s.getLockSystem(username),
 	}
 
 	//Create event listener for the path request
 	fs.RequestEventListener = func(path string) {
 		//Generate thumbnail in the background if listed
-		vpath, _ := fsh.FileSystemAbstraction.RealPathToVirtualPath(path, username)
+		fsh, vpath, err := rootfs.VirtualPath(path)
+		if err != nil {
+			//The virtual root has no thumbnails to build
+			return
+		}
 		go func() {
 			isHidden, _ := hidden.IsHidden(vpath, false)
 			if !isHidden {

+ 2 - 10
src/mod/storage/webdav/webdavWindowHandler.go

@@ -11,7 +11,6 @@ import (
 	"fmt"
 	"net"
 	"net/http"
-	"path/filepath"
 	"strings"
 	"time"
 
@@ -20,7 +19,7 @@ import (
 )
 
 // Handle request from Windows File Explorer
-func (s *Server) HandleWindowClientAccess(w http.ResponseWriter, r *http.Request, vroot string) {
+func (s *Server) HandleWindowClientAccess(w http.ResponseWriter, r *http.Request) {
 	coookieName := "arozosWebdavToken"
 	cookie, err := r.Cookie(coookieName)
 	if err != nil {
@@ -121,15 +120,8 @@ func (s *Server) HandleWindowClientAccess(w http.ResponseWriter, r *http.Request
 				return
 			}
 
-			fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vroot + ":/")
-			if err != nil {
-				logger.PrintAndLog("Webdav", fmt.Sprint("[WebDAV] Failed to load File System Handler from request root: ", err.Error()), nil)
-				http.Error(w, "Invalid ", http.StatusUnauthorized)
-				return
-			}
-
 			//Get and serve the file content
-			fs := s.getFsFromRealRoot(fsh, userinfo.Username, filepath.ToSlash(filepath.Join(s.prefix, vroot)))
+			fs := s.getRootFs(userinfo.GetAllFileSystemHandler(), userinfo.Username)
 			fs.ServeHTTP(w, r)
 		}
 	}

+ 42 - 33
src/mod/storage/webdav/webdav_test.go

@@ -12,6 +12,7 @@ import (
 
 	"imuslab.com/arozos/mod/auth"
 	db "imuslab.com/arozos/mod/database"
+	"imuslab.com/arozos/mod/filesystem"
 	"imuslab.com/arozos/mod/network/webdav"
 	"imuslab.com/arozos/mod/permission"
 	"imuslab.com/arozos/mod/share/shareEntry"
@@ -133,15 +134,22 @@ func TestHandleRequest_Disabled(t *testing.T) {
 	}
 }
 
+// The bare endpoint is the virtual root now, so it asks for credentials
+// instead of being rejected.
 func TestHandleRequest_RootPath(t *testing.T) {
-	s := newTestServer()
+	for _, p := range []string{"/webdav", "/webdav/", "/webdav//"} {
+		s := newTestServer()
 
-	req := httptest.NewRequest(http.MethodGet, "/webdav", nil)
-	w := httptest.NewRecorder()
-	s.HandleRequest(w, req)
+		req := httptest.NewRequest("PROPFIND", p, nil)
+		w := httptest.NewRecorder()
+		s.HandleRequest(w, req)
 
-	if w.Code != http.StatusNotFound {
-		t.Errorf("root-only path: expected 404, got %d", w.Code)
+		if w.Code != http.StatusUnauthorized {
+			t.Errorf("%s: expected 401, got %d", p, w.Code)
+		}
+		if w.Header().Get("WWW-Authenticate") == "" {
+			t.Errorf("%s: expected WWW-Authenticate header to be set", p)
+		}
 	}
 }
 
@@ -433,19 +441,6 @@ func TestHandleRequest_NoBasicAuth(t *testing.T) {
 	}
 }
 
-func TestHandleRequest_EmptyVroot(t *testing.T) {
-	s := newTestServer()
-
-	// Path like /webdav// has empty segment after stripping
-	req := httptest.NewRequest(http.MethodGet, "/webdav//", nil)
-	w := httptest.NewRecorder()
-	s.HandleRequest(w, req)
-
-	if w.Code != http.StatusNotFound {
-		t.Errorf("expected 404 for empty vroot, got %d", w.Code)
-	}
-}
-
 // --- auto-login access token authentication (X-Access-Token / X-Aroz-User) ---
 
 func TestAutoLoginTokenMatchesUsername(t *testing.T) {
@@ -599,31 +594,24 @@ func TestHandleConnectionList_Empty(t *testing.T) {
 	}
 }
 
-func TestGetLockSystem_SharedPerUserAndRoot(t *testing.T) {
+func TestGetLockSystem_SharedPerUser(t *testing.T) {
 	s := newTestServer()
-	a := s.getLockSystem("alice", "/webdav/user")
-	if a != s.getLockSystem("alice", "/webdav/user") {
-		t.Error("expected the same lock system for the same user and root")
+	a := s.getLockSystem("alice")
+	if a != s.getLockSystem("alice") {
+		t.Error("expected the same lock system for the same user")
 	}
-	if a == s.getLockSystem("bob", "/webdav/user") {
+	if a == s.getLockSystem("bob") {
 		t.Error("expected different users to get different lock systems")
 	}
-	if a == s.getLockSystem("alice", "/webdav/tmp") {
-		t.Error("expected different roots to get different lock systems")
-	}
 }
 
 // Finder LOCKs a file, then PUTs its content with the lock token in an If
 // header, each in its own request. The PUT must succeed and write the body.
 func TestLockThenPut_AcrossRequests(t *testing.T) {
 	s := newTestServer()
-	dir := t.TempDir()
+	fsh, dir := newLocalTestFsh(t, "user")
 	newHandler := func() *webdav.Handler {
-		return &webdav.Handler{
-			Prefix:     "/webdav/user",
-			FileSystem: webdav.Dir(dir),
-			LockSystem: s.getLockSystem("alice", "/webdav/user"),
-		}
+		return s.getRootFs([]*filesystem.FileSystemHandler{fsh}, "alice")
 	}
 
 	lockBody := `<?xml version="1.0" encoding="utf-8"?><D:lockinfo xmlns:D="DAV:"><D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype><D:owner>finder</D:owner></D:lockinfo>`
@@ -654,3 +642,24 @@ func TestLockThenPut_AcrossRequests(t *testing.T) {
 		t.Errorf("uploaded file content = %q, want %q", got, content)
 	}
 }
+
+// A logged in client opening the bare endpoint gets the virtual root.
+func TestHandleRequest_BasicAuth_ServesVirtualRoot(t *testing.T) {
+	env := newAuthedTestEnv(t)
+	defer env.cleanup()
+
+	for _, p := range []string{"/webdav", "/webdav/"} {
+		req := httptest.NewRequest("PROPFIND", p, nil)
+		req.SetBasicAuth("alice", "alicepw")
+		req.Header.Set("Depth", "1")
+		w := httptest.NewRecorder()
+		env.server.HandleRequest(w, req)
+
+		if w.Code != http.StatusMultiStatus {
+			t.Errorf("PROPFIND %s: expected 207, got %d: %s", p, w.Code, w.Body.String())
+		}
+		if !strings.Contains(w.Body.String(), "<D:href>/webdav/</D:href>") {
+			t.Errorf("PROPFIND %s: expected the root listing, got %s", p, w.Body.String())
+		}
+	}
+}

+ 3 - 3
src/web/SystemAO/disk/instr/webdav.html

@@ -1,6 +1,6 @@
 <div class="ui message maconly instr" style="display:none; margin-top: 0;">
     <h4><i class="apple icon"></i> Login Method for MacOS</h4>
-    <p>If you are using MacOS, you can select "Connect to Network Server", enter the endpoint of the arozos WebDAV service (<span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/{vroot_name}) and login with your arozos username and password.</p>
+    <p>If you are using MacOS, you can select "Connect to Network Server", enter the endpoint of the arozos WebDAV service (<span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/) and login with your arozos username and password. Each of your storages shows up as a folder.</p>
 </div>
 <div class="ui blue message windowonly nontls instr" style="display:none; margin-top: 0;">
     <h4><i class="windows icon"></i> Login Method for Windows (Non SSL / TLS Mode)</h4>
@@ -9,13 +9,13 @@
     <ol class="ui list">
         <li>Use a reverse proxy server like <a href="https://zoraxy.aroz.org" target="_blank">Zoraxy <i class="ui external icon"></i></a> to proxy WebDAV traffic with TLS enabled</li>
         <li>Click "Map Network Drive" in File Explorer > This PC toolbar</li>
-        <li>Enter <span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/{vroot_name} as the target</li>
+        <li>Enter <span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/ as the target</li>
         <li>Login with your ArozOS username and password</li>
     </ol>
 </div>
 <div class="ui teal message windowonly tls instr" style="display:none">
     <h4><i class="windows icon"></i> Login Method for Windows (With SSL / TLS MODE)</h4>
-    <p>If you are using Windows File Explorer as your WebDAV Client, go to "This PC" and add a network drive with the following endpoint: <span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/{vroot_name}</p>
+    <p>If you are using Windows File Explorer as your WebDAV Client, go to "This PC" and add a network drive with the following endpoint: <span class="protocol"></span>//<span class="hostname"></span>:<span class="port"></span>/webdav/<br>Each of your storages shows up as a folder.</p>
 </div>
 <a onclick="showAllInstr(this);" style="cursor: pointer;">Show instruction for other platforms</a>
 <script>