prop.go 12 KB

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