webdav.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. // TODO: ETag, properties.
  7. import (
  8. "errors"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "time"
  14. )
  15. // TODO: define the PropSystem interface.
  16. type PropSystem interface{}
  17. type Handler struct {
  18. // FileSystem is the virtual file system.
  19. FileSystem FileSystem
  20. // LockSystem is the lock management system.
  21. LockSystem LockSystem
  22. // PropSystem is an optional property management system. If non-nil, TODO.
  23. PropSystem PropSystem
  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. }
  28. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  29. status, err := http.StatusBadRequest, error(nil)
  30. if h.FileSystem == nil {
  31. status, err = http.StatusInternalServerError, errNoFileSystem
  32. } else if h.LockSystem == nil {
  33. status, err = http.StatusInternalServerError, errNoLockSystem
  34. } else {
  35. // TODO: PROPFIND, PROPPATCH methods.
  36. switch r.Method {
  37. case "OPTIONS":
  38. status, err = h.handleOptions(w, r)
  39. case "GET", "HEAD", "POST":
  40. status, err = h.handleGetHeadPost(w, r)
  41. case "DELETE":
  42. status, err = h.handleDelete(w, r)
  43. case "PUT":
  44. status, err = h.handlePut(w, r)
  45. case "MKCOL":
  46. status, err = h.handleMkcol(w, r)
  47. case "COPY", "MOVE":
  48. status, err = h.handleCopyMove(w, r)
  49. case "LOCK":
  50. status, err = h.handleLock(w, r)
  51. case "UNLOCK":
  52. status, err = h.handleUnlock(w, r)
  53. }
  54. }
  55. if status != 0 {
  56. w.WriteHeader(status)
  57. if status != http.StatusNoContent {
  58. w.Write([]byte(StatusText(status)))
  59. }
  60. }
  61. if h.Logger != nil {
  62. h.Logger(r, err)
  63. }
  64. }
  65. type nopReleaser struct{}
  66. func (nopReleaser) Release() {}
  67. func (h *Handler) confirmLocks(r *http.Request) (releaser Releaser, status int, err error) {
  68. hdr := r.Header.Get("If")
  69. if hdr == "" {
  70. return nopReleaser{}, 0, nil
  71. }
  72. ih, ok := parseIfHeader(hdr)
  73. if !ok {
  74. return nil, http.StatusBadRequest, errInvalidIfHeader
  75. }
  76. // ih is a disjunction (OR) of ifLists, so any ifList will do.
  77. for _, l := range ih.lists {
  78. path := l.resourceTag
  79. if path == "" {
  80. path = r.URL.Path
  81. }
  82. releaser, err = h.LockSystem.Confirm(time.Now(), path, l.conditions...)
  83. if err == ErrConfirmationFailed {
  84. continue
  85. }
  86. if err != nil {
  87. return nil, http.StatusInternalServerError, err
  88. }
  89. return releaser, 0, nil
  90. }
  91. return nil, http.StatusPreconditionFailed, ErrLocked
  92. }
  93. func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status int, err error) {
  94. allow := "OPTIONS, LOCK, PUT, MKCOL"
  95. if fi, err := h.FileSystem.Stat(r.URL.Path); err == nil {
  96. if fi.IsDir() {
  97. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND"
  98. } else {
  99. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND, PUT"
  100. }
  101. }
  102. w.Header().Set("Allow", allow)
  103. // http://www.webdav.org/specs/rfc4918.html#dav.compliance.classes
  104. w.Header().Set("DAV", "1, 2")
  105. // http://msdn.microsoft.com/en-au/library/cc250217.aspx
  106. w.Header().Set("MS-Author-Via", "DAV")
  107. return 0, nil
  108. }
  109. func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (status int, err error) {
  110. // TODO: check locks for read-only access??
  111. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDONLY, 0)
  112. if err != nil {
  113. return http.StatusNotFound, err
  114. }
  115. defer f.Close()
  116. fi, err := f.Stat()
  117. if err != nil {
  118. return http.StatusNotFound, err
  119. }
  120. http.ServeContent(w, r, r.URL.Path, fi.ModTime(), f)
  121. return 0, nil
  122. }
  123. func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status int, err error) {
  124. releaser, status, err := h.confirmLocks(r)
  125. if err != nil {
  126. return status, err
  127. }
  128. defer releaser.Release()
  129. // TODO: return MultiStatus where appropriate.
  130. // "godoc os RemoveAll" says that "If the path does not exist, RemoveAll
  131. // returns nil (no error)." WebDAV semantics are that it should return a
  132. // "404 Not Found". We therefore have to Stat before we RemoveAll.
  133. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  134. if os.IsNotExist(err) {
  135. return http.StatusNotFound, err
  136. }
  137. return http.StatusMethodNotAllowed, err
  138. }
  139. if err := h.FileSystem.RemoveAll(r.URL.Path); err != nil {
  140. return http.StatusMethodNotAllowed, err
  141. }
  142. return http.StatusNoContent, nil
  143. }
  144. func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) {
  145. releaser, status, err := h.confirmLocks(r)
  146. if err != nil {
  147. return status, err
  148. }
  149. defer releaser.Release()
  150. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  151. if err != nil {
  152. return http.StatusNotFound, err
  153. }
  154. defer f.Close()
  155. if _, err := io.Copy(f, r.Body); err != nil {
  156. return http.StatusMethodNotAllowed, err
  157. }
  158. return http.StatusCreated, nil
  159. }
  160. func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status int, err error) {
  161. releaser, status, err := h.confirmLocks(r)
  162. if err != nil {
  163. return status, err
  164. }
  165. defer releaser.Release()
  166. if r.ContentLength > 0 {
  167. return http.StatusUnsupportedMediaType, nil
  168. }
  169. if err := h.FileSystem.Mkdir(r.URL.Path, 0777); err != nil {
  170. if os.IsNotExist(err) {
  171. return http.StatusConflict, err
  172. }
  173. return http.StatusMethodNotAllowed, err
  174. }
  175. return http.StatusCreated, nil
  176. }
  177. func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status int, err error) {
  178. // TODO: COPY/MOVE for Properties, as per sections 9.8.2 and 9.9.1.
  179. hdr := r.Header.Get("Destination")
  180. if hdr == "" {
  181. return http.StatusBadRequest, errInvalidDestination
  182. }
  183. u, err := url.Parse(hdr)
  184. if err != nil {
  185. return http.StatusBadRequest, errInvalidDestination
  186. }
  187. if u.Host != r.Host {
  188. return http.StatusBadGateway, errInvalidDestination
  189. }
  190. // TODO: do we need a webdav.StripPrefix HTTP handler that's like the
  191. // standard library's http.StripPrefix handler, but also strips the
  192. // prefix in the Destination header?
  193. dst, src := u.Path, r.URL.Path
  194. if dst == src {
  195. return http.StatusForbidden, errDestinationEqualsSource
  196. }
  197. // TODO: confirmLocks should also check dst.
  198. releaser, status, err := h.confirmLocks(r)
  199. if err != nil {
  200. return status, err
  201. }
  202. defer releaser.Release()
  203. if r.Method == "COPY" {
  204. // Section 9.8.3 says that "The COPY method on a collection without a Depth
  205. // header must act as if a Depth header with value "infinity" was included".
  206. depth := infiniteDepth
  207. if hdr := r.Header.Get("Depth"); hdr != "" {
  208. depth = parseDepth(hdr)
  209. if depth != 0 && depth != infiniteDepth {
  210. // Section 9.8.3 says that "A client may submit a Depth header on a
  211. // COPY on a collection with a value of "0" or "infinity"."
  212. return http.StatusBadRequest, errInvalidDepth
  213. }
  214. }
  215. return copyFiles(h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0)
  216. }
  217. // Section 9.9.2 says that "The MOVE method on a collection must act as if
  218. // a "Depth: infinity" header was used on it. A client must not submit a
  219. // Depth header on a MOVE on a collection with any value but "infinity"."
  220. if hdr := r.Header.Get("Depth"); hdr != "" {
  221. if parseDepth(hdr) != infiniteDepth {
  222. return http.StatusBadRequest, errInvalidDepth
  223. }
  224. }
  225. created := false
  226. if _, err := h.FileSystem.Stat(dst); err != nil {
  227. if !os.IsNotExist(err) {
  228. return http.StatusForbidden, err
  229. }
  230. created = true
  231. } else {
  232. switch r.Header.Get("Overwrite") {
  233. case "T":
  234. // Section 9.9.3 says that "If a resource exists at the destination
  235. // and the Overwrite header is "T", then prior to performing the move,
  236. // the server must perform a DELETE with "Depth: infinity" on the
  237. // destination resource.
  238. if err := h.FileSystem.RemoveAll(dst); err != nil {
  239. return http.StatusForbidden, err
  240. }
  241. case "F":
  242. return http.StatusPreconditionFailed, os.ErrExist
  243. default:
  244. return http.StatusBadRequest, errInvalidOverwrite
  245. }
  246. }
  247. if err := h.FileSystem.Rename(src, dst); err != nil {
  248. return http.StatusForbidden, err
  249. }
  250. if created {
  251. return http.StatusCreated, nil
  252. }
  253. return http.StatusNoContent, nil
  254. }
  255. func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) {
  256. duration, err := parseTimeout(r.Header.Get("Timeout"))
  257. if err != nil {
  258. return http.StatusBadRequest, err
  259. }
  260. li, status, err := readLockInfo(r.Body)
  261. if err != nil {
  262. return status, err
  263. }
  264. token, ld, now, created := "", LockDetails{}, time.Now(), false
  265. if li == (lockInfo{}) {
  266. // An empty lockInfo means to refresh the lock.
  267. ih, ok := parseIfHeader(r.Header.Get("If"))
  268. if !ok {
  269. return http.StatusBadRequest, errInvalidIfHeader
  270. }
  271. if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 {
  272. token = ih.lists[0].conditions[0].Token
  273. }
  274. if token == "" {
  275. return http.StatusBadRequest, errInvalidLockToken
  276. }
  277. ld, err = h.LockSystem.Refresh(now, token, duration)
  278. if err != nil {
  279. if err == ErrNoSuchLock {
  280. return http.StatusPreconditionFailed, err
  281. }
  282. return http.StatusInternalServerError, err
  283. }
  284. } else {
  285. // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request,
  286. // then the request MUST act as if a "Depth:infinity" had been submitted."
  287. depth := infiniteDepth
  288. if hdr := r.Header.Get("Depth"); hdr != "" {
  289. depth = parseDepth(hdr)
  290. if depth != 0 && depth != infiniteDepth {
  291. // Section 9.10.3 says that "Values other than 0 or infinity must not be
  292. // used with the Depth header on a LOCK method".
  293. return http.StatusBadRequest, errInvalidDepth
  294. }
  295. }
  296. ld = LockDetails{
  297. Root: r.URL.Path,
  298. Duration: duration,
  299. OwnerXML: li.Owner.InnerXML,
  300. ZeroDepth: depth == 0,
  301. }
  302. token, err = h.LockSystem.Create(now, ld)
  303. if err != nil {
  304. if err == ErrLocked {
  305. return StatusLocked, err
  306. }
  307. return http.StatusInternalServerError, err
  308. }
  309. defer func() {
  310. if retErr != nil {
  311. h.LockSystem.Unlock(now, token)
  312. }
  313. }()
  314. // Create the resource if it didn't previously exist.
  315. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  316. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  317. if err != nil {
  318. // TODO: detect missing intermediate dirs and return http.StatusConflict?
  319. return http.StatusInternalServerError, err
  320. }
  321. f.Close()
  322. created = true
  323. }
  324. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  325. // Lock-Token value is a Coded-URL. We add angle brackets.
  326. w.Header().Set("Lock-Token", "<"+token+">")
  327. }
  328. w.Header().Set("Content-Type", "application/xml; charset=utf-8")
  329. if created {
  330. // This is "w.WriteHeader(http.StatusCreated)" and not "return
  331. // http.StatusCreated, nil" because we write our own (XML) response to w
  332. // and Handler.ServeHTTP would otherwise write "Created".
  333. w.WriteHeader(http.StatusCreated)
  334. }
  335. writeLockInfo(w, token, ld)
  336. return 0, nil
  337. }
  338. func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) {
  339. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  340. // Lock-Token value is a Coded-URL. We strip its angle brackets.
  341. t := r.Header.Get("Lock-Token")
  342. if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' {
  343. return http.StatusBadRequest, errInvalidLockToken
  344. }
  345. t = t[1 : len(t)-1]
  346. switch err = h.LockSystem.Unlock(time.Now(), t); err {
  347. case nil:
  348. return http.StatusNoContent, err
  349. case ErrForbidden:
  350. return http.StatusForbidden, err
  351. case ErrLocked:
  352. return StatusLocked, err
  353. case ErrNoSuchLock:
  354. return http.StatusConflict, err
  355. default:
  356. return http.StatusInternalServerError, err
  357. }
  358. }
  359. const (
  360. infiniteDepth = -1
  361. invalidDepth = -2
  362. )
  363. // parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and
  364. // infiniteDepth. Parsing any other string returns invalidDepth.
  365. //
  366. // Different WebDAV methods have further constraints on valid depths:
  367. // - PROPFIND has no further restrictions, as per section 9.1.
  368. // - COPY accepts only "0" or "infinity", as per section 9.8.3.
  369. // - MOVE accepts only "infinity", as per section 9.9.2.
  370. // - LOCK accepts only "0" or "infinity", as per section 9.10.3.
  371. // These constraints are enforced by the handleXxx methods.
  372. func parseDepth(s string) int {
  373. switch s {
  374. case "0":
  375. return 0
  376. case "1":
  377. return 1
  378. case "infinity":
  379. return infiniteDepth
  380. }
  381. return invalidDepth
  382. }
  383. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11
  384. const (
  385. StatusMulti = 207
  386. StatusUnprocessableEntity = 422
  387. StatusLocked = 423
  388. StatusFailedDependency = 424
  389. StatusInsufficientStorage = 507
  390. )
  391. func StatusText(code int) string {
  392. switch code {
  393. case StatusMulti:
  394. return "Multi-Status"
  395. case StatusUnprocessableEntity:
  396. return "Unprocessable Entity"
  397. case StatusLocked:
  398. return "Locked"
  399. case StatusFailedDependency:
  400. return "Failed Dependency"
  401. case StatusInsufficientStorage:
  402. return "Insufficient Storage"
  403. }
  404. return http.StatusText(code)
  405. }
  406. var (
  407. errDestinationEqualsSource = errors.New("webdav: destination equals source")
  408. errDirectoryNotEmpty = errors.New("webdav: directory not empty")
  409. errInvalidDepth = errors.New("webdav: invalid depth")
  410. errInvalidDestination = errors.New("webdav: invalid destination")
  411. errInvalidIfHeader = errors.New("webdav: invalid If header")
  412. errInvalidLockInfo = errors.New("webdav: invalid lock info")
  413. errInvalidLockToken = errors.New("webdav: invalid lock token")
  414. errInvalidOverwrite = errors.New("webdav: invalid overwrite")
  415. errInvalidPropfind = errors.New("webdav: invalid propfind")
  416. errInvalidResponse = errors.New("webdav: invalid response")
  417. errInvalidTimeout = errors.New("webdav: invalid timeout")
  418. errNoFileSystem = errors.New("webdav: no file system")
  419. errNoLockSystem = errors.New("webdav: no lock system")
  420. errNotADirectory = errors.New("webdav: not a directory")
  421. errRecursionTooDeep = errors.New("webdav: recursion too deep")
  422. errUnsupportedLockInfo = errors.New("webdav: unsupported lock info")
  423. )