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