395 lines
11 KiB
Go
395 lines
11 KiB
Go
// 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 provides a WebDAV server implementation.
|
|
package webdav
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
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
|
|
// Logger is an optional error logger. If non-nil, it will be called
|
|
// for all HTTP requests.
|
|
Logger func(*http.Request, error)
|
|
}
|
|
|
|
func (h *Handler) stripPrefix(p string) (string, int, error) {
|
|
if h.Prefix == "" {
|
|
return p, http.StatusOK, nil
|
|
}
|
|
if r := strings.TrimPrefix(p, h.Prefix); len(r) < len(p) {
|
|
return r, http.StatusOK, nil
|
|
}
|
|
return p, http.StatusNotFound, errPrefixMismatch
|
|
}
|
|
|
|
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 {
|
|
switch r.Method {
|
|
case "OPTIONS":
|
|
status, err = h.handleOptions(w, r)
|
|
case "GET", "HEAD", "POST":
|
|
status, err = h.handleGetHeadPost(w, r)
|
|
case "DELETE":
|
|
status, err = h.handleDelete(w, r)
|
|
case "PUT":
|
|
status, err = h.handlePut(w, r)
|
|
case "MKCOL":
|
|
status, err = h.handleMkcol(w, r)
|
|
case "COPY", "MOVE":
|
|
status, err = h.handleCopyMove(w, r)
|
|
case "PROPFIND":
|
|
status, err = h.handlePropfind(w, r)
|
|
}
|
|
}
|
|
|
|
if status != 0 {
|
|
w.WriteHeader(status)
|
|
if status != http.StatusNoContent {
|
|
w.Write([]byte(http.StatusText(status)))
|
|
}
|
|
}
|
|
if h.Logger != nil {
|
|
h.Logger(r, err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
ctx := r.Context()
|
|
allow := "OPTIONS, PUT, MKCOL"
|
|
if fi, err := h.FileSystem.Stat(ctx, reqPath); err == nil {
|
|
if fi.IsDir() {
|
|
allow = "OPTIONS, DELETE, COPY, MOVE, PROPFIND"
|
|
} else {
|
|
allow = "OPTIONS, GET, HEAD, POST, DELETE, COPY, MOVE, PROPFIND, PUT"
|
|
}
|
|
}
|
|
w.Header().Set("Allow", allow)
|
|
// http://www.webdav.org/specs/rfc4918.html#dav.compliance.classes
|
|
w.Header().Set("DAV", "1, 2")
|
|
// http://msdn.microsoft.com/en-au/library/cc250217.aspx
|
|
w.Header().Set("MS-Author-Via", "DAV")
|
|
return 0, nil
|
|
}
|
|
|
|
func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
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()
|
|
if err != nil {
|
|
return http.StatusNotFound, err
|
|
}
|
|
if fi.IsDir() {
|
|
return http.StatusMethodNotAllowed, nil
|
|
}
|
|
etag, err := findETag(ctx, h.FileSystem, 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)
|
|
return 0, nil
|
|
}
|
|
|
|
func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
|
|
ctx := r.Context()
|
|
|
|
// 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) {
|
|
return http.StatusNotFound, err
|
|
}
|
|
return http.StatusMethodNotAllowed, err
|
|
}
|
|
if err := h.FileSystem.RemoveAll(ctx, reqPath); err != nil {
|
|
return http.StatusMethodNotAllowed, err
|
|
}
|
|
return http.StatusNoContent, nil
|
|
}
|
|
|
|
func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
ctx := r.Context()
|
|
|
|
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 statErr != nil {
|
|
return http.StatusMethodNotAllowed, statErr
|
|
}
|
|
if closeErr != nil {
|
|
return http.StatusMethodNotAllowed, closeErr
|
|
}
|
|
etag, err := findETag(ctx, h.FileSystem, reqPath, fi)
|
|
if err != nil {
|
|
return http.StatusInternalServerError, err
|
|
}
|
|
|
|
w.Header().Set("Etag", etag)
|
|
w.Header().Set("Oc-Etag", etag)
|
|
w.Header().Set("Oc-Fileid", etag)
|
|
w.Header().Set("X-Hash-Md5", "97a81b5ce26cfa53e66c21da5c3d60ee")
|
|
w.Header().Set("X-Hash-Sha1", "0bdaebd3d8915d4a7de79cdc76cc42ad757a073d")
|
|
w.Header().Set("X-Hash-Sha256", "7de442457c55ce163ca64e7952cf4e1c796488f24f2adae8140f4f3160ea94c2")
|
|
if r.Header.Get("X-Oc-Ctime") != "" {
|
|
w.Header().Set("X-Oc-Ctime", "accepted")
|
|
}
|
|
if r.Header.Get("X-Oc-Mtime") != "" {
|
|
w.Header().Set("X-Oc-Mtime", "accepted")
|
|
}
|
|
return http.StatusCreated, nil
|
|
}
|
|
|
|
func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
ctx := r.Context()
|
|
|
|
if r.ContentLength > 0 {
|
|
return http.StatusUnsupportedMediaType, nil
|
|
}
|
|
if err := h.FileSystem.Mkdir(ctx, reqPath, 0777); err != nil {
|
|
if os.IsNotExist(err) {
|
|
return http.StatusConflict, err
|
|
}
|
|
return http.StatusMethodNotAllowed, err
|
|
}
|
|
return http.StatusCreated, nil
|
|
}
|
|
|
|
func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
hdr := r.Header.Get("Destination")
|
|
if hdr == "" {
|
|
return http.StatusBadRequest, errInvalidDestination
|
|
}
|
|
u, err := url.Parse(hdr)
|
|
if err != nil {
|
|
return http.StatusBadRequest, errInvalidDestination
|
|
}
|
|
if u.Host != "" && u.Host != r.Host {
|
|
return http.StatusBadGateway, errInvalidDestination
|
|
}
|
|
|
|
src, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
|
|
dst, status, err := h.stripPrefix(u.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
|
|
if dst == "" {
|
|
return http.StatusBadGateway, errInvalidDestination
|
|
}
|
|
if dst == src {
|
|
return http.StatusForbidden, errDestinationEqualsSource
|
|
}
|
|
|
|
ctx := r.Context()
|
|
|
|
if r.Method == "COPY" {
|
|
// Section 9.8.3 says that "The COPY method on a collection without a Depth
|
|
// header must act as if a Depth header with value "infinity" was included".
|
|
depth := infiniteDepth
|
|
if hdr := r.Header.Get("Depth"); hdr != "" {
|
|
depth = parseDepth(hdr)
|
|
if depth != 0 && depth != infiniteDepth {
|
|
// Section 9.8.3 says that "A client may submit a Depth header on a
|
|
// COPY on a collection with a value of "0" or "infinity"."
|
|
return http.StatusBadRequest, errInvalidDepth
|
|
}
|
|
}
|
|
return copyFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0)
|
|
}
|
|
|
|
// Section 9.9.2 says that "The MOVE method on a collection must act as if
|
|
// a "Depth: infinity" header was used on it. A client must not submit a
|
|
// Depth header on a MOVE on a collection with any value but "infinity"."
|
|
if hdr := r.Header.Get("Depth"); hdr != "" {
|
|
if parseDepth(hdr) != infiniteDepth {
|
|
return http.StatusBadRequest, errInvalidDepth
|
|
}
|
|
}
|
|
return moveFiles(ctx, h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T")
|
|
}
|
|
|
|
func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status int, err error) {
|
|
reqPath, status, err := h.stripPrefix(r.URL.Path)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
ctx := r.Context()
|
|
fi, err := h.FileSystem.Stat(ctx, reqPath)
|
|
if err != nil {
|
|
if os.IsNotExist(err) {
|
|
return http.StatusNotFound, err
|
|
}
|
|
return http.StatusMethodNotAllowed, err
|
|
}
|
|
depth := infiniteDepth
|
|
if hdr := r.Header.Get("Depth"); hdr != "" {
|
|
depth = parseDepth(hdr)
|
|
if depth == invalidDepth {
|
|
return http.StatusBadRequest, errInvalidDepth
|
|
}
|
|
}
|
|
pf, status, err := readPropfind(r.Body)
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
mw := multistatusWriter{w: w}
|
|
|
|
walkFn := func(reqPath string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var pstats []Propstat
|
|
if pf.Propname != nil {
|
|
pnames, err := propnames(ctx, h.FileSystem, reqPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pstat := Propstat{Status: http.StatusOK}
|
|
for _, xmlname := range pnames {
|
|
pstat.Props = append(pstat.Props, Property{XMLName: xmlname})
|
|
}
|
|
pstats = append(pstats, pstat)
|
|
} else if pf.Allprop != nil {
|
|
pstats, err = allprop(ctx, h.FileSystem, reqPath, pf.Prop)
|
|
} else {
|
|
pstats, err = props(ctx, h.FileSystem, reqPath, pf.Prop)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
href := path.Join(h.Prefix, reqPath)
|
|
if href != "/" && info.IsDir() {
|
|
href += "/"
|
|
}
|
|
return mw.write(makePropstatResponse(href, pstats))
|
|
}
|
|
|
|
walkErr := walkFS(ctx, h.FileSystem, depth, reqPath, fi, walkFn)
|
|
closeErr := mw.close()
|
|
if walkErr != nil {
|
|
return http.StatusInternalServerError, walkErr
|
|
}
|
|
if closeErr != nil {
|
|
return http.StatusInternalServerError, closeErr
|
|
}
|
|
return 0, nil
|
|
}
|
|
|
|
func makePropstatResponse(href string, pstats []Propstat) *response {
|
|
resp := response{
|
|
Href: []string{(&url.URL{Path: href}).EscapedPath()},
|
|
Propstat: make([]propstat, 0, len(pstats)),
|
|
}
|
|
for _, p := range pstats {
|
|
var xmlErr *xmlError
|
|
if p.XMLError != "" {
|
|
xmlErr = &xmlError{InnerXML: []byte(p.XMLError)}
|
|
}
|
|
resp.Propstat = append(resp.Propstat, propstat{
|
|
Status: fmt.Sprintf("HTTP/1.1 %d %s", p.Status, http.StatusText(p.Status)),
|
|
Prop: p.Props,
|
|
ResponseDescription: p.ResponseDescription,
|
|
Error: xmlErr,
|
|
})
|
|
}
|
|
return &resp
|
|
}
|
|
|
|
const (
|
|
infiniteDepth = -1
|
|
invalidDepth = -2
|
|
)
|
|
|
|
// parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and
|
|
// infiniteDepth. Parsing any other string returns invalidDepth.
|
|
//
|
|
// Different WebDAV methods have further constraints on valid depths:
|
|
// - PROPFIND has no further restrictions, as per section 9.1.
|
|
// - COPY accepts only "0" or "infinity", as per section 9.8.3.
|
|
// - MOVE accepts only "infinity", as per section 9.9.2.
|
|
// These constraints are enforced by the handleXxx methods.
|
|
func parseDepth(s string) int {
|
|
switch s {
|
|
case "0":
|
|
return 0
|
|
case "1":
|
|
return 1
|
|
case "infinity":
|
|
// forbidden for security
|
|
return invalidDepth
|
|
}
|
|
return invalidDepth
|
|
}
|
|
|
|
var (
|
|
errDestinationEqualsSource = errors.New("webdav: destination equals source")
|
|
errDirectoryNotEmpty = errors.New("webdav: directory not empty")
|
|
errInvalidDepth = errors.New("webdav: invalid depth")
|
|
errInvalidDestination = errors.New("webdav: invalid destination")
|
|
errInvalidPropfind = errors.New("webdav: invalid propfind")
|
|
errInvalidResponse = errors.New("webdav: invalid response")
|
|
errNoFileSystem = errors.New("webdav: no file system")
|
|
errNotADirectory = errors.New("webdav: not a directory")
|
|
errPrefixMismatch = errors.New("webdav: prefix mismatch")
|
|
errRecursionTooDeep = errors.New("webdav: recursion too deep")
|
|
errUnsupportedMethod = errors.New("webdav: unsupported method")
|
|
)
|