xml.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 propfindProps []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 *propfindProps) 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 propfindProps `xml:"DAV: prop"`
  142. Include propfindProps `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. err := w.writeHeader()
  243. if err != nil {
  244. return err
  245. }
  246. return w.enc.Encode(r)
  247. }
  248. // writeHeader writes a XML multistatus start element on w's underlying
  249. // http.ResponseWriter and returns the result of the write operation.
  250. // After the first write attempt, writeHeader becomes a no-op.
  251. func (w *multistatusWriter) writeHeader() error {
  252. if w.enc != nil {
  253. return nil
  254. }
  255. w.w.Header().Add("Content-Type", "text/xml; charset=utf-8")
  256. w.w.WriteHeader(StatusMulti)
  257. _, err := fmt.Fprintf(w.w, `<?xml version="1.0" encoding="UTF-8"?>`)
  258. if err != nil {
  259. return err
  260. }
  261. w.enc = xml.NewEncoder(w.w)
  262. return w.enc.EncodeToken(xml.StartElement{
  263. Name: xml.Name{
  264. Space: "DAV:",
  265. Local: "multistatus",
  266. },
  267. Attr: []xml.Attr{{
  268. Name: xml.Name{Local: "xmlns"},
  269. Value: "DAV:",
  270. }},
  271. })
  272. }
  273. // Close completes the marshalling of the multistatus response. It returns
  274. // an error if the multistatus response could not be completed. If both the
  275. // return value and field enc of w are nil, then no multistatus response has
  276. // been written.
  277. func (w *multistatusWriter) close() error {
  278. if w.enc == nil {
  279. return nil
  280. }
  281. var end []xml.Token
  282. if w.responseDescription != "" {
  283. name := xml.Name{Space: "DAV:", Local: "responsedescription"}
  284. end = append(end,
  285. xml.StartElement{Name: name},
  286. xml.CharData(w.responseDescription),
  287. xml.EndElement{Name: name},
  288. )
  289. }
  290. end = append(end, xml.EndElement{
  291. Name: xml.Name{Space: "DAV:", Local: "multistatus"},
  292. })
  293. for _, t := range end {
  294. err := w.enc.EncodeToken(t)
  295. if err != nil {
  296. return err
  297. }
  298. }
  299. return w.enc.Flush()
  300. }
  301. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for proppatch)
  302. type proppatchProps []Property
  303. var xmlLangName = xml.Name{Space: "http://www.w3.org/XML/1998/namespace", Local: "lang"}
  304. func xmlLang(s xml.StartElement, d string) string {
  305. for _, attr := range s.Attr {
  306. if attr.Name == xmlLangName {
  307. return attr.Value
  308. }
  309. }
  310. return d
  311. }
  312. // UnmarshalXML appends the property names and values enclosed within start
  313. // to ps.
  314. //
  315. // An xml:lang attribute that is defined either on the DAV:prop or property
  316. // name XML element is propagated to the property's Lang field.
  317. //
  318. // UnmarshalXML returns an error if start does not contain any properties or if
  319. // property values contain syntactically incorrect XML.
  320. func (ps *proppatchProps) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
  321. lang := xmlLang(start, "")
  322. for {
  323. t, err := next(d)
  324. if err != nil {
  325. return err
  326. }
  327. switch t.(type) {
  328. case xml.EndElement:
  329. if len(*ps) == 0 {
  330. return fmt.Errorf("%s must not be empty", start.Name.Local)
  331. }
  332. return nil
  333. case xml.StartElement:
  334. p := Property{
  335. XMLName: t.(xml.StartElement).Name,
  336. Lang: xmlLang(t.(xml.StartElement), lang),
  337. }
  338. // The XML value of a property can be arbitrary, mixed-content XML.
  339. // To make sure that the unmarshalled value contains all required
  340. // namespaces, we encode all the property value XML tokens into a
  341. // buffer. This forces the encoder to redeclare any used namespaces.
  342. var b bytes.Buffer
  343. e := xml.NewEncoder(&b)
  344. for {
  345. t, err = next(d)
  346. if err != nil {
  347. return err
  348. }
  349. if e, ok := t.(xml.EndElement); ok && e.Name == p.XMLName {
  350. break
  351. }
  352. if err = e.EncodeToken(t); err != nil {
  353. return err
  354. }
  355. }
  356. err = e.Flush()
  357. if err != nil {
  358. return err
  359. }
  360. p.InnerXML = b.Bytes()
  361. *ps = append(*ps, p)
  362. }
  363. }
  364. }
  365. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_set
  366. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_remove
  367. type setRemove struct {
  368. XMLName xml.Name
  369. Lang string `xml:"xml:lang,attr,omitempty"`
  370. Prop proppatchProps `xml:"DAV: prop"`
  371. }
  372. // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propertyupdate
  373. type propertyupdate struct {
  374. XMLName xml.Name `xml:"DAV: propertyupdate"`
  375. Lang string `xml:"xml:lang,attr,omitempty"`
  376. SetRemove []setRemove `xml:",any"`
  377. }
  378. func readProppatch(r io.Reader) (patches []Proppatch, status int, err error) {
  379. var pu propertyupdate
  380. if err = xml.NewDecoder(r).Decode(&pu); err != nil {
  381. return nil, http.StatusBadRequest, err
  382. }
  383. for _, op := range pu.SetRemove {
  384. remove := false
  385. switch op.XMLName {
  386. case xml.Name{Space: "DAV:", Local: "set"}:
  387. // No-op.
  388. case xml.Name{Space: "DAV:", Local: "remove"}:
  389. for _, p := range op.Prop {
  390. if len(p.InnerXML) > 0 {
  391. return nil, http.StatusBadRequest, errInvalidProppatch
  392. }
  393. }
  394. remove = true
  395. default:
  396. return nil, http.StatusBadRequest, errInvalidProppatch
  397. }
  398. patches = append(patches, Proppatch{Remove: remove, Props: op.Prop})
  399. }
  400. return patches, 0, nil
  401. }