handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package webdavd
  2. import (
  3. "context"
  4. "net/http"
  5. "os"
  6. "path"
  7. "strings"
  8. "github.com/eikenb/pipeat"
  9. "golang.org/x/net/webdav"
  10. "github.com/drakkan/sftpgo/common"
  11. "github.com/drakkan/sftpgo/dataprovider"
  12. "github.com/drakkan/sftpgo/logger"
  13. "github.com/drakkan/sftpgo/utils"
  14. "github.com/drakkan/sftpgo/vfs"
  15. )
  16. // Connection details for a WebDav connection.
  17. type Connection struct {
  18. *common.BaseConnection
  19. request *http.Request
  20. }
  21. // GetClientVersion returns the connected client's version.
  22. func (c *Connection) GetClientVersion() string {
  23. if c.request != nil {
  24. return c.request.UserAgent()
  25. }
  26. return ""
  27. }
  28. // GetRemoteAddress return the connected client's address
  29. func (c *Connection) GetRemoteAddress() string {
  30. if c.request != nil {
  31. return c.request.RemoteAddr
  32. }
  33. return ""
  34. }
  35. // Disconnect closes the active transfer
  36. func (c *Connection) Disconnect() error {
  37. return c.SignalTransfersAbort()
  38. }
  39. // GetCommand returns the request method
  40. func (c *Connection) GetCommand() string {
  41. if c.request != nil {
  42. return strings.ToUpper(c.request.Method)
  43. }
  44. return ""
  45. }
  46. // Mkdir creates a directory using the connection filesystem
  47. func (c *Connection) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  48. c.UpdateLastActivity()
  49. name = utils.CleanPath(name)
  50. return c.CreateDir(name)
  51. }
  52. // Rename renames a file or a directory
  53. func (c *Connection) Rename(ctx context.Context, oldName, newName string) error {
  54. c.UpdateLastActivity()
  55. oldName = utils.CleanPath(oldName)
  56. newName = utils.CleanPath(newName)
  57. return c.BaseConnection.Rename(oldName, newName)
  58. }
  59. // Stat returns a FileInfo describing the named file/directory, or an error,
  60. // if any happens
  61. func (c *Connection) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  62. c.UpdateLastActivity()
  63. name = utils.CleanPath(name)
  64. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  65. return nil, c.GetPermissionDeniedError()
  66. }
  67. fi, err := c.DoStat(name, 0)
  68. if err != nil {
  69. c.Log(logger.LevelDebug, "error running stat on path %#v: %+v", name, err)
  70. return nil, err
  71. }
  72. return fi, err
  73. }
  74. // RemoveAll removes path and any children it contains.
  75. // If the path does not exist, RemoveAll returns nil (no error).
  76. func (c *Connection) RemoveAll(ctx context.Context, name string) error {
  77. c.UpdateLastActivity()
  78. name = utils.CleanPath(name)
  79. fs, p, err := c.GetFsAndResolvedPath(name)
  80. if err != nil {
  81. return err
  82. }
  83. var fi os.FileInfo
  84. if fi, err = fs.Lstat(p); err != nil {
  85. c.Log(logger.LevelDebug, "failed to remove a file %#v: stat error: %+v", p, err)
  86. return c.GetFsError(fs, err)
  87. }
  88. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  89. return c.removeDirTree(fs, p, name)
  90. }
  91. return c.RemoveFile(fs, p, name, fi)
  92. }
  93. // OpenFile opens the named file with specified flag.
  94. // This method is used for uploads and downloads but also for Stat and Readdir
  95. func (c *Connection) OpenFile(ctx context.Context, name string, flag int, perm os.FileMode) (webdav.File, error) {
  96. c.UpdateLastActivity()
  97. name = utils.CleanPath(name)
  98. fs, p, err := c.GetFsAndResolvedPath(name)
  99. if err != nil {
  100. return nil, err
  101. }
  102. if flag == os.O_RDONLY || c.request.Method == "PROPPATCH" {
  103. // Download, Stat, Readdir or simply open/close
  104. return c.getFile(fs, p, name)
  105. }
  106. return c.putFile(fs, p, name)
  107. }
  108. func (c *Connection) getFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  109. var err error
  110. var file vfs.File
  111. var r *pipeat.PipeReaderAt
  112. var cancelFn func()
  113. // for cloud fs we open the file when we receive the first read to avoid to download the first part of
  114. // the file if it was opened only to do a stat or a readdir and so it is not a real download
  115. if vfs.IsLocalOrUnbufferedSFTPFs(fs) {
  116. file, r, cancelFn, err = fs.Open(fsPath, 0)
  117. if err != nil {
  118. c.Log(logger.LevelWarn, "could not open file %#v for reading: %+v", fsPath, err)
  119. return nil, c.GetFsError(fs, err)
  120. }
  121. }
  122. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, fsPath, fsPath, virtualPath, common.TransferDownload,
  123. 0, 0, 0, false, fs)
  124. return newWebDavFile(baseTransfer, nil, r), nil
  125. }
  126. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  127. if !c.User.IsFileAllowed(virtualPath) {
  128. c.Log(logger.LevelWarn, "writing file %#v is not allowed", virtualPath)
  129. return nil, c.GetPermissionDeniedError()
  130. }
  131. filePath := fsPath
  132. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  133. filePath = fs.GetAtomicUploadPath(fsPath)
  134. }
  135. stat, statErr := fs.Lstat(fsPath)
  136. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  137. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualPath)) {
  138. return nil, c.GetPermissionDeniedError()
  139. }
  140. return c.handleUploadToNewFile(fs, fsPath, filePath, virtualPath)
  141. }
  142. if statErr != nil {
  143. c.Log(logger.LevelError, "error performing file stat %#v: %+v", fsPath, statErr)
  144. return nil, c.GetFsError(fs, statErr)
  145. }
  146. // This happen if we upload a file that has the same name of an existing directory
  147. if stat.IsDir() {
  148. c.Log(logger.LevelWarn, "attempted to open a directory for writing to: %#v", fsPath)
  149. return nil, c.GetOpUnsupportedError()
  150. }
  151. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualPath)) {
  152. return nil, c.GetPermissionDeniedError()
  153. }
  154. return c.handleUploadToExistingFile(fs, fsPath, filePath, stat.Size(), virtualPath)
  155. }
  156. func (c *Connection) handleUploadToNewFile(fs vfs.Fs, resolvedPath, filePath, requestPath string) (webdav.File, error) {
  157. quotaResult := c.HasSpace(true, false, requestPath)
  158. if !quotaResult.HasSpace {
  159. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  160. return nil, common.ErrQuotaExceeded
  161. }
  162. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), 0); err != nil {
  163. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  164. return nil, c.GetPermissionDeniedError()
  165. }
  166. file, w, cancelFn, err := fs.Create(filePath, 0)
  167. if err != nil {
  168. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  169. return nil, c.GetFsError(fs, err)
  170. }
  171. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  172. // we can get an error only for resume
  173. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, 0, fs.IsUploadResumeSupported())
  174. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  175. common.TransferUpload, 0, 0, maxWriteSize, true, fs)
  176. return newWebDavFile(baseTransfer, w, nil), nil
  177. }
  178. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  179. requestPath string) (webdav.File, error) {
  180. var err error
  181. quotaResult := c.HasSpace(false, false, requestPath)
  182. if !quotaResult.HasSpace {
  183. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  184. return nil, common.ErrQuotaExceeded
  185. }
  186. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), fileSize); err != nil {
  187. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  188. return nil, c.GetPermissionDeniedError()
  189. }
  190. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  191. // will return false in this case and we deny the upload before
  192. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, fileSize, fs.IsUploadResumeSupported())
  193. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  194. err = fs.Rename(resolvedPath, filePath)
  195. if err != nil {
  196. c.Log(logger.LevelWarn, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  197. resolvedPath, filePath, err)
  198. return nil, c.GetFsError(fs, err)
  199. }
  200. }
  201. file, w, cancelFn, err := fs.Create(filePath, 0)
  202. if err != nil {
  203. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  204. return nil, c.GetFsError(fs, err)
  205. }
  206. initialSize := int64(0)
  207. if vfs.IsLocalOrSFTPFs(fs) {
  208. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  209. if err == nil {
  210. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  211. if vfolder.IsIncludedInUserQuota() {
  212. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  213. }
  214. } else {
  215. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  216. }
  217. } else {
  218. initialSize = fileSize
  219. }
  220. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  221. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  222. common.TransferUpload, 0, initialSize, maxWriteSize, false, fs)
  223. return newWebDavFile(baseTransfer, w, nil), nil
  224. }
  225. type objectMapping struct {
  226. fsPath string
  227. virtualPath string
  228. info os.FileInfo
  229. }
  230. func (c *Connection) removeDirTree(fs vfs.Fs, fsPath, virtualPath string) error {
  231. var dirsToRemove []objectMapping
  232. var filesToRemove []objectMapping
  233. err := fs.Walk(fsPath, func(walkedPath string, info os.FileInfo, err error) error {
  234. if err != nil {
  235. return err
  236. }
  237. obj := objectMapping{
  238. fsPath: walkedPath,
  239. virtualPath: fs.GetRelativePath(walkedPath),
  240. info: info,
  241. }
  242. if info.IsDir() {
  243. err = c.IsRemoveDirAllowed(fs, obj.fsPath, obj.virtualPath)
  244. isDuplicated := false
  245. for _, d := range dirsToRemove {
  246. if d.fsPath == obj.fsPath {
  247. isDuplicated = true
  248. break
  249. }
  250. }
  251. if !isDuplicated {
  252. dirsToRemove = append(dirsToRemove, obj)
  253. }
  254. } else {
  255. err = c.IsRemoveFileAllowed(obj.virtualPath)
  256. filesToRemove = append(filesToRemove, obj)
  257. }
  258. if err != nil {
  259. c.Log(logger.LevelDebug, "unable to remove dir tree, object %#v->%#v cannot be removed: %v",
  260. virtualPath, fsPath, err)
  261. return err
  262. }
  263. return nil
  264. })
  265. if err != nil {
  266. c.Log(logger.LevelWarn, "failed to remove dir tree %#v->%#v: error: %+v", virtualPath, fsPath, err)
  267. return err
  268. }
  269. for _, fileObj := range filesToRemove {
  270. err = c.RemoveFile(fs, fileObj.fsPath, fileObj.virtualPath, fileObj.info)
  271. if err != nil {
  272. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing file %#v->%#v: %v",
  273. fileObj.virtualPath, fileObj.fsPath, err)
  274. return err
  275. }
  276. }
  277. for _, dirObj := range c.orderDirsToRemove(fs, dirsToRemove) {
  278. err = c.RemoveDir(dirObj.virtualPath)
  279. if err != nil {
  280. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing directory %#v->%#v: %v",
  281. dirObj.virtualPath, dirObj.fsPath, err)
  282. return err
  283. }
  284. }
  285. return err
  286. }
  287. // order directories so that the empty ones will be at slice start
  288. func (c *Connection) orderDirsToRemove(fs vfs.Fs, dirsToRemove []objectMapping) []objectMapping {
  289. orderedDirs := make([]objectMapping, 0, len(dirsToRemove))
  290. removedDirs := make([]string, 0, len(dirsToRemove))
  291. pathSeparator := "/"
  292. if vfs.IsLocalOsFs(fs) {
  293. pathSeparator = string(os.PathSeparator)
  294. }
  295. for len(orderedDirs) < len(dirsToRemove) {
  296. for idx, d := range dirsToRemove {
  297. if utils.IsStringInSlice(d.fsPath, removedDirs) {
  298. continue
  299. }
  300. isEmpty := true
  301. for idx1, d1 := range dirsToRemove {
  302. if idx == idx1 {
  303. continue
  304. }
  305. if utils.IsStringInSlice(d1.fsPath, removedDirs) {
  306. continue
  307. }
  308. if strings.HasPrefix(d1.fsPath, d.fsPath+pathSeparator) {
  309. isEmpty = false
  310. break
  311. }
  312. }
  313. if isEmpty {
  314. orderedDirs = append(orderedDirs, d)
  315. removedDirs = append(removedDirs, d.fsPath)
  316. }
  317. }
  318. }
  319. return orderedDirs
  320. }