prop.go 13 KB

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