prop.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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
  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: true,
  107. },
  108. xml.Name{Space: "DAV:", Local: "getlastmodified"}: {
  109. findFn: findLastModified,
  110. dir: true,
  111. },
  112. xml.Name{Space: "DAV:", Local: "creationdate"}: {
  113. findFn: nil,
  114. dir: true,
  115. },
  116. xml.Name{Space: "DAV:", Local: "getcontentlanguage"}: {
  117. findFn: nil,
  118. dir: true,
  119. },
  120. xml.Name{Space: "DAV:", Local: "getcontenttype"}: {
  121. findFn: findContentType,
  122. dir: true,
  123. },
  124. xml.Name{Space: "DAV:", Local: "getetag"}: {
  125. findFn: findETag,
  126. // findETag implements ETag as the concatenated hex values of a file's
  127. // modification time and size. This is not a reliable synchronization
  128. // mechanism for directories, so we do not advertise getetag for DAV
  129. // collections.
  130. dir: false,
  131. },
  132. // TODO(nigeltao) Lock properties will be defined later.
  133. xml.Name{Space: "DAV:", Local: "lockdiscovery"}: {},
  134. xml.Name{Space: "DAV:", Local: "supportedlock"}: {},
  135. }
  136. // TODO(nigeltao) merge props and allprop?
  137. // Props returns the status of the properties named pnames for resource name.
  138. //
  139. // Each Propstat has a unique status and each property name will only be part
  140. // of one Propstat element.
  141. func props(fs FileSystem, ls LockSystem, name string, pnames []xml.Name) ([]Propstat, error) {
  142. f, err := fs.OpenFile(name, os.O_RDONLY, 0)
  143. if err != nil {
  144. return nil, err
  145. }
  146. defer f.Close()
  147. fi, err := f.Stat()
  148. if err != nil {
  149. return nil, err
  150. }
  151. isDir := fi.IsDir()
  152. var deadProps map[xml.Name]Property
  153. if dph, ok := f.(DeadPropsHolder); ok {
  154. deadProps = dph.DeadProps()
  155. }
  156. pstatOK := Propstat{Status: http.StatusOK}
  157. pstatNotFound := Propstat{Status: http.StatusNotFound}
  158. for _, pn := range pnames {
  159. // If this file has dead properties, check if they contain pn.
  160. if dp, ok := deadProps[pn]; ok {
  161. pstatOK.Props = append(pstatOK.Props, dp)
  162. continue
  163. }
  164. // Otherwise, it must either be a live property or we don't know it.
  165. if prop := liveProps[pn]; prop.findFn != nil && (prop.dir || !isDir) {
  166. innerXML, err := prop.findFn(fs, ls, name, fi)
  167. if err != nil {
  168. return nil, err
  169. }
  170. pstatOK.Props = append(pstatOK.Props, Property{
  171. XMLName: pn,
  172. InnerXML: []byte(innerXML),
  173. })
  174. } else {
  175. pstatNotFound.Props = append(pstatNotFound.Props, Property{
  176. XMLName: pn,
  177. })
  178. }
  179. }
  180. return makePropstats(pstatOK, pstatNotFound), nil
  181. }
  182. // Propnames returns the property names defined for resource name.
  183. func propnames(fs FileSystem, ls LockSystem, name string) ([]xml.Name, error) {
  184. f, err := fs.OpenFile(name, os.O_RDONLY, 0)
  185. if err != nil {
  186. return nil, err
  187. }
  188. defer f.Close()
  189. fi, err := f.Stat()
  190. if err != nil {
  191. return nil, err
  192. }
  193. isDir := fi.IsDir()
  194. var deadProps map[xml.Name]Property
  195. if dph, ok := f.(DeadPropsHolder); ok {
  196. deadProps = dph.DeadProps()
  197. }
  198. pnames := make([]xml.Name, 0, len(liveProps)+len(deadProps))
  199. for pn, prop := range liveProps {
  200. if prop.findFn != nil && (prop.dir || !isDir) {
  201. pnames = append(pnames, pn)
  202. }
  203. }
  204. for pn := range deadProps {
  205. pnames = append(pnames, pn)
  206. }
  207. return pnames, nil
  208. }
  209. // Allprop returns the properties defined for resource name and the properties
  210. // named in include.
  211. //
  212. // Note that RFC 4918 defines 'allprop' to return the DAV: properties defined
  213. // within the RFC plus dead properties. Other live properties should only be
  214. // returned if they are named in 'include'.
  215. //
  216. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
  217. func allprop(fs FileSystem, ls LockSystem, name string, include []xml.Name) ([]Propstat, error) {
  218. pnames, err := propnames(fs, ls, name)
  219. if err != nil {
  220. return nil, err
  221. }
  222. // Add names from include if they are not already covered in pnames.
  223. nameset := make(map[xml.Name]bool)
  224. for _, pn := range pnames {
  225. nameset[pn] = true
  226. }
  227. for _, pn := range include {
  228. if !nameset[pn] {
  229. pnames = append(pnames, pn)
  230. }
  231. }
  232. return props(fs, ls, name, pnames)
  233. }
  234. // Patch patches the properties of resource name. The return values are
  235. // constrained in the same manner as DeadPropsHolder.Patch.
  236. func patch(fs FileSystem, ls LockSystem, name string, patches []Proppatch) ([]Propstat, error) {
  237. conflict := false
  238. loop:
  239. for _, patch := range patches {
  240. for _, p := range patch.Props {
  241. if _, ok := liveProps[p.XMLName]; ok {
  242. conflict = true
  243. break loop
  244. }
  245. }
  246. }
  247. if conflict {
  248. pstatForbidden := Propstat{
  249. Status: http.StatusForbidden,
  250. XMLError: `<error xmlns="DAV:"><cannot-modify-protected-property/></error>`,
  251. }
  252. pstatFailedDep := Propstat{
  253. Status: StatusFailedDependency,
  254. }
  255. for _, patch := range patches {
  256. for _, p := range patch.Props {
  257. if _, ok := liveProps[p.XMLName]; ok {
  258. pstatForbidden.Props = append(pstatForbidden.Props, Property{XMLName: p.XMLName})
  259. } else {
  260. pstatFailedDep.Props = append(pstatFailedDep.Props, Property{XMLName: p.XMLName})
  261. }
  262. }
  263. }
  264. return makePropstats(pstatForbidden, pstatFailedDep), nil
  265. }
  266. f, err := fs.OpenFile(name, os.O_RDWR, 0)
  267. if err != nil {
  268. return nil, err
  269. }
  270. defer f.Close()
  271. if dph, ok := f.(DeadPropsHolder); ok {
  272. ret, err := dph.Patch(patches)
  273. if err != nil {
  274. return nil, err
  275. }
  276. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat says that
  277. // "The contents of the prop XML element must only list the names of
  278. // properties to which the result in the status element applies."
  279. for _, pstat := range ret {
  280. for i, p := range pstat.Props {
  281. pstat.Props[i] = Property{XMLName: p.XMLName}
  282. }
  283. }
  284. return ret, nil
  285. }
  286. // The file doesn't implement the optional DeadPropsHolder interface, so
  287. // all patches are forbidden.
  288. pstat := Propstat{Status: http.StatusForbidden}
  289. for _, patch := range patches {
  290. for _, p := range patch.Props {
  291. pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName})
  292. }
  293. }
  294. return []Propstat{pstat}, nil
  295. }
  296. func findResourceType(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  297. if fi.IsDir() {
  298. return `<collection xmlns="DAV:"/>`, nil
  299. }
  300. return "", nil
  301. }
  302. func findDisplayName(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  303. if slashClean(name) == "/" {
  304. // Hide the real name of a possibly prefixed root directory.
  305. return "", nil
  306. }
  307. return fi.Name(), nil
  308. }
  309. func findContentLength(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  310. return strconv.FormatInt(fi.Size(), 10), nil
  311. }
  312. func findLastModified(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  313. return fi.ModTime().Format(http.TimeFormat), nil
  314. }
  315. func findContentType(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  316. f, err := fs.OpenFile(name, os.O_RDONLY, 0)
  317. if err != nil {
  318. return "", err
  319. }
  320. defer f.Close()
  321. // This implementation is based on serveContent's code in the standard net/http package.
  322. ctype := mime.TypeByExtension(filepath.Ext(name))
  323. if ctype == "" {
  324. // Read a chunk to decide between utf-8 text and binary.
  325. var buf [512]byte
  326. n, _ := io.ReadFull(f, buf[:])
  327. ctype = http.DetectContentType(buf[:n])
  328. // Rewind file.
  329. _, err = f.Seek(0, os.SEEK_SET)
  330. }
  331. return ctype, err
  332. }
  333. func findETag(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) {
  334. return detectETag(fi), nil
  335. }
  336. // detectETag determines the ETag for the file described by fi.
  337. func detectETag(fi os.FileInfo) string {
  338. // The Apache http 2.4 web server by default concatenates the
  339. // modification time and size of a file. We replicate the heuristic
  340. // with nanosecond granularity.
  341. return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size())
  342. }