prop.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. // PropSystem manages the properties of named resources. It allows finding
  16. // and setting properties as defined in RFC 4918.
  17. //
  18. // The elements in a resource name are separated by slash ('/', U+002F)
  19. // characters, regardless of host operating system convention.
  20. type PropSystem interface {
  21. // Find returns the status of properties named propnames for resource name.
  22. //
  23. // Each Propstat must have a unique status and each property name must
  24. // only be part of one Propstat element.
  25. Find(name string, propnames []xml.Name) ([]Propstat, error)
  26. // TODO(nigeltao) merge Find and Allprop?
  27. // Allprop returns the properties defined for resource name and the
  28. // properties named in include. The returned Propstats are handled
  29. // as in Find.
  30. //
  31. // Note that RFC 4918 defines 'allprop' to return the DAV: properties
  32. // defined within the RFC plus dead properties. Other live properties
  33. // should only be returned if they are named in 'include'.
  34. //
  35. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
  36. Allprop(name string, include []xml.Name) ([]Propstat, error)
  37. // Propnames returns the property names defined for resource name.
  38. Propnames(name string) ([]xml.Name, error)
  39. // Patch patches the properties of resource name.
  40. //
  41. // If all patches can be applied without conflict, Patch returns a slice
  42. // of length one and a Propstat element of status 200, naming all patched
  43. // properties. In case of conflict, Patch returns an arbitrary long slice
  44. // and no Propstat element must have status 200. In either case, properties
  45. // in Propstat must not have values.
  46. //
  47. // Note that the WebDAV RFC requires either all patches to succeed or none.
  48. Patch(name string, patches []Proppatch) ([]Propstat, error)
  49. // TODO(rost) COPY/MOVE/DELETE.
  50. }
  51. // Proppatch describes a property update instruction as defined in RFC 4918.
  52. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH
  53. type Proppatch struct {
  54. // Remove specifies whether this patch removes properties. If it does not
  55. // remove them, it sets them.
  56. Remove bool
  57. // Props contains the properties to be set or removed.
  58. Props []Property
  59. }
  60. // Propstat describes a XML propstat element as defined in RFC 4918.
  61. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat
  62. type Propstat struct {
  63. // Props contains the properties for which Status applies.
  64. Props []Property
  65. // Status defines the HTTP status code of the properties in Prop.
  66. // Allowed values include, but are not limited to the WebDAV status
  67. // code extensions for HTTP/1.1.
  68. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11
  69. Status int
  70. // XMLError contains the XML representation of the optional error element.
  71. // XML content within this field must not rely on any predefined
  72. // namespace declarations or prefixes. If empty, the XML error element
  73. // is omitted.
  74. XMLError string
  75. // ResponseDescription contains the contents of the optional
  76. // responsedescription field. If empty, the XML element is omitted.
  77. ResponseDescription string
  78. }
  79. // memPS implements an in-memory PropSystem. It supports all of the mandatory
  80. // live properties of RFC 4918.
  81. type memPS struct {
  82. fs FileSystem
  83. ls LockSystem
  84. }
  85. // NewMemPS returns a new in-memory PropSystem implementation.
  86. func NewMemPS(fs FileSystem, ls LockSystem) PropSystem {
  87. return &memPS{fs: fs, ls: ls}
  88. }
  89. // davProps contains all supported DAV: properties and their optional
  90. // propfind functions. A nil findFn indicates a hidden, protected property.
  91. // The dir field indicates if the property applies to directories in addition
  92. // to regular files.
  93. var davProps = map[xml.Name]struct {
  94. findFn func(*memPS, string, os.FileInfo) (string, error)
  95. dir bool
  96. }{
  97. xml.Name{Space: "DAV:", Local: "resourcetype"}: {
  98. findFn: (*memPS).findResourceType,
  99. dir: true,
  100. },
  101. xml.Name{Space: "DAV:", Local: "displayname"}: {
  102. findFn: (*memPS).findDisplayName,
  103. dir: true,
  104. },
  105. xml.Name{Space: "DAV:", Local: "getcontentlength"}: {
  106. findFn: (*memPS).findContentLength,
  107. dir: true,
  108. },
  109. xml.Name{Space: "DAV:", Local: "getlastmodified"}: {
  110. findFn: (*memPS).findLastModified,
  111. dir: true,
  112. },
  113. xml.Name{Space: "DAV:", Local: "creationdate"}: {
  114. findFn: nil,
  115. dir: true,
  116. },
  117. xml.Name{Space: "DAV:", Local: "getcontentlanguage"}: {
  118. findFn: nil,
  119. dir: true,
  120. },
  121. xml.Name{Space: "DAV:", Local: "getcontenttype"}: {
  122. findFn: (*memPS).findContentType,
  123. dir: true,
  124. },
  125. // memPS implements ETag as the concatenated hex values of a file's
  126. // modification time and size. This is not a reliable synchronization
  127. // mechanism for directories, so we do not advertise getetag for
  128. // DAV collections.
  129. xml.Name{Space: "DAV:", Local: "getetag"}: {
  130. findFn: (*memPS).findETag,
  131. dir: false,
  132. },
  133. // TODO(nigeltao) Lock properties will be defined later.
  134. // xml.Name{Space: "DAV:", Local: "lockdiscovery"}
  135. // xml.Name{Space: "DAV:", Local: "supportedlock"}
  136. }
  137. func (ps *memPS) Find(name string, propnames []xml.Name) ([]Propstat, error) {
  138. fi, err := ps.fs.Stat(name)
  139. if err != nil {
  140. return nil, err
  141. }
  142. pm := make(map[int]Propstat)
  143. for _, pn := range propnames {
  144. p := Property{XMLName: pn}
  145. s := http.StatusNotFound
  146. if prop := davProps[pn]; prop.findFn != nil && (prop.dir || !fi.IsDir()) {
  147. xmlvalue, err := prop.findFn(ps, name, fi)
  148. if err != nil {
  149. return nil, err
  150. }
  151. s = http.StatusOK
  152. p.InnerXML = []byte(xmlvalue)
  153. }
  154. pstat := pm[s]
  155. pstat.Props = append(pstat.Props, p)
  156. pm[s] = pstat
  157. }
  158. pstats := make([]Propstat, 0, len(pm))
  159. for s, pstat := range pm {
  160. pstat.Status = s
  161. pstats = append(pstats, pstat)
  162. }
  163. return pstats, nil
  164. }
  165. func (ps *memPS) Propnames(name string) ([]xml.Name, error) {
  166. fi, err := ps.fs.Stat(name)
  167. if err != nil {
  168. return nil, err
  169. }
  170. propnames := make([]xml.Name, 0, len(davProps))
  171. for pn, prop := range davProps {
  172. if prop.findFn != nil && (prop.dir || !fi.IsDir()) {
  173. propnames = append(propnames, pn)
  174. }
  175. }
  176. return propnames, nil
  177. }
  178. func (ps *memPS) Allprop(name string, include []xml.Name) ([]Propstat, error) {
  179. propnames, err := ps.Propnames(name)
  180. if err != nil {
  181. return nil, err
  182. }
  183. // Add names from include if they are not already covered in propnames.
  184. nameset := make(map[xml.Name]bool)
  185. for _, pn := range propnames {
  186. nameset[pn] = true
  187. }
  188. for _, pn := range include {
  189. if !nameset[pn] {
  190. propnames = append(propnames, pn)
  191. }
  192. }
  193. return ps.Find(name, propnames)
  194. }
  195. func (ps *memPS) Patch(name string, patches []Proppatch) ([]Propstat, error) {
  196. // TODO(rost): Support to patch "dead" DAV properties in the next CL.
  197. pstat := Propstat{Status: http.StatusForbidden}
  198. for _, patch := range patches {
  199. for _, p := range patch.Props {
  200. pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName})
  201. }
  202. }
  203. return []Propstat{pstat}, nil
  204. }
  205. func (ps *memPS) findResourceType(name string, fi os.FileInfo) (string, error) {
  206. if fi.IsDir() {
  207. return `<collection xmlns="DAV:"/>`, nil
  208. }
  209. return "", nil
  210. }
  211. func (ps *memPS) findDisplayName(name string, fi os.FileInfo) (string, error) {
  212. if slashClean(name) == "/" {
  213. // Hide the real name of a possibly prefixed root directory.
  214. return "", nil
  215. }
  216. return fi.Name(), nil
  217. }
  218. func (ps *memPS) findContentLength(name string, fi os.FileInfo) (string, error) {
  219. return strconv.FormatInt(fi.Size(), 10), nil
  220. }
  221. func (ps *memPS) findLastModified(name string, fi os.FileInfo) (string, error) {
  222. return fi.ModTime().Format(http.TimeFormat), nil
  223. }
  224. func (ps *memPS) findContentType(name string, fi os.FileInfo) (string, error) {
  225. f, err := ps.fs.OpenFile(name, os.O_RDONLY, 0)
  226. if err != nil {
  227. return "", err
  228. }
  229. defer f.Close()
  230. // This implementation is based on serveContent's code in the standard net/http package.
  231. ctype := mime.TypeByExtension(filepath.Ext(name))
  232. if ctype == "" {
  233. // Read a chunk to decide between utf-8 text and binary.
  234. var buf [512]byte
  235. n, _ := io.ReadFull(f, buf[:])
  236. ctype = http.DetectContentType(buf[:n])
  237. // Rewind file.
  238. _, err = f.Seek(0, os.SEEK_SET)
  239. }
  240. return ctype, err
  241. }
  242. func (ps *memPS) findETag(name string, fi os.FileInfo) (string, error) {
  243. return detectETag(fi), nil
  244. }
  245. // detectETag determines the ETag for the file described by fi.
  246. func detectETag(fi os.FileInfo) string {
  247. // The Apache http 2.4 web server by default concatenates the
  248. // modification time and size of a file. We replicate the heuristic
  249. // with nanosecond granularity.
  250. return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size())
  251. }