handler.go 9.8 KB

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