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