webdav.go 20 KB

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