webdav.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "os"
  12. "time"
  13. )
  14. // TODO: define the PropSystem interface.
  15. type PropSystem interface{}
  16. type Handler struct {
  17. // FileSystem is the virtual file system.
  18. FileSystem FileSystem
  19. // LockSystem is the lock management system.
  20. LockSystem LockSystem
  21. // PropSystem is an optional property management system. If non-nil, TODO.
  22. PropSystem PropSystem
  23. // Logger is an optional error logger. If non-nil, it will be called
  24. // for all HTTP requests.
  25. Logger func(*http.Request, error)
  26. }
  27. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. status, err := http.StatusBadRequest, error(nil)
  29. if h.FileSystem == nil {
  30. status, err = http.StatusInternalServerError, errNoFileSystem
  31. } else if h.LockSystem == nil {
  32. status, err = http.StatusInternalServerError, errNoLockSystem
  33. } else {
  34. // TODO: COPY, MOVE, PROPFIND, PROPPATCH methods.
  35. // MOVE needs to enforce its Depth constraint. See the parseDepth comment.
  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 "LOCK":
  48. status, err = h.handleLock(w, r)
  49. case "UNLOCK":
  50. status, err = h.handleUnlock(w, r)
  51. }
  52. }
  53. if status != 0 {
  54. w.WriteHeader(status)
  55. if status != http.StatusNoContent {
  56. w.Write([]byte(StatusText(status)))
  57. }
  58. }
  59. if h.Logger != nil {
  60. h.Logger(r, err)
  61. }
  62. }
  63. type nopReleaser struct{}
  64. func (nopReleaser) Release() {}
  65. func (h *Handler) confirmLocks(r *http.Request) (releaser Releaser, status int, err error) {
  66. hdr := r.Header.Get("If")
  67. if hdr == "" {
  68. return nopReleaser{}, 0, nil
  69. }
  70. ih, ok := parseIfHeader(hdr)
  71. if !ok {
  72. return nil, http.StatusBadRequest, errInvalidIfHeader
  73. }
  74. // ih is a disjunction (OR) of ifLists, so any ifList will do.
  75. for _, l := range ih.lists {
  76. path := l.resourceTag
  77. if path == "" {
  78. path = r.URL.Path
  79. }
  80. releaser, err = h.LockSystem.Confirm(time.Now(), path, l.conditions...)
  81. if err == ErrConfirmationFailed {
  82. continue
  83. }
  84. if err != nil {
  85. return nil, http.StatusInternalServerError, err
  86. }
  87. return releaser, 0, nil
  88. }
  89. return nil, http.StatusPreconditionFailed, ErrLocked
  90. }
  91. func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status int, err error) {
  92. allow := "OPTIONS, LOCK, PUT, MKCOL"
  93. if fi, err := h.FileSystem.Stat(r.URL.Path); err == nil {
  94. if fi.IsDir() {
  95. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, TRACE, PROPPATCH, COPY, MOVE, UNLOCK, PUT, PROPFIND"
  96. } else {
  97. allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, TRACE, PROPPATCH, COPY, MOVE, UNLOCK"
  98. }
  99. }
  100. // http://www.webdav.org/specs/rfc4918.html#dav.compliance.classes
  101. w.Header().Set("DAV", "1, 2")
  102. // http://msdn.microsoft.com/en-au/library/cc250217.aspx
  103. w.Header().Set("MS-Author-Via", "DAV")
  104. w.Header().Set("Allow", allow)
  105. return 0, nil
  106. }
  107. func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (status int, err error) {
  108. // TODO: check locks for read-only access??
  109. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDONLY, 0)
  110. if err != nil {
  111. return http.StatusNotFound, err
  112. }
  113. defer f.Close()
  114. fi, err := f.Stat()
  115. if err != nil {
  116. return http.StatusNotFound, err
  117. }
  118. http.ServeContent(w, r, r.URL.Path, fi.ModTime(), f)
  119. return 0, nil
  120. }
  121. func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status int, err error) {
  122. releaser, status, err := h.confirmLocks(r)
  123. if err != nil {
  124. return status, err
  125. }
  126. defer releaser.Release()
  127. if err := h.FileSystem.RemoveAll(r.URL.Path); err != nil {
  128. if os.IsNotExist(err) {
  129. return http.StatusNotFound, err
  130. }
  131. // TODO: MultiStatus.
  132. return http.StatusMethodNotAllowed, err
  133. }
  134. return http.StatusNoContent, nil
  135. }
  136. func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) {
  137. releaser, status, err := h.confirmLocks(r)
  138. if err != nil {
  139. return status, err
  140. }
  141. defer releaser.Release()
  142. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  143. if err != nil {
  144. return http.StatusNotFound, err
  145. }
  146. defer f.Close()
  147. if _, err := io.Copy(f, r.Body); err != nil {
  148. return http.StatusMethodNotAllowed, err
  149. }
  150. return http.StatusCreated, nil
  151. }
  152. func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status int, err error) {
  153. releaser, status, err := h.confirmLocks(r)
  154. if err != nil {
  155. return status, err
  156. }
  157. defer releaser.Release()
  158. if r.ContentLength > 0 {
  159. return http.StatusUnsupportedMediaType, nil
  160. }
  161. if err := h.FileSystem.Mkdir(r.URL.Path, 0777); err != nil {
  162. if os.IsNotExist(err) {
  163. return http.StatusConflict, err
  164. }
  165. return http.StatusMethodNotAllowed, err
  166. }
  167. return http.StatusCreated, nil
  168. }
  169. func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) {
  170. duration, err := parseTimeout(r.Header.Get("Timeout"))
  171. if err != nil {
  172. return http.StatusBadRequest, err
  173. }
  174. li, status, err := readLockInfo(r.Body)
  175. if err != nil {
  176. return status, err
  177. }
  178. token, ld, now := "", LockDetails{}, time.Now()
  179. if li == (lockInfo{}) {
  180. // An empty lockInfo means to refresh the lock.
  181. ih, ok := parseIfHeader(r.Header.Get("If"))
  182. if !ok {
  183. return http.StatusBadRequest, errInvalidIfHeader
  184. }
  185. if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 {
  186. token = ih.lists[0].conditions[0].Token
  187. }
  188. if token == "" {
  189. return http.StatusBadRequest, errInvalidLockToken
  190. }
  191. ld, err = h.LockSystem.Refresh(now, token, duration)
  192. if err != nil {
  193. if err == ErrNoSuchLock {
  194. return http.StatusPreconditionFailed, err
  195. }
  196. return http.StatusInternalServerError, err
  197. }
  198. } else {
  199. // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request,
  200. // then the request MUST act as if a "Depth:infinity" had been submitted."
  201. depth := infiniteDepth
  202. if hdr := r.Header.Get("Depth"); hdr != "" {
  203. depth = parseDepth(hdr)
  204. if depth != 0 && depth != infiniteDepth {
  205. // Section 9.10.3 says that "Values other than 0 or infinity must not be
  206. // used with the Depth header on a LOCK method".
  207. return http.StatusBadRequest, errInvalidDepth
  208. }
  209. }
  210. ld = LockDetails{
  211. Root: r.URL.Path,
  212. Duration: duration,
  213. OwnerXML: li.Owner.InnerXML,
  214. ZeroDepth: depth == 0,
  215. }
  216. token, err = h.LockSystem.Create(now, ld)
  217. if err != nil {
  218. if err == ErrLocked {
  219. return StatusLocked, err
  220. }
  221. return http.StatusInternalServerError, err
  222. }
  223. defer func() {
  224. if retErr != nil {
  225. h.LockSystem.Unlock(now, token)
  226. }
  227. }()
  228. // Create the resource if it didn't previously exist.
  229. if _, err := h.FileSystem.Stat(r.URL.Path); err != nil {
  230. f, err := h.FileSystem.OpenFile(r.URL.Path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
  231. if err != nil {
  232. // TODO: detect missing intermediate dirs and return http.StatusConflict?
  233. return http.StatusInternalServerError, err
  234. }
  235. f.Close()
  236. w.WriteHeader(http.StatusCreated)
  237. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  238. // Lock-Token value is a Coded-URL. We add angle brackets.
  239. w.Header().Set("Lock-Token", "<"+token+">")
  240. }
  241. }
  242. w.Header().Set("Content-Type", "application/xml; charset=utf-8")
  243. writeLockInfo(w, token, ld)
  244. return 0, nil
  245. }
  246. func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) {
  247. // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the
  248. // Lock-Token value is a Coded-URL. We strip its angle brackets.
  249. t := r.Header.Get("Lock-Token")
  250. if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' {
  251. return http.StatusBadRequest, errInvalidLockToken
  252. }
  253. t = t[1 : len(t)-1]
  254. switch err = h.LockSystem.Unlock(time.Now(), t); err {
  255. case nil:
  256. return http.StatusNoContent, err
  257. case ErrForbidden:
  258. return http.StatusForbidden, err
  259. case ErrLocked:
  260. return StatusLocked, err
  261. case ErrNoSuchLock:
  262. return http.StatusConflict, err
  263. default:
  264. return http.StatusInternalServerError, err
  265. }
  266. }
  267. const (
  268. infiniteDepth = -1
  269. invalidDepth = -2
  270. )
  271. // parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and
  272. // infiniteDepth. Parsing any other string returns invalidDepth.
  273. //
  274. // Different WebDAV methods have further constraints on valid depths:
  275. // - PROPFIND has no further restrictions, as per section 9.1.
  276. // - MOVE accepts only "infinity", as per section 9.2.2.
  277. // - LOCK accepts only "0" or "infinity", as per section 9.10.3.
  278. // These constraints are enforced by the handleXxx methods.
  279. func parseDepth(s string) int {
  280. switch s {
  281. case "0":
  282. return 0
  283. case "1":
  284. return 1
  285. case "infinity":
  286. return infiniteDepth
  287. }
  288. return invalidDepth
  289. }
  290. func parseTimeout(s string) (time.Duration, error) {
  291. // TODO: implement.
  292. return 1 * time.Second, nil
  293. }
  294. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11
  295. const (
  296. StatusMulti = 207
  297. StatusUnprocessableEntity = 422
  298. StatusLocked = 423
  299. StatusFailedDependency = 424
  300. StatusInsufficientStorage = 507
  301. )
  302. func StatusText(code int) string {
  303. switch code {
  304. case StatusMulti:
  305. return "Multi-Status"
  306. case StatusUnprocessableEntity:
  307. return "Unprocessable Entity"
  308. case StatusLocked:
  309. return "Locked"
  310. case StatusFailedDependency:
  311. return "Failed Dependency"
  312. case StatusInsufficientStorage:
  313. return "Insufficient Storage"
  314. }
  315. return http.StatusText(code)
  316. }
  317. var (
  318. errInvalidDepth = errors.New("webdav: invalid depth")
  319. errInvalidIfHeader = errors.New("webdav: invalid If header")
  320. errInvalidLockInfo = errors.New("webdav: invalid lock info")
  321. errInvalidLockToken = errors.New("webdav: invalid lock token")
  322. errNoFileSystem = errors.New("webdav: no file system")
  323. errNoLockSystem = errors.New("webdav: no lock system")
  324. errUnsupportedLockInfo = errors.New("webdav: unsupported lock info")
  325. )