You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

470 lines
15 KiB

  1. // Copyright 2015 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
  5. import (
  6. "bytes"
  7. "context"
  8. "encoding/xml"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "mime"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. )
  18. // Proppatch describes a property update instruction as defined in RFC 4918.
  19. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
  20. type Proppatch struct {
  21. // Remove specifies whether this patch removes properties. If it does not
  22. // remove them, it sets them.
  23. Remove bool
  24. // Props contains the properties to be set or removed.
  25. Props []Property
  26. }
  27. // Propstat describes a XML propstat element as defined in RFC 4918.
  28. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat
  29. type Propstat struct {
  30. // Props contains the properties for which Status applies.
  31. Props []Property
  32. // Status defines the HTTP status code of the properties in Prop.
  33. // Allowed values include, but are not limited to the WebDAV status
  34. // code extensions for HTTP/1.1.
  35. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11
  36. Status int
  37. // XMLError contains the XML representation of the optional error element.
  38. // XML content within this field must not rely on any predefined
  39. // namespace declarations or prefixes. If empty, the XML error element
  40. // is omitted.
  41. XMLError string
  42. // ResponseDescription contains the contents of the optional
  43. // responsedescription field. If empty, the XML element is omitted.
  44. ResponseDescription string
  45. }
  46. // makePropstats returns a slice containing those of x and y whose Props slice
  47. // is non-empty. If both are empty, it returns a slice containing an otherwise
  48. // zero Propstat whose HTTP status code is 200 OK.
  49. func makePropstats(x, y Propstat) []Propstat {
  50. pstats := make([]Propstat, 0, 2)
  51. if len(x.Props) != 0 {
  52. pstats = append(pstats, x)
  53. }
  54. if len(y.Props) != 0 {
  55. pstats = append(pstats, y)
  56. }
  57. if len(pstats) == 0 {
  58. pstats = append(pstats, Propstat{
  59. Status: http.StatusOK,
  60. })
  61. }
  62. return pstats
  63. }
  64. // DeadPropsHolder holds the dead properties of a resource.
  65. //
  66. // Dead properties are those properties that are explicitly defined. In
  67. // comparison, live properties, such as DAV:getcontentlength, are implicitly
  68. // defined by the underlying resource, and cannot be explicitly overridden or
  69. // removed. See the Terminology section of
  70. // http://www.webdav.org/specs/rfc4918.html#rfc.section.3
  71. //
  72. // There is a whitelist of the names of live properties. This package handles
  73. // all live properties, and will only pass non-whitelisted names to the Patch
  74. // method of DeadPropsHolder implementations.
  75. type DeadPropsHolder interface {
  76. // DeadProps returns a copy of the dead properties held.
  77. DeadProps() (map[xml.Name]Property, error)
  78. // Patch patches the dead properties held.
  79. //
  80. // Patching is atomic; either all or no patches succeed. It returns (nil,
  81. // non-nil) if an internal server error occurred, otherwise the Propstats
  82. // collectively contain one Property for each proposed patch Property. If
  83. // all patches succeed, Patch returns a slice of length one and a Propstat
  84. // element with a 200 OK HTTP status code. If none succeed, for reasons
  85. // other than an internal server error, no Propstat has status 200 OK.
  86. //
  87. // For more details on when various HTTP status codes apply, see
  88. // http://www.webdav.org/specs/rfc4918.html#PROPPATCH-status
  89. Patch([]Proppatch) ([]Propstat, error)
  90. }
  91. // liveProps contains all supported, protected DAV: properties.
  92. var liveProps = map[xml.Name]struct {
  93. // findFn implements the propfind function of this property. If nil,
  94. // it indicates a hidden property.
  95. findFn func(context.Context, FileSystem, LockSystem, string, os.FileInfo) (string, error)
  96. // dir is true if the property applies to directories.
  97. dir bool
  98. }{
  99. {Space: "DAV:", Local: "resourcetype"}: {
  100. findFn: findResourceType,
  101. dir: true,
  102. },
  103. {Space: "DAV:", Local: "displayname"}: {
  104. findFn: findDisplayName,
  105. dir: true,
  106. },
  107. {Space: "DAV:", Local: "getcontentlength"}: {
  108. findFn: findContentLength,
  109. dir: false,
  110. },
  111. {Space: "DAV:", Local: "getlastmodified"}: {
  112. findFn: findLastModified,
  113. // http://webdav.org/specs/rfc4918.html#PROPERTY_getlastmodified
  114. // suggests that getlastmodified should only apply to GETable
  115. // resources, and this package does not support GET on directories.
  116. //
  117. // Nonetheless, some WebDAV clients expect child directories to be
  118. // sortable by getlastmodified date, so this value is true, not false.
  119. // See golang.org/issue/15334.
  120. dir: true,
  121. },
  122. {Space: "DAV:", Local: "creationdate"}: {
  123. findFn: nil,
  124. dir: false,
  125. },
  126. {Space: "DAV:", Local: "getcontentlanguage"}: {
  127. findFn: nil,
  128. dir: false,
  129. },
  130. {Space: "DAV:", Local: "getcontenttype"}: {
  131. findFn: findContentType,
  132. dir: false,
  133. },
  134. {Space: "DAV:", Local: "getetag"}: {
  135. findFn: findETag,
  136. // findETag implements ETag as the concatenated hex values of a file's
  137. // modification time and size. This is not a reliable synchronization
  138. // mechanism for directories, so we do not advertise getetag for DAV
  139. // collections.
  140. dir: false,
  141. },
  142. // TODO: The lockdiscovery property requires LockSystem to list the
  143. // active locks on a resource.
  144. {Space: "DAV:", Local: "lockdiscovery"}: {},
  145. {Space: "DAV:", Local: "supportedlock"}: {
  146. findFn: findSupportedLock,
  147. dir: true,
  148. },
  149. }
  150. // TODO(nigeltao) merge props and allprop?
  151. // Props returns the status of the properties named pnames for resource name.
  152. //
  153. // Each Propstat has a unique status and each property name will only be part
  154. // of one Propstat element.
  155. func props(ctx context.Context, fs FileSystem, ls LockSystem, name string, pnames []xml.Name) ([]Propstat, error) {
  156. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0)
  157. if err != nil {
  158. return nil, err
  159. }
  160. defer f.Close()
  161. fi, err := f.Stat()
  162. if err != nil {
  163. return nil, err
  164. }
  165. isDir := fi.IsDir()
  166. var deadProps map[xml.Name]Property
  167. if dph, ok := f.(DeadPropsHolder); ok {
  168. deadProps, err = dph.DeadProps()
  169. if err != nil {
  170. return nil, err
  171. }
  172. }
  173. pstatOK := Propstat{Status: http.StatusOK}
  174. pstatNotFound := Propstat{Status: http.StatusNotFound}
  175. for _, pn := range pnames {
  176. // If this file has dead properties, check if they contain pn.
  177. if dp, ok := deadProps[pn]; ok {
  178. pstatOK.Props = append(pstatOK.Props, dp)
  179. continue
  180. }
  181. // Otherwise, it must either be a live property or we don't know it.
  182. if prop := liveProps[pn]; prop.findFn != nil && (prop.dir || !isDir) {
  183. innerXML, err := prop.findFn(ctx, fs, ls, name, fi)
  184. if err != nil {
  185. return nil, err
  186. }
  187. pstatOK.Props = append(pstatOK.Props, Property{
  188. XMLName: pn,
  189. InnerXML: []byte(innerXML),
  190. })
  191. } else {
  192. pstatNotFound.Props = append(pstatNotFound.Props, Property{
  193. XMLName: pn,
  194. })
  195. }
  196. }
  197. return makePropstats(pstatOK, pstatNotFound), nil
  198. }
  199. // Propnames returns the property names defined for resource name.
  200. func propnames(ctx context.Context, fs FileSystem, ls LockSystem, name string) ([]xml.Name, error) {
  201. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0)
  202. if err != nil {
  203. return nil, err
  204. }
  205. defer f.Close()
  206. fi, err := f.Stat()
  207. if err != nil {
  208. return nil, err
  209. }
  210. isDir := fi.IsDir()
  211. var deadProps map[xml.Name]Property
  212. if dph, ok := f.(DeadPropsHolder); ok {
  213. deadProps, err = dph.DeadProps()
  214. if err != nil {
  215. return nil, err
  216. }
  217. }
  218. pnames := make([]xml.Name, 0, len(liveProps)+len(deadProps))
  219. for pn, prop := range liveProps {
  220. if prop.findFn != nil && (prop.dir || !isDir) {
  221. pnames = append(pnames, pn)
  222. }
  223. }
  224. for pn := range deadProps {
  225. pnames = append(pnames, pn)
  226. }
  227. return pnames, nil
  228. }
  229. // Allprop returns the properties defined for resource name and the properties
  230. // named in include.
  231. //
  232. // Note that RFC 4918 defines 'allprop' to return the DAV: properties defined
  233. // within the RFC plus dead properties. Other live properties should only be
  234. // returned if they are named in 'include'.
  235. //
  236. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
  237. func allprop(ctx context.Context, fs FileSystem, ls LockSystem, name string, include []xml.Name) ([]Propstat, error) {
  238. pnames, err := propnames(ctx, fs, ls, name)
  239. if err != nil {
  240. return nil, err
  241. }
  242. // Add names from include if they are not already covered in pnames.
  243. nameset := make(map[xml.Name]bool)
  244. for _, pn := range pnames {
  245. nameset[pn] = true
  246. }
  247. for _, pn := range include {
  248. if !nameset[pn] {
  249. pnames = append(pnames, pn)
  250. }
  251. }
  252. return props(ctx, fs, ls, name, pnames)
  253. }
  254. // Patch patches the properties of resource name. The return values are
  255. // constrained in the same manner as DeadPropsHolder.Patch.
  256. func patch(ctx context.Context, fs FileSystem, ls LockSystem, name string, patches []Proppatch) ([]Propstat, error) {
  257. conflict := false
  258. loop:
  259. for _, patch := range patches {
  260. for _, p := range patch.Props {
  261. if _, ok := liveProps[p.XMLName]; ok {
  262. conflict = true
  263. break loop
  264. }
  265. }
  266. }
  267. if conflict {
  268. pstatForbidden := Propstat{
  269. Status: http.StatusForbidden,
  270. XMLError: `<D:cannot-modify-protected-property xmlns:D="DAV:"/>`,
  271. }
  272. pstatFailedDep := Propstat{
  273. Status: StatusFailedDependency,
  274. }
  275. for _, patch := range patches {
  276. for _, p := range patch.Props {
  277. if _, ok := liveProps[p.XMLName]; ok {
  278. pstatForbidden.Props = append(pstatForbidden.Props, Property{XMLName: p.XMLName})
  279. } else {
  280. pstatFailedDep.Props = append(pstatFailedDep.Props, Property{XMLName: p.XMLName})
  281. }
  282. }
  283. }
  284. return makePropstats(pstatForbidden, pstatFailedDep), nil
  285. }
  286. f, err := fs.OpenFile(ctx, name, os.O_RDWR, 0)
  287. if err != nil {
  288. return nil, err
  289. }
  290. defer f.Close()
  291. if dph, ok := f.(DeadPropsHolder); ok {
  292. ret, err := dph.Patch(patches)
  293. if err != nil {
  294. return nil, err
  295. }
  296. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat says that
  297. // "The contents of the prop XML element must only list the names of
  298. // properties to which the result in the status element applies."
  299. for _, pstat := range ret {
  300. for i, p := range pstat.Props {
  301. pstat.Props[i] = Property{XMLName: p.XMLName}
  302. }
  303. }
  304. return ret, nil
  305. }
  306. // The file doesn't implement the optional DeadPropsHolder interface, so
  307. // all patches are forbidden.
  308. pstat := Propstat{Status: http.StatusForbidden}
  309. for _, patch := range patches {
  310. for _, p := range patch.Props {
  311. pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName})
  312. }
  313. }
  314. return []Propstat{pstat}, nil
  315. }
  316. func escapeXML(s string) string {
  317. for i := 0; i < len(s); i++ {
  318. // As an optimization, if s contains only ASCII letters, digits or a
  319. // few special characters, the escaped value is s itself and we don't
  320. // need to allocate a buffer and convert between string and []byte.
  321. switch c := s[i]; {
  322. case c == ' ' || c == '_' ||
  323. ('+' <= c && c <= '9') || // Digits as well as + , - . and /
  324. ('A' <= c && c <= 'Z') ||
  325. ('a' <= c && c <= 'z'):
  326. continue
  327. }
  328. // Otherwise, go through the full escaping process.
  329. var buf bytes.Buffer
  330. xml.EscapeText(&buf, []byte(s))
  331. return buf.String()
  332. }
  333. return s
  334. }
  335. func findResourceType(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  336. if fi.IsDir() {
  337. return `<D:collection xmlns:D="DAV:"/>`, nil
  338. }
  339. return "", nil
  340. }
  341. func findDisplayName(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  342. if slashClean(name) == "/" {
  343. // Hide the real name of a possibly prefixed root directory.
  344. return "", nil
  345. }
  346. return escapeXML(fi.Name()), nil
  347. }
  348. func findContentLength(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  349. return strconv.FormatInt(fi.Size(), 10), nil
  350. }
  351. func findLastModified(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  352. return fi.ModTime().UTC().Format(http.TimeFormat), nil
  353. }
  354. // ErrNotImplemented should be returned by optional interfaces if they
  355. // want the original implementation to be used.
  356. var ErrNotImplemented = errors.New("not implemented")
  357. // ContentTyper is an optional interface for the os.FileInfo
  358. // objects returned by the FileSystem.
  359. //
  360. // If this interface is defined then it will be used to read the
  361. // content type from the object.
  362. //
  363. // If this interface is not defined the file will be opened and the
  364. // content type will be guessed from the initial contents of the file.
  365. type ContentTyper interface {
  366. // ContentType returns the content type for the file.
  367. //
  368. // If this returns error ErrNotImplemented then the error will
  369. // be ignored and the base implementation will be used
  370. // instead.
  371. ContentType(ctx context.Context) (string, error)
  372. }
  373. func findContentType(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  374. if do, ok := fi.(ContentTyper); ok {
  375. ctype, err := do.ContentType(ctx)
  376. if err != ErrNotImplemented {
  377. return ctype, err
  378. }
  379. }
  380. f, err := fs.OpenFile(ctx, name, os.O_RDONLY, 0)
  381. if err != nil {
  382. return "", err
  383. }
  384. defer f.Close()
  385. // This implementation is based on serveContent's code in the standard net/http package.
  386. ctype := mime.TypeByExtension(filepath.Ext(name))
  387. if ctype != "" {
  388. return ctype, nil
  389. }
  390. // Read a chunk to decide between utf-8 text and binary.
  391. var buf [512]byte
  392. n, err := io.ReadFull(f, buf[:])
  393. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  394. return "", err
  395. }
  396. ctype = http.DetectContentType(buf[:n])
  397. // Rewind file.
  398. _, err = f.Seek(0, os.SEEK_SET)
  399. return ctype, err
  400. }
  401. // ETager is an optional interface for the os.FileInfo objects
  402. // returned by the FileSystem.
  403. //
  404. // If this interface is defined then it will be used to read the ETag
  405. // for the object.
  406. //
  407. // If this interface is not defined an ETag will be computed using the
  408. // ModTime() and the Size() methods of the os.FileInfo object.
  409. type ETager interface {
  410. // ETag returns an ETag for the file. This should be of the
  411. // form "value" or W/"value"
  412. //
  413. // If this returns error ErrNotImplemented then the error will
  414. // be ignored and the base implementation will be used
  415. // instead.
  416. ETag(ctx context.Context) (string, error)
  417. }
  418. func findETag(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  419. if do, ok := fi.(ETager); ok {
  420. etag, err := do.ETag(ctx)
  421. if err != ErrNotImplemented {
  422. return etag, err
  423. }
  424. }
  425. // The Apache http 2.4 web server by default concatenates the
  426. // modification time and size of a file. We replicate the heuristic
  427. // with nanosecond granularity.
  428. return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size()), nil
  429. }
  430. func findSupportedLock(ctx context.Context, fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  431. return `` +
  432. `<D:lockentry xmlns:D="DAV:">` +
  433. `<D:lockscope><D:exclusive/></D:lockscope>` +
  434. `<D:locktype><D:write/></D:locktype>` +
  435. `</D:lockentry>`, nil
  436. }