handler.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Copyright (C) 2019 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(_ context.Context, name string, _ 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(_ 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(_ 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(_ 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(_ context.Context, name string, flag int, _ os.FileMode) (webdav.File, error) {
  124. c.UpdateLastActivity()
  125. if err := common.Connections.IsNewTransferAllowed(c.User.Username); err != nil {
  126. c.Log(logger.LevelInfo, "denying transfer due to count limits")
  127. return nil, c.GetPermissionDeniedError()
  128. }
  129. name = util.CleanPath(name)
  130. fs, p, err := c.GetFsAndResolvedPath(name)
  131. if err != nil {
  132. return nil, err
  133. }
  134. if flag == os.O_RDONLY || c.request.Method == "PROPPATCH" {
  135. // Download, Stat, Readdir or simply open/close
  136. return c.getFile(fs, p, name)
  137. }
  138. return c.putFile(fs, p, name)
  139. }
  140. func (c *Connection) getFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  141. var cancelFn func()
  142. // we open the file when we receive the first read so we only open the file if necessary
  143. baseTransfer := common.NewBaseTransfer(nil, c.BaseConnection, cancelFn, fsPath, fsPath, virtualPath,
  144. common.TransferDownload, 0, 0, 0, 0, false, fs, c.GetTransferQuota())
  145. return newWebDavFile(baseTransfer, nil, nil), nil
  146. }
  147. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  148. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  149. c.Log(logger.LevelWarn, "writing file %q is not allowed", virtualPath)
  150. return nil, c.GetPermissionDeniedError()
  151. }
  152. filePath := fsPath
  153. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  154. filePath = fs.GetAtomicUploadPath(fsPath)
  155. }
  156. stat, statErr := fs.Lstat(fsPath)
  157. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  158. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualPath)) {
  159. return nil, c.GetPermissionDeniedError()
  160. }
  161. return c.handleUploadToNewFile(fs, fsPath, filePath, virtualPath)
  162. }
  163. if statErr != nil {
  164. c.Log(logger.LevelError, "error performing file stat %q: %+v", fsPath, statErr)
  165. return nil, c.GetFsError(fs, statErr)
  166. }
  167. // This happen if we upload a file that has the same name of an existing directory
  168. if stat.IsDir() {
  169. c.Log(logger.LevelError, "attempted to open a directory for writing to: %q", fsPath)
  170. return nil, c.GetOpUnsupportedError()
  171. }
  172. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualPath)) {
  173. return nil, c.GetPermissionDeniedError()
  174. }
  175. return c.handleUploadToExistingFile(fs, fsPath, filePath, stat.Size(), virtualPath)
  176. }
  177. func (c *Connection) handleUploadToNewFile(fs vfs.Fs, resolvedPath, filePath, requestPath string) (webdav.File, error) {
  178. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  179. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  180. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  181. return nil, common.ErrQuotaExceeded
  182. }
  183. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  184. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  185. return nil, c.GetPermissionDeniedError()
  186. }
  187. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.GetCreateChecks(requestPath, true, false))
  188. if err != nil {
  189. c.Log(logger.LevelError, "error creating file %q: %+v", resolvedPath, err)
  190. return nil, c.GetFsError(fs, err)
  191. }
  192. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  193. // we can get an error only for resume
  194. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, 0, fs.IsUploadResumeSupported())
  195. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  196. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  197. mtime := c.getModificationTime()
  198. baseTransfer.SetTimes(resolvedPath, mtime, mtime)
  199. return newWebDavFile(baseTransfer, w, nil), nil
  200. }
  201. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  202. requestPath string,
  203. ) (webdav.File, error) {
  204. var err error
  205. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  206. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  207. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  208. return nil, common.ErrQuotaExceeded
  209. }
  210. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath,
  211. fileSize, os.O_TRUNC); err != nil {
  212. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  213. return nil, c.GetPermissionDeniedError()
  214. }
  215. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  216. // will return false in this case and we deny the upload before
  217. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  218. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  219. _, _, err = fs.Rename(resolvedPath, filePath, 0)
  220. if err != nil {
  221. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %+v",
  222. resolvedPath, filePath, err)
  223. return nil, c.GetFsError(fs, err)
  224. }
  225. }
  226. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.GetCreateChecks(requestPath, false, false))
  227. if err != nil {
  228. c.Log(logger.LevelError, "error creating file %q: %+v", resolvedPath, err)
  229. return nil, c.GetFsError(fs, err)
  230. }
  231. initialSize := int64(0)
  232. truncatedSize := int64(0) // bytes truncated and not included in quota
  233. if vfs.HasTruncateSupport(fs) {
  234. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  235. if err == nil {
  236. dataprovider.UpdateUserFolderQuota(&vfolder, &c.User, 0, -fileSize, false)
  237. } else {
  238. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  239. }
  240. } else {
  241. initialSize = fileSize
  242. truncatedSize = fileSize
  243. }
  244. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  245. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  246. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  247. mtime := c.getModificationTime()
  248. baseTransfer.SetTimes(resolvedPath, mtime, mtime)
  249. return newWebDavFile(baseTransfer, w, nil), nil
  250. }