handler.go 9.4 KB

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