webdav.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package webdav etc etc TODO.
  5. package webdav // import "golang.org/x/net/webdav"
  6. import (
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "runtime"
  15. "strings"
  16. "time"
  17. )
  18. // Package webdav's XML output requires the standard library's encoding/xml
  19. // package version 1.5 or greater. Otherwise, it will produce malformed XML.
  20. //
  21. // As of May 2015, the Go stable release is version 1.4, so we print a message
  22. // to let users know that this golang.org/x/etc package won't work yet.
  23. //
  24. // This package also won't work with Go 1.3 and earlier, but making this
  25. // runtime version check catch all the earlier versions too, and not just
  26. // "1.4.x", isn't worth the complexity.
  27. //
  28. // TODO: delete this check at some point after Go 1.5 is released.
  29. var go1Dot4 = strings.HasPrefix(runtime.Version(), "go1.4.")
  30. func init() {
  31. if go1Dot4 {
  32. log.Println("package webdav requires Go version 1.5 or greater")
  33. }
  34. }
  35. type Handler struct {
  36. // FileSystem is the virtual file system.
  37. FileSystem FileSystem
  38. // LockSystem is the lock management system.
  39. LockSystem LockSystem
  40. // Logger is an optional error logger. If non-nil, it will be called
  41. // for all HTTP requests.
  42. Logger func(*http.Request, error)
  43. }
  44. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  45. status, err := http.StatusBadRequest, errUnsupportedMethod
  46. if h.FileSystem == nil {
  47. status, err = http.StatusInternalServerError, errNoFileSystem
  48. } else if h.LockSystem == nil {
  49. status, err = http.StatusInternalServerError, errNoLockSystem
  50. } else {
  51. switch r.Method {
  52. case "OPTIONS":
  53. status, err = h.handleOptions(w, r)
  54. case "GET", "HEAD", "POST":
  55. status, err = h.handleGetHeadPost(w, r)
  56. case "DELETE":
  57. status, err = h.handleDelete(w, r)
  58. case "PUT":
  59. status, err = h.handlePut(w, r)
  60. case "MKCOL":
  61. status, err = h.handleMkcol(w, r)
  62. case "COPY", "MOVE":
  63. status, err = h.handleCopyMove(w, r)
  64. case "LOCK":
  65. status, err = h.handleLock(w, r)
  66. case "UNLOCK":
  67. status, err = h.handleUnlock(w, r)
  68. case "PROPFIND":
  69. status, err = h.handlePropfind(w, r)
  70. case "PROPPATCH":
  71. status, err = h.handleProppatch(w, r)
  72. }
  73. }
  74. if status != 0 {
  75. w.WriteHeader(status)
  76. if status != http.StatusNoContent {
  77. w.Write([]byte(StatusText(status)))
  78. }
  79. }
  80. if h.Logger != nil {
  81. h.Logger(r, err)
  82. }
  83. }
  84. func (h *Handler) lock(now time.Time, root string) (token string, status int, err error) {
  85. token, err = h.LockSystem.Create(now, LockDetails{
  86. Root: root,
  87. Duration: infiniteTimeout,
  88. ZeroDepth: true,
  89. })
  90. if err != nil {
  91. if err == ErrLocked {
  92. return "", StatusLocked, err
  93. }
  94. return "", http.StatusInternalServerError, err
  95. }
  96. return token, 0, nil
  97. }
  98. func (h *Handler) confirmLocks(r *http.Request, src, dst string) (release func(), status int, err error) {
  99. hdr := r.Header.Get("If")
  100. if hdr == "" {
  101. // An empty If header means that the client hasn't previously created locks.
  102. // Even if this client doesn't care about locks, we still need to check that
  103. // the resources aren't locked by another client, so we create temporary
  104. // locks that would conflict with another client's locks. These temporary
  105. // locks are unlocked at the end of the HTTP request.
  106. now, srcToken, dstToken := time.Now(), "", ""
  107. if src != "" {
  108. srcToken, status, err = h.lock(now, src)
  109. if err != nil {
  110. return nil, status, err
  111. }
  112. }
  113. if dst != "" {
  114. dstToken, status, err = h.lock(now, dst)
  115. if err != nil {
  116. if srcToken != "" {
  117. h.LockSystem.Unlock(now, srcToken)
  118. }
  119. return nil, status, err
  120. }
  121. }
  122. return func() {
  123. if dstToken != "" {
  124. h.LockSystem.Unlock(now, dstToken)
  125. }
  126. if srcToken != "" {
  127. h.LockSystem.Unlock(now, srcToken)
  128. }
  129. }, 0, nil
  130. }
  131. ih, ok := parseIfHeader(hdr)
  132. if !ok {
  133. return nil, http.StatusBadRequest, errInvalidIfHeader
  134. }
  135. // ih is a disjunction (OR) of ifLists, so any ifList will do.
  136. for _, l := range ih.lists {
  137. lsrc := l.resourceTag
  138. if lsrc == "" {
  139. lsrc = src
  140. } else {
  141. u, err := url.Parse(lsrc)
  142. if err != nil {
  143. continue
  144. }
  145. if u.Host != r.Host {
  146. continue
  147. }
  148. lsrc = u.Path
  149. }
  150. release, err = h.LockSystem.Confirm(time.Now(), lsrc, dst, l.conditions...)
  151. if err == ErrConfirmationFailed {
  152. continue
  153. }
  154. if err != nil {
  155. return nil, http.StatusInternalServerError, err
  156. }
  157. return release, 0, nil
  158. }
  159. // Section 10.4.1 says that "If this header is evaluated and all state lists
  160. // fail, then the request must fail with a 412 (Precondition Failed) status."
  161. // We follow the spec even though the cond_put_corrupt_token test case from
  162. // the litmus test warns on seeing a 412 instead of a 423 (Locked).
  163. return nil, http.StatusPreconditionFailed, ErrLocked
  164. }
  165. func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status int, err error) {
  166. allow := "OPTIONS, LOCK, PUT, MKCOL"
  167. if fi, err := h.FileSystem.Stat(r.URL.Path); err == nil {
  168. if fi.IsDir() {
  169. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND"
  170. } else {
  171. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND, PUT"
  172. }
  173. }
  174. w.Header().Set("Allow", allow)
  175. // http://www.webdav.org/specs/rfc4918.html#dav.compliance.classes
  176. w.Header().Set("DAV", "1, 2")
  177. // http://msdn.microsoft.com/en-au/library/cc250217.aspx
  178. w.Header().Set("MS-Author-Via", "DAV")
  179. return 0, nil
  180. }
  181. func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (status int, err error) {
  182. // TODO: check locks for read-only access??
  183. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDONLY, 0)
  184. if err != nil {
  185. return http.StatusNotFound, err
  186. }
  187. defer f.Close()
  188. fi, err := f.Stat()
  189. if err != nil {
  190. return http.StatusNotFound, err
  191. }
  192. if !fi.IsDir() {
  193. etag, err := findETag(h.FileSystem, h.LockSystem, r.URL.Path, fi)
  194. if err != nil {
  195. return http.StatusInternalServerError, err
  196. }
  197. w.Header().Set("ETag", etag)
  198. }
  199. // Let ServeContent determine the Content-Type header.
  200. http.ServeContent(w, r, r.URL.Path, fi.ModTime(), f)
  201. return 0, nil
  202. }
  203. func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status int, err error) {
  204. release, status, err := h.confirmLocks(r, r.URL.Path, "")
  205. if err != nil {
  206. return status, err
  207. }
  208. defer release()
  209. // TODO: return MultiStatus where appropriate.
  210. // "godoc os RemoveAll" says that "If the path does not exist, RemoveAll
  211. // returns nil (no error)." WebDAV semantics are that it should return a
  212. // "404 Not Found". We therefore have to Stat before we RemoveAll.
  213. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  214. if os.IsNotExist(err) {
  215. return http.StatusNotFound, err
  216. }
  217. return http.StatusMethodNotAllowed, err
  218. }
  219. if err := h.FileSystem.RemoveAll(r.URL.Path); err != nil {
  220. return http.StatusMethodNotAllowed, err
  221. }
  222. return http.StatusNoContent, nil
  223. }
  224. func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) {
  225. release, status, err := h.confirmLocks(r, r.URL.Path, "")
  226. if err != nil {
  227. return status, err
  228. }
  229. defer release()
  230. // TODO(rost): Support the If-Match, If-None-Match headers? See bradfitz'
  231. // comments in http.checkEtag.
  232. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  233. if err != nil {
  234. return http.StatusNotFound, err
  235. }
  236. _, copyErr := io.Copy(f, r.Body)
  237. fi, statErr := f.Stat()
  238. closeErr := f.Close()
  239. // TODO(rost): Returning 405 Method Not Allowed might not be appropriate.
  240. if copyErr != nil {
  241. return http.StatusMethodNotAllowed, copyErr
  242. }
  243. if statErr != nil {
  244. return http.StatusMethodNotAllowed, statErr
  245. }
  246. if closeErr != nil {
  247. return http.StatusMethodNotAllowed, closeErr
  248. }
  249. etag, err := findETag(h.FileSystem, h.LockSystem, r.URL.Path, fi)
  250. if err != nil {
  251. return http.StatusInternalServerError, err
  252. }
  253. w.Header().Set("ETag", etag)
  254. return http.StatusCreated, nil
  255. }
  256. func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status int, err error) {
  257. release, status, err := h.confirmLocks(r, r.URL.Path, "")
  258. if err != nil {
  259. return status, err
  260. }
  261. defer release()
  262. if r.ContentLength > 0 {
  263. return http.StatusUnsupportedMediaType, nil
  264. }
  265. if err := h.FileSystem.Mkdir(r.URL.Path, 0777); err != nil {
  266. if os.IsNotExist(err) {
  267. return http.StatusConflict, err
  268. }
  269. return http.StatusMethodNotAllowed, err
  270. }
  271. return http.StatusCreated, nil
  272. }
  273. func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status int, err error) {
  274. hdr := r.Header.Get("Destination")
  275. if hdr == "" {
  276. return http.StatusBadRequest, errInvalidDestination
  277. }
  278. u, err := url.Parse(hdr)
  279. if err != nil {
  280. return http.StatusBadRequest, errInvalidDestination
  281. }
  282. if u.Host != r.Host {
  283. return http.StatusBadGateway, errInvalidDestination
  284. }
  285. dst, src := u.Path, r.URL.Path
  286. if dst == "" {
  287. return http.StatusBadGateway, errInvalidDestination
  288. }
  289. if dst == src {
  290. return http.StatusForbidden, errDestinationEqualsSource
  291. }
  292. if r.Method == "COPY" {
  293. // Section 7.5.1 says that a COPY only needs to lock the destination,
  294. // not both destination and source. Strictly speaking, this is racy,
  295. // even though a COPY doesn't modify the source, if a concurrent
  296. // operation modifies the source. However, the litmus test explicitly
  297. // checks that COPYing a locked-by-another source is OK.
  298. release, status, err := h.confirmLocks(r, "", dst)
  299. if err != nil {
  300. return status, err
  301. }
  302. defer release()
  303. // Section 9.8.3 says that "The COPY method on a collection without a Depth
  304. // header must act as if a Depth header with value "infinity" was included".
  305. depth := infiniteDepth
  306. if hdr := r.Header.Get("Depth"); hdr != "" {
  307. depth = parseDepth(hdr)
  308. if depth != 0 && depth != infiniteDepth {
  309. // Section 9.8.3 says that "A client may submit a Depth header on a
  310. // COPY on a collection with a value of "0" or "infinity"."
  311. return http.StatusBadRequest, errInvalidDepth
  312. }
  313. }
  314. return copyFiles(h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0)
  315. }
  316. release, status, err := h.confirmLocks(r, src, dst)
  317. if err != nil {
  318. return status, err
  319. }
  320. defer release()
  321. // Section 9.9.2 says that "The MOVE method on a collection must act as if
  322. // a "Depth: infinity" header was used on it. A client must not submit a
  323. // Depth header on a MOVE on a collection with any value but "infinity"."
  324. if hdr := r.Header.Get("Depth"); hdr != "" {
  325. if parseDepth(hdr) != infiniteDepth {
  326. return http.StatusBadRequest, errInvalidDepth
  327. }
  328. }
  329. return moveFiles(h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T")
  330. }
  331. func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) {
  332. duration, err := parseTimeout(r.Header.Get("Timeout"))
  333. if err != nil {
  334. return http.StatusBadRequest, err
  335. }
  336. li, status, err := readLockInfo(r.Body)
  337. if err != nil {
  338. return status, err
  339. }
  340. token, ld, now, created := "", LockDetails{}, time.Now(), false
  341. if li == (lockInfo{}) {
  342. // An empty lockInfo means to refresh the lock.
  343. ih, ok := parseIfHeader(r.Header.Get("If"))
  344. if !ok {
  345. return http.StatusBadRequest, errInvalidIfHeader
  346. }
  347. if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 {
  348. token = ih.lists[0].conditions[0].Token
  349. }
  350. if token == "" {
  351. return http.StatusBadRequest, errInvalidLockToken
  352. }
  353. ld, err = h.LockSystem.Refresh(now, token, duration)
  354. if err != nil {
  355. if err == ErrNoSuchLock {
  356. return http.StatusPreconditionFailed, err
  357. }
  358. return http.StatusInternalServerError, err
  359. }
  360. } else {
  361. // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request,
  362. // then the request MUST act as if a "Depth:infinity" had been submitted."
  363. depth := infiniteDepth
  364. if hdr := r.Header.Get("Depth"); hdr != "" {
  365. depth = parseDepth(hdr)
  366. if depth != 0 && depth != infiniteDepth {
  367. // Section 9.10.3 says that "Values other than 0 or infinity must not be
  368. // used with the Depth header on a LOCK method".
  369. return http.StatusBadRequest, errInvalidDepth
  370. }
  371. }
  372. ld = LockDetails{
  373. Root: r.URL.Path,
  374. Duration: duration,
  375. OwnerXML: li.Owner.InnerXML,
  376. ZeroDepth: depth == 0,
  377. }
  378. token, err = h.LockSystem.Create(now, ld)
  379. if err != nil {
  380. if err == ErrLocked {
  381. return StatusLocked, err
  382. }
  383. return http.StatusInternalServerError, err
  384. }
  385. defer func() {
  386. if retErr != nil {
  387. h.LockSystem.Unlock(now, token)
  388. }
  389. }()
  390. // Create the resource if it didn't previously exist.
  391. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  392. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  393. if err != nil {
  394. // TODO: detect missing intermediate dirs and return http.StatusConflict?
  395. return http.StatusInternalServerError, err
  396. }
  397. f.Close()
  398. created = true
  399. }
  400. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  401. // Lock-Token value is a Coded-URL. We add angle brackets.
  402. w.Header().Set("Lock-Token", "<"+token+">")
  403. }
  404. w.Header().Set("Content-Type", "application/xml; charset=utf-8")
  405. if created {
  406. // This is "w.WriteHeader(http.StatusCreated)" and not "return
  407. // http.StatusCreated, nil" because we write our own (XML) response to w
  408. // and Handler.ServeHTTP would otherwise write "Created".
  409. w.WriteHeader(http.StatusCreated)
  410. }
  411. writeLockInfo(w, token, ld)
  412. return 0, nil
  413. }
  414. func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) {
  415. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  416. // Lock-Token value is a Coded-URL. We strip its angle brackets.
  417. t := r.Header.Get("Lock-Token")
  418. if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' {
  419. return http.StatusBadRequest, errInvalidLockToken
  420. }
  421. t = t[1 : len(t)-1]
  422. switch err = h.LockSystem.Unlock(time.Now(), t); err {
  423. case nil:
  424. return http.StatusNoContent, err
  425. case ErrForbidden:
  426. return http.StatusForbidden, err
  427. case ErrLocked:
  428. return StatusLocked, err
  429. case ErrNoSuchLock:
  430. return http.StatusConflict, err
  431. default:
  432. return http.StatusInternalServerError, err
  433. }
  434. }
  435. func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status int, err error) {
  436. fi, err := h.FileSystem.Stat(r.URL.Path)
  437. if err != nil {
  438. if os.IsNotExist(err) {
  439. return http.StatusNotFound, err
  440. }
  441. return http.StatusMethodNotAllowed, err
  442. }
  443. depth := infiniteDepth
  444. if hdr := r.Header.Get("Depth"); hdr != "" {
  445. depth = parseDepth(hdr)
  446. if depth == invalidDepth {
  447. return http.StatusBadRequest, errInvalidDepth
  448. }
  449. }
  450. pf, status, err := readPropfind(r.Body)
  451. if err != nil {
  452. return status, err
  453. }
  454. mw := multistatusWriter{w: w}
  455. walkFn := func(path string, info os.FileInfo, err error) error {
  456. if err != nil {
  457. return err
  458. }
  459. var pstats []Propstat
  460. if pf.Propname != nil {
  461. pnames, err := propnames(h.FileSystem, h.LockSystem, path)
  462. if err != nil {
  463. return err
  464. }
  465. pstat := Propstat{Status: http.StatusOK}
  466. for _, xmlname := range pnames {
  467. pstat.Props = append(pstat.Props, Property{XMLName: xmlname})
  468. }
  469. pstats = append(pstats, pstat)
  470. } else if pf.Allprop != nil {
  471. pstats, err = allprop(h.FileSystem, h.LockSystem, path, pf.Prop)
  472. } else {
  473. pstats, err = props(h.FileSystem, h.LockSystem, path, pf.Prop)
  474. }
  475. if err != nil {
  476. return err
  477. }
  478. return mw.write(makePropstatResponse(path, pstats))
  479. }
  480. walkErr := walkFS(h.FileSystem, depth, r.URL.Path, fi, walkFn)
  481. closeErr := mw.close()
  482. if walkErr != nil {
  483. return http.StatusInternalServerError, walkErr
  484. }
  485. if closeErr != nil {
  486. return http.StatusInternalServerError, closeErr
  487. }
  488. return 0, nil
  489. }
  490. func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request) (status int, err error) {
  491. release, status, err := h.confirmLocks(r, r.URL.Path, "")
  492. if err != nil {
  493. return status, err
  494. }
  495. defer release()
  496. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  497. if os.IsNotExist(err) {
  498. return http.StatusNotFound, err
  499. }
  500. return http.StatusMethodNotAllowed, err
  501. }
  502. patches, status, err := readProppatch(r.Body)
  503. if err != nil {
  504. return status, err
  505. }
  506. pstats, err := patch(h.FileSystem, h.LockSystem, r.URL.Path, patches)
  507. if err != nil {
  508. return http.StatusInternalServerError, err
  509. }
  510. mw := multistatusWriter{w: w}
  511. writeErr := mw.write(makePropstatResponse(r.URL.Path, pstats))
  512. closeErr := mw.close()
  513. if writeErr != nil {
  514. return http.StatusInternalServerError, writeErr
  515. }
  516. if closeErr != nil {
  517. return http.StatusInternalServerError, closeErr
  518. }
  519. return 0, nil
  520. }
  521. func makePropstatResponse(href string, pstats []Propstat) *response {
  522. resp := response{
  523. Href: []string{href},
  524. Propstat: make([]propstat, 0, len(pstats)),
  525. }
  526. for _, p := range pstats {
  527. var xmlErr *xmlError
  528. if p.XMLError != "" {
  529. xmlErr = &xmlError{InnerXML: []byte(p.XMLError)}
  530. }
  531. resp.Propstat = append(resp.Propstat, propstat{
  532. Status: fmt.Sprintf("HTTP/1.1 %d %s", p.Status, StatusText(p.Status)),
  533. Prop: p.Props,
  534. ResponseDescription: p.ResponseDescription,
  535. Error: xmlErr,
  536. })
  537. }
  538. return &resp
  539. }
  540. const (
  541. infiniteDepth = -1
  542. invalidDepth = -2
  543. )
  544. // parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and
  545. // infiniteDepth. Parsing any other string returns invalidDepth.
  546. //
  547. // Different WebDAV methods have further constraints on valid depths:
  548. // - PROPFIND has no further restrictions, as per section 9.1.
  549. // - COPY accepts only "0" or "infinity", as per section 9.8.3.
  550. // - MOVE accepts only "infinity", as per section 9.9.2.
  551. // - LOCK accepts only "0" or "infinity", as per section 9.10.3.
  552. // These constraints are enforced by the handleXxx methods.
  553. func parseDepth(s string) int {
  554. switch s {
  555. case "0":
  556. return 0
  557. case "1":
  558. return 1
  559. case "infinity":
  560. return infiniteDepth
  561. }
  562. return invalidDepth
  563. }
  564. // StripPrefix is like http.StripPrefix but it also strips the prefix from any
  565. // Destination headers, so that COPY and MOVE requests also see stripped paths.
  566. func StripPrefix(prefix string, h http.Handler) http.Handler {
  567. if prefix == "" {
  568. return h
  569. }
  570. h = http.StripPrefix(prefix, h)
  571. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  572. dsts := r.Header["Destination"]
  573. for i, dst := range dsts {
  574. u, err := url.Parse(dst)
  575. if err != nil {
  576. continue
  577. }
  578. if p := strings.TrimPrefix(u.Path, prefix); len(p) < len(u.Path) {
  579. u.Path = p
  580. dsts[i] = u.String()
  581. }
  582. }
  583. h.ServeHTTP(w, r)
  584. })
  585. }
  586. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11
  587. const (
  588. StatusMulti = 207
  589. StatusUnprocessableEntity = 422
  590. StatusLocked = 423
  591. StatusFailedDependency = 424
  592. StatusInsufficientStorage = 507
  593. )
  594. func StatusText(code int) string {
  595. switch code {
  596. case StatusMulti:
  597. return "Multi-Status"
  598. case StatusUnprocessableEntity:
  599. return "Unprocessable Entity"
  600. case StatusLocked:
  601. return "Locked"
  602. case StatusFailedDependency:
  603. return "Failed Dependency"
  604. case StatusInsufficientStorage:
  605. return "Insufficient Storage"
  606. }
  607. return http.StatusText(code)
  608. }
  609. var (
  610. errDestinationEqualsSource = errors.New("webdav: destination equals source")
  611. errDirectoryNotEmpty = errors.New("webdav: directory not empty")
  612. errInvalidDepth = errors.New("webdav: invalid depth")
  613. errInvalidDestination = errors.New("webdav: invalid destination")
  614. errInvalidIfHeader = errors.New("webdav: invalid If header")
  615. errInvalidLockInfo = errors.New("webdav: invalid lock info")
  616. errInvalidLockToken = errors.New("webdav: invalid lock token")
  617. errInvalidPropfind = errors.New("webdav: invalid propfind")
  618. errInvalidProppatch = errors.New("webdav: invalid proppatch")
  619. errInvalidResponse = errors.New("webdav: invalid response")
  620. errInvalidTimeout = errors.New("webdav: invalid timeout")
  621. errNoFileSystem = errors.New("webdav: no file system")
  622. errNoLockSystem = errors.New("webdav: no lock system")
  623. errNotADirectory = errors.New("webdav: not a directory")
  624. errRecursionTooDeep = errors.New("webdav: recursion too deep")
  625. errUnsupportedLockInfo = errors.New("webdav: unsupported lock info")
  626. errUnsupportedMethod = errors.New("webdav: unsupported method")
  627. )