prop.go 12 KB

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