The reconcile package is used for DOM reconcilation in Isomorphic Go web applications.

prop.go 13KB

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