webdav.go 21 KB

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