handler.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. // Copyright (C) 2019-2022 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package webdavd
  15. import (
  16. "context"
  17. "net/http"
  18. "os"
  19. "path"
  20. "strings"
  21. "github.com/drakkan/webdav"
  22. "github.com/drakkan/sftpgo/v2/internal/common"
  23. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  24. "github.com/drakkan/sftpgo/v2/internal/logger"
  25. "github.com/drakkan/sftpgo/v2/internal/util"
  26. "github.com/drakkan/sftpgo/v2/internal/vfs"
  27. )
  28. // Connection details for a WebDav connection.
  29. type Connection struct {
  30. *common.BaseConnection
  31. request *http.Request
  32. }
  33. // GetClientVersion returns the connected client's version.
  34. func (c *Connection) GetClientVersion() string {
  35. if c.request != nil {
  36. return c.request.UserAgent()
  37. }
  38. return ""
  39. }
  40. // GetLocalAddress returns local connection address
  41. func (c *Connection) GetLocalAddress() string {
  42. return util.GetHTTPLocalAddress(c.request)
  43. }
  44. // GetRemoteAddress returns the connected client's address
  45. func (c *Connection) GetRemoteAddress() string {
  46. if c.request != nil {
  47. return c.request.RemoteAddr
  48. }
  49. return ""
  50. }
  51. // Disconnect closes the active transfer
  52. func (c *Connection) Disconnect() error {
  53. return c.SignalTransfersAbort()
  54. }
  55. // GetCommand returns the request method
  56. func (c *Connection) GetCommand() string {
  57. if c.request != nil {
  58. return strings.ToUpper(c.request.Method)
  59. }
  60. return ""
  61. }
  62. // Mkdir creates a directory using the connection filesystem
  63. func (c *Connection) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  64. c.UpdateLastActivity()
  65. name = util.CleanPath(name)
  66. return c.CreateDir(name, true)
  67. }
  68. // Rename renames a file or a directory
  69. func (c *Connection) Rename(ctx context.Context, oldName, newName string) error {
  70. c.UpdateLastActivity()
  71. oldName = util.CleanPath(oldName)
  72. newName = util.CleanPath(newName)
  73. return c.BaseConnection.Rename(oldName, newName)
  74. }
  75. // Stat returns a FileInfo describing the named file/directory, or an error,
  76. // if any happens
  77. func (c *Connection) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  78. c.UpdateLastActivity()
  79. name = util.CleanPath(name)
  80. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  81. return nil, c.GetPermissionDeniedError()
  82. }
  83. fi, err := c.DoStat(name, 0, true)
  84. if err != nil {
  85. return nil, err
  86. }
  87. return fi, err
  88. }
  89. // RemoveAll removes path and any children it contains.
  90. // If the path does not exist, RemoveAll returns nil (no error).
  91. func (c *Connection) RemoveAll(ctx context.Context, name string) error {
  92. c.UpdateLastActivity()
  93. name = util.CleanPath(name)
  94. return c.BaseConnection.RemoveAll(name)
  95. }
  96. // OpenFile opens the named file with specified flag.
  97. // This method is used for uploads and downloads but also for Stat and Readdir
  98. func (c *Connection) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
  99. c.UpdateLastActivity()
  100. name = util.CleanPath(name)
  101. fs, p, err := c.GetFsAndResolvedPath(name)
  102. if err != nil {
  103. return nil, err
  104. }
  105. if flag == os.O_RDONLY || c.request.Method == "PROPPATCH" {
  106. // Download, Stat, Readdir or simply open/close
  107. return c.getFile(fs, p, name)
  108. }
  109. return c.putFile(fs, p, name)
  110. }
  111. func (c *Connection) getFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  112. var cancelFn func()
  113. // we open the file when we receive the first read so we only open the file if necessary
  114. baseTransfer := common.NewBaseTransfer(nil, c.BaseConnection, cancelFn, fsPath, fsPath, virtualPath,
  115. common.TransferDownload, 0, 0, 0, 0, false, fs, c.GetTransferQuota())
  116. return newWebDavFile(baseTransfer, nil, nil), nil
  117. }
  118. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  119. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  120. c.Log(logger.LevelWarn, "writing file %#v is not allowed", virtualPath)
  121. return nil, c.GetPermissionDeniedError()
  122. }
  123. filePath := fsPath
  124. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  125. filePath = fs.GetAtomicUploadPath(fsPath)
  126. }
  127. stat, statErr := fs.Lstat(fsPath)
  128. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  129. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualPath)) {
  130. return nil, c.GetPermissionDeniedError()
  131. }
  132. return c.handleUploadToNewFile(fs, fsPath, filePath, virtualPath)
  133. }
  134. if statErr != nil {
  135. c.Log(logger.LevelError, "error performing file stat %#v: %+v", fsPath, statErr)
  136. return nil, c.GetFsError(fs, statErr)
  137. }
  138. // This happen if we upload a file that has the same name of an existing directory
  139. if stat.IsDir() {
  140. c.Log(logger.LevelError, "attempted to open a directory for writing to: %#v", fsPath)
  141. return nil, c.GetOpUnsupportedError()
  142. }
  143. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualPath)) {
  144. return nil, c.GetPermissionDeniedError()
  145. }
  146. return c.handleUploadToExistingFile(fs, fsPath, filePath, stat.Size(), virtualPath)
  147. }
  148. func (c *Connection) handleUploadToNewFile(fs vfs.Fs, resolvedPath, filePath, requestPath string) (webdav.File, error) {
  149. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  150. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  151. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  152. return nil, common.ErrQuotaExceeded
  153. }
  154. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  155. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  156. return nil, c.GetPermissionDeniedError()
  157. }
  158. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.GetCreateChecks(requestPath, true))
  159. if err != nil {
  160. c.Log(logger.LevelError, "error creating file %#v: %+v", resolvedPath, err)
  161. return nil, c.GetFsError(fs, err)
  162. }
  163. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  164. // we can get an error only for resume
  165. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, 0, fs.IsUploadResumeSupported())
  166. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  167. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  168. return newWebDavFile(baseTransfer, w, nil), nil
  169. }
  170. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  171. requestPath string,
  172. ) (webdav.File, error) {
  173. var err error
  174. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  175. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  176. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  177. return nil, common.ErrQuotaExceeded
  178. }
  179. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath,
  180. fileSize, os.O_TRUNC); err != nil {
  181. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  182. return nil, c.GetPermissionDeniedError()
  183. }
  184. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  185. // will return false in this case and we deny the upload before
  186. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  187. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  188. err = fs.Rename(resolvedPath, filePath)
  189. if err != nil {
  190. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  191. resolvedPath, filePath, err)
  192. return nil, c.GetFsError(fs, err)
  193. }
  194. }
  195. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.GetCreateChecks(requestPath, false))
  196. if err != nil {
  197. c.Log(logger.LevelError, "error creating file %#v: %+v", resolvedPath, err)
  198. return nil, c.GetFsError(fs, err)
  199. }
  200. initialSize := int64(0)
  201. truncatedSize := int64(0) // bytes truncated and not included in quota
  202. if vfs.HasTruncateSupport(fs) {
  203. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  204. if err == nil {
  205. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  206. if vfolder.IsIncludedInUserQuota() {
  207. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  208. }
  209. } else {
  210. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  211. }
  212. } else {
  213. initialSize = fileSize
  214. truncatedSize = fileSize
  215. }
  216. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  217. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  218. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  219. return newWebDavFile(baseTransfer, w, nil), nil
  220. }