xml.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 2014 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. // The XML encoding is covered by Section 14.
  6. // http://www.webdav.org/specs/rfc4918.html#xml.element.definitions
  7. import (
  8. "bytes"
  9. "encoding/xml"
  10. "fmt"
  11. "io"
  12. "net/http"
  13. "time"
  14. )
  15. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_lockinfo
  16. type lockInfo struct {
  17. XMLName xml.Name `xml:"lockinfo"`
  18. Exclusive *struct{} `xml:"lockscope>exclusive"`
  19. Shared *struct{} `xml:"lockscope>shared"`
  20. Write *struct{} `xml:"locktype>write"`
  21. Owner owner `xml:"owner"`
  22. }
  23. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_owner
  24. type owner struct {
  25. InnerXML string `xml:",innerxml"`
  26. }
  27. func readLockInfo(r io.Reader) (li lockInfo, status int, err error) {
  28. c := &countingReader{r: r}
  29. if err = xml.NewDecoder(c).Decode(&li); err != nil {
  30. if err == io.EOF {
  31. if c.n == 0 {
  32. // An empty body means to refresh the lock.
  33. // http://www.webdav.org/specs/rfc4918.html#refreshing-locks
  34. return lockInfo{}, 0, nil
  35. }
  36. err = errInvalidLockInfo
  37. }
  38. return lockInfo{}, http.StatusBadRequest, err
  39. }
  40. // We only support exclusive (non-shared) write locks. In practice, these are
  41. // the only types of locks that seem to matter.
  42. if li.Exclusive == nil || li.Shared != nil || li.Write == nil {
  43. return lockInfo{}, http.StatusNotImplemented, errUnsupportedLockInfo
  44. }
  45. return li, 0, nil
  46. }
  47. type countingReader struct {
  48. n int
  49. r io.Reader
  50. }
  51. func (c *countingReader) Read(p []byte) (int, error) {
  52. n, err := c.r.Read(p)
  53. c.n += n
  54. return n, err
  55. }
  56. func writeLockInfo(w io.Writer, token string, ld LockDetails) (int, error) {
  57. depth := "infinity"
  58. if ld.ZeroDepth {
  59. depth = "0"
  60. }
  61. timeout := ld.Duration / time.Second
  62. return fmt.Fprintf(w, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+
  63. "<D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock>\n"+
  64. " <D:locktype><D:write/></D:locktype>\n"+
  65. " <D:lockscope><D:exclusive/></D:lockscope>\n"+
  66. " <D:depth>%s</D:depth>\n"+
  67. " <D:owner>%s</D:owner>\n"+
  68. " <D:timeout>Second-%d</D:timeout>\n"+
  69. " <D:locktoken><D:href>%s</D:href></D:locktoken>\n"+
  70. " <D:lockroot><D:href>%s</D:href></D:lockroot>\n"+
  71. "</D:activelock></D:lockdiscovery></D:prop>",
  72. depth, ld.OwnerXML, timeout, escape(token), escape(ld.Root),
  73. )
  74. }
  75. func escape(s string) string {
  76. for i := 0; i < len(s); i++ {
  77. switch s[i] {
  78. case '"', '&', '\'', '<', '>':
  79. b := bytes.NewBuffer(nil)
  80. xml.EscapeText(b, []byte(s))
  81. return b.String()
  82. }
  83. }
  84. return s
  85. }
  86. // Next returns the next token, if any, in the XML stream of d.
  87. // RFC 4918 requires to ignore comments, processing instructions
  88. // and directives.
  89. // http://www.webdav.org/specs/rfc4918.html#property_values
  90. // http://www.webdav.org/specs/rfc4918.html#xml-extensibility
  91. func next(d *xml.Decoder) (xml.Token, error) {
  92. for {
  93. t, err := d.Token()
  94. if err != nil {
  95. return t, err
  96. }
  97. switch t.(type) {
  98. case xml.Comment, xml.Directive, xml.ProcInst:
  99. continue
  100. default:
  101. return t, nil
  102. }
  103. }
  104. }
  105. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for propfind)
  106. type propnames []xml.Name
  107. // UnmarshalXML appends the property names enclosed within start to pn.
  108. //
  109. // It returns an error if start does not contain any properties or if
  110. // properties contain values. Character data between properties is ignored.
  111. func (pn *propnames) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  112. for {
  113. t, err := next(d)
  114. if err != nil {
  115. return err
  116. }
  117. switch t.(type) {
  118. case xml.EndElement:
  119. if len(*pn) == 0 {
  120. return fmt.Errorf("%s must not be empty", start.Name.Local)
  121. }
  122. return nil
  123. case xml.StartElement:
  124. name := t.(xml.StartElement).Name
  125. t, err = next(d)
  126. if err != nil {
  127. return err
  128. }
  129. if _, ok := t.(xml.EndElement); !ok {
  130. return fmt.Errorf("unexpected token %T", t)
  131. }
  132. *pn = append(*pn, name)
  133. }
  134. }
  135. }
  136. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propfind
  137. type propfind struct {
  138. XMLName xml.Name `xml:"DAV: propfind"`
  139. Allprop *struct{} `xml:"DAV: allprop"`
  140. Propname *struct{} `xml:"DAV: propname"`
  141. Prop propnames `xml:"DAV: prop"`
  142. Include propnames `xml:"DAV: include"`
  143. }
  144. func readPropfind(r io.Reader) (pf propfind, status int, err error) {
  145. c := countingReader{r: r}
  146. if err = xml.NewDecoder(&c).Decode(&pf); err != nil {
  147. if err == io.EOF {
  148. if c.n == 0 {
  149. // An empty body means to propfind allprop.
  150. // http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND
  151. return propfind{Allprop: new(struct{})}, 0, nil
  152. }
  153. err = errInvalidPropfind
  154. }
  155. return propfind{}, http.StatusBadRequest, err
  156. }
  157. if pf.Allprop == nil && pf.Include != nil {
  158. return propfind{}, http.StatusBadRequest, errInvalidPropfind
  159. }
  160. if pf.Allprop != nil && (pf.Prop != nil || pf.Propname != nil) {
  161. return propfind{}, http.StatusBadRequest, errInvalidPropfind
  162. }
  163. if pf.Prop != nil && pf.Propname != nil {
  164. return propfind{}, http.StatusBadRequest, errInvalidPropfind
  165. }
  166. if pf.Propname == nil && pf.Allprop == nil && pf.Prop == nil {
  167. return propfind{}, http.StatusBadRequest, errInvalidPropfind
  168. }
  169. return pf, 0, nil
  170. }
  171. // Property represents a single DAV resource property as defined in RFC 4918.
  172. // See http://www.webdav.org/specs/rfc4918.html#data.model.for.resource.properties
  173. type Property struct {
  174. // XMLName is the fully qualified name that identifies this property.
  175. XMLName xml.Name
  176. // Lang is an optional xml:lang attribute.
  177. Lang string `xml:"xml:lang,attr,omitempty"`
  178. // InnerXML contains the XML representation of the property value.
  179. // See http://www.webdav.org/specs/rfc4918.html#property_values
  180. //
  181. // Property values of complex type or mixed-content must have fully
  182. // expanded XML namespaces or be self-contained with according
  183. // XML namespace declarations. They must not rely on any XML
  184. // namespace declarations within the scope of the XML document,
  185. // even including the DAV: namespace.
  186. InnerXML []byte `xml:",innerxml"`
  187. }
  188. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_error
  189. type xmlError struct {
  190. XMLName xml.Name `xml:"DAV: error"`
  191. InnerXML []byte `xml:",innerxml"`
  192. }
  193. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat
  194. type propstat struct {
  195. Prop []Property `xml:"DAV: prop>_ignored_"`
  196. Status string `xml:"DAV: status"`
  197. Error *xmlError `xml:"DAV: error"`
  198. ResponseDescription string `xml:"DAV: responsedescription,omitempty"`
  199. }
  200. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_response
  201. type response struct {
  202. XMLName xml.Name `xml:"DAV: response"`
  203. Href []string `xml:"DAV: href"`
  204. Propstat []propstat `xml:"DAV: propstat"`
  205. Status string `xml:"DAV: status,omitempty"`
  206. Error *xmlError `xml:"DAV: error"`
  207. ResponseDescription string `xml:"DAV: responsedescription,omitempty"`
  208. }
  209. // MultistatusWriter marshals one or more Responses into a XML
  210. // multistatus response.
  211. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_multistatus
  212. type multistatusWriter struct {
  213. // ResponseDescription contains the optional responsedescription
  214. // of the multistatus XML element. Only the latest content before
  215. // close will be emitted. Empty response descriptions are not
  216. // written.
  217. responseDescription string
  218. w http.ResponseWriter
  219. enc *xml.Encoder
  220. }
  221. // Write validates and emits a DAV response as part of a multistatus response
  222. // element.
  223. //
  224. // It sets the HTTP status code of its underlying http.ResponseWriter to 207
  225. // (Multi-Status) and populates the Content-Type header. If r is the
  226. // first, valid response to be written, Write prepends the XML representation
  227. // of r with a multistatus tag. Callers must call close after the last response
  228. // has been written.
  229. func (w *multistatusWriter) write(r *response) error {
  230. switch len(r.Href) {
  231. case 0:
  232. return errInvalidResponse
  233. case 1:
  234. if len(r.Propstat) > 0 != (r.Status == "") {
  235. return errInvalidResponse
  236. }
  237. default:
  238. if len(r.Propstat) > 0 || r.Status == "" {
  239. return errInvalidResponse
  240. }
  241. }
  242. if w.enc == nil {
  243. w.w.Header().Add("Content-Type", "text/xml; charset=utf-8")
  244. w.w.WriteHeader(StatusMulti)
  245. _, err := fmt.Fprintf(w.w, `<?xml version="1.0" encoding="UTF-8"?>`)
  246. if err != nil {
  247. return err
  248. }
  249. w.enc = xml.NewEncoder(w.w)
  250. err = w.enc.EncodeToken(xml.StartElement{
  251. Name: xml.Name{
  252. Space: "DAV:",
  253. Local: "multistatus",
  254. },
  255. Attr: []xml.Attr{{
  256. Name: xml.Name{Local: "xmlns"},
  257. Value: "DAV:",
  258. }},
  259. })
  260. if err != nil {
  261. return err
  262. }
  263. }
  264. return w.enc.Encode(r)
  265. }
  266. // Close completes the marshalling of the multistatus response. It returns
  267. // an error if the multistatus response could not be completed. If both the
  268. // return value and field enc of w are nil, then no multistatus response has
  269. // been written.
  270. func (w *multistatusWriter) close() error {
  271. if w.enc == nil {
  272. return nil
  273. }
  274. var end []xml.Token
  275. if w.responseDescription != "" {
  276. name := xml.Name{Space: "DAV:", Local: "responsedescription"}
  277. end = append(end,
  278. xml.StartElement{Name: name},
  279. xml.CharData(w.responseDescription),
  280. xml.EndElement{Name: name},
  281. )
  282. }
  283. end = append(end, xml.EndElement{
  284. Name: xml.Name{Space: "DAV:", Local: "multistatus"},
  285. })
  286. for _, t := range end {
  287. err := w.enc.EncodeToken(t)
  288. if err != nil {
  289. return err
  290. }
  291. }
  292. return w.enc.Flush()
  293. }