feat: webdav handle

This commit is contained in:
Noah Hsu
2022-06-30 22:41:55 +08:00
parent dd013ac0b2
commit 2b1726614b
11 changed files with 344 additions and 3451 deletions

View File

@ -8,7 +8,12 @@ package webdav // import "golang.org/x/net/webdav"
import (
"errors"
"fmt"
"io"
"github.com/alist-org/alist/v3/internal/errs"
"github.com/alist-org/alist/v3/internal/fs"
"github.com/alist-org/alist/v3/internal/model"
"github.com/alist-org/alist/v3/internal/sign"
"github.com/alist-org/alist/v3/pkg/utils"
"github.com/alist-org/alist/v3/server/common"
"net/http"
"net/url"
"os"
@ -20,8 +25,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 LockSystem
// Logger is an optional error logger. If non-nil, it will be called
@ -41,9 +44,7 @@ func (h *Handler) stripPrefix(p string) (string, int, error) {
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
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 {
switch r.Method {
@ -76,7 +77,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(StatusText(status)))
}
}
if h.Logger != nil {
if h.Logger != nil && err != nil {
h.Logger(r, err)
}
}
@ -175,8 +176,10 @@ func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status
return status, err
}
ctx := r.Context()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
allow := "OPTIONS, LOCK, PUT, MKCOL"
if fi, err := h.FileSystem.Stat(ctx, reqPath); err == nil {
if fi, err := fs.Get(ctx, reqPath); err == nil {
if fi.IsDir() {
allow = "OPTIONS, LOCK, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND"
} else {
@ -198,25 +201,41 @@ func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (sta
}
// TODO: check locks for read-only access??
ctx := r.Context()
f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDONLY, 0)
if err != nil {
return http.StatusNotFound, err
}
defer f.Close()
fi, err := f.Stat()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
fi, err := fs.Get(ctx, reqPath)
if err != nil {
return http.StatusNotFound, err
}
if fi.IsDir() {
return http.StatusMethodNotAllowed, nil
}
etag, err := findETag(ctx, h.FileSystem, h.LockSystem, reqPath, fi)
etag, err := findETag(ctx, h.LockSystem, reqPath, fi)
if err != nil {
return http.StatusInternalServerError, err
}
w.Header().Set("ETag", etag)
// Let ServeContent determine the Content-Type header.
http.ServeContent(w, r, reqPath, fi.ModTime(), f)
account, _ := fs.GetAccount(reqPath)
if account.GetAccount().WebdavNative() {
link, _, err := fs.Link(ctx, reqPath, model.LinkArgs{Header: r.Header})
if err != nil {
return http.StatusInternalServerError, err
}
err = common.Proxy(w, r, link, fi)
if err != nil {
return http.StatusInternalServerError, err
}
} else if account.Config().MustProxy() || account.GetAccount().WebdavProxy() {
u := fmt.Sprintf("%s/p%s?sign=%s", common.GetBaseUrl(r), reqPath, sign.Sign(path.Base(reqPath)))
http.Redirect(w, r, u, 302)
} else {
link, _, err := fs.Link(ctx, reqPath, model.LinkArgs{IP: utils.ClientIP(r)})
if err != nil {
return http.StatusInternalServerError, err
}
http.Redirect(w, r, link.URL, 302)
}
return 0, nil
}
@ -232,19 +251,20 @@ func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status i
defer release()
ctx := r.Context()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
// TODO: return MultiStatus where appropriate.
// "godoc os RemoveAll" says that "If the path does not exist, RemoveAll
// returns nil (no error)." WebDAV semantics are that it should return a
// "404 Not Found". We therefore have to Stat before we RemoveAll.
if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
if os.IsNotExist(err) {
if _, err := fs.Get(ctx, reqPath); err != nil {
if errs.IsObjectNotFound(err) {
return http.StatusNotFound, err
}
return http.StatusMethodNotAllowed, err
}
if err := h.FileSystem.RemoveAll(ctx, reqPath); err != nil {
if err := fs.Remove(ctx, reqPath); err != nil {
return http.StatusMethodNotAllowed, err
}
return http.StatusNoContent, nil
@ -263,25 +283,30 @@ func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int,
// TODO(rost): Support the If-Match, If-None-Match headers? See bradfitz'
// comments in http.checkEtag.
ctx := r.Context()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
obj := model.Object{
Name: path.Base(reqPath),
Size: r.ContentLength,
Modified: time.Now(),
}
stream := model.FileStream{
Obj: obj,
ReadCloser: r.Body,
Mimetype: r.Header.Get("Content-Type"),
}
err = fs.PutDirectly(ctx, path.Dir(reqPath), stream)
f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return http.StatusNotFound, err
}
_, copyErr := io.Copy(f, r.Body)
fi, statErr := f.Stat()
closeErr := f.Close()
// TODO(rost): Returning 405 Method Not Allowed might not be appropriate.
if copyErr != nil {
return http.StatusMethodNotAllowed, copyErr
if err != nil {
return http.StatusMethodNotAllowed, err
}
if statErr != nil {
return http.StatusMethodNotAllowed, statErr
// TODO clear cache
fi, err := fs.Get(ctx, reqPath)
if err != nil {
fi = obj
}
if closeErr != nil {
return http.StatusMethodNotAllowed, closeErr
}
etag, err := findETag(ctx, h.FileSystem, h.LockSystem, reqPath, fi)
etag, err := findETag(ctx, h.LockSystem, reqPath, fi)
if err != nil {
return http.StatusInternalServerError, err
}
@ -301,11 +326,13 @@ func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status in
defer release()
ctx := r.Context()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
if r.ContentLength > 0 {
return http.StatusUnsupportedMediaType, nil
}
if err := h.FileSystem.Mkdir(ctx, reqPath, 0777); err != nil {
if err := fs.MakeDir(ctx, reqPath); err != nil {
if os.IsNotExist(err) {
return http.StatusConflict, err
}
@ -345,6 +372,9 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status
}
ctx := r.Context()
user := ctx.Value("user").(*model.User)
src = path.Join(user.BasePath, src)
dst = path.Join(user.BasePath, dst)
if r.Method == "COPY" {
// Section 7.5.1 says that a COPY only needs to lock the destination,
@ -369,7 +399,7 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status
return http.StatusBadRequest, errInvalidDepth
}
}
return copyFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0)
return copyFiles(ctx, src, dst, r.Header.Get("Overwrite") != "F")
}
release, status, err := h.confirmLocks(r, src, dst)
@ -386,7 +416,7 @@ func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status
return http.StatusBadRequest, errInvalidDepth
}
}
return moveFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T")
return moveFiles(ctx, src, dst, r.Header.Get("Overwrite") == "T")
}
func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) {
@ -400,6 +430,7 @@ func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus
}
ctx := r.Context()
user := ctx.Value("user").(*model.User)
token, ld, now, created := "", LockDetails{}, time.Now(), false
if li == (lockInfo{}) {
// An empty lockInfo means to refresh the lock.
@ -434,6 +465,7 @@ func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus
}
}
reqPath, status, err := h.stripPrefix(r.URL.Path)
reqPath = path.Join(user.BasePath, reqPath)
if err != nil {
return status, err
}
@ -456,16 +488,17 @@ func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus
}
}()
// Create the resource if it didn't previously exist.
if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
// TODO: detect missing intermediate dirs and return http.StatusConflict?
return http.StatusInternalServerError, err
}
f.Close()
created = true
}
// ??? Why create resource here?
//// Create the resource if it didn't previously exist.
//if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
// f, err := h.FileSystem.OpenFile(ctx, reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
// if err != nil {
// // TODO: detect missing intermediate dirs and return http.StatusConflict?
// return http.StatusInternalServerError, err
// }
// f.Close()
// created = true
//}
// http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
// Lock-Token value is a Coded-URL. We add angle brackets.
@ -512,9 +545,11 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status
return status, err
}
ctx := r.Context()
fi, err := h.FileSystem.Stat(ctx, reqPath)
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
fi, err := fs.Get(ctx, reqPath)
if err != nil {
if os.IsNotExist(err) {
if errs.IsObjectNotFound(err) {
return http.StatusNotFound, err
}
return http.StatusMethodNotAllowed, err
@ -533,13 +568,13 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status
mw := multistatusWriter{w: w}
walkFn := func(reqPath string, info os.FileInfo, err error) error {
walkFn := func(reqPath string, info model.Obj, err error) error {
if err != nil {
return err
}
var pstats []Propstat
if pf.Propname != nil {
pnames, err := propnames(ctx, h.FileSystem, h.LockSystem, reqPath)
pnames, err := propnames(ctx, h.LockSystem, info)
if err != nil {
return err
}
@ -549,9 +584,9 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status
}
pstats = append(pstats, pstat)
} else if pf.Allprop != nil {
pstats, err = allprop(ctx, h.FileSystem, h.LockSystem, reqPath, pf.Prop)
pstats, err = allprop(ctx, h.LockSystem, info, pf.Prop)
} else {
pstats, err = props(ctx, h.FileSystem, h.LockSystem, reqPath, pf.Prop)
pstats, err = props(ctx, h.LockSystem, info, pf.Prop)
}
if err != nil {
return err
@ -563,7 +598,7 @@ func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status
return mw.write(makePropstatResponse(href, pstats))
}
walkErr := walkFS(ctx, h.FileSystem, depth, reqPath, fi, walkFn)
walkErr := walkFS(ctx, depth, reqPath, fi, walkFn)
closeErr := mw.close()
if walkErr != nil {
return http.StatusInternalServerError, walkErr
@ -586,9 +621,11 @@ func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request) (statu
defer release()
ctx := r.Context()
user := ctx.Value("user").(*model.User)
reqPath = path.Join(user.BasePath, reqPath)
if _, err := h.FileSystem.Stat(ctx, reqPath); err != nil {
if os.IsNotExist(err) {
if _, err := fs.Get(ctx, reqPath); err != nil {
if errs.IsObjectNotFound(err) {
return http.StatusNotFound, err
}
return http.StatusMethodNotAllowed, err
@ -597,7 +634,7 @@ func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request) (statu
if err != nil {
return status, err
}
pstats, err := patch(ctx, h.FileSystem, h.LockSystem, reqPath, patches)
pstats, err := patch(ctx, h.LockSystem, reqPath, patches)
if err != nil {
return http.StatusInternalServerError, err
}