webdav.go 22 KB

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