prop.go 12 KB

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