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