handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. if err := c.BaseConnection.Rename(oldName, newName); err != nil {
  58. return err
  59. }
  60. return nil
  61. }
  62. // Stat returns a FileInfo describing the named file/directory, or an error,
  63. // if any happens
  64. func (c *Connection) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  65. c.UpdateLastActivity()
  66. name = utils.CleanPath(name)
  67. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  68. return nil, c.GetPermissionDeniedError()
  69. }
  70. fi, err := c.DoStat(name, 0)
  71. if err != nil {
  72. c.Log(logger.LevelDebug, "error running stat on path %#v: %+v", name, err)
  73. return nil, err
  74. }
  75. return fi, err
  76. }
  77. // RemoveAll removes path and any children it contains.
  78. // If the path does not exist, RemoveAll returns nil (no error).
  79. func (c *Connection) RemoveAll(ctx context.Context, name string) error {
  80. c.UpdateLastActivity()
  81. name = utils.CleanPath(name)
  82. fs, p, err := c.GetFsAndResolvedPath(name)
  83. if err != nil {
  84. return err
  85. }
  86. var fi os.FileInfo
  87. if fi, err = fs.Lstat(p); err != nil {
  88. c.Log(logger.LevelDebug, "failed to remove a file %#v: stat error: %+v", p, err)
  89. return c.GetFsError(fs, err)
  90. }
  91. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  92. return c.removeDirTree(fs, p, name)
  93. }
  94. return c.RemoveFile(fs, p, name, fi)
  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 = utils.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 err error
  113. var file vfs.File
  114. var r *pipeat.PipeReaderAt
  115. var cancelFn func()
  116. // for cloud fs we open the file when we receive the first read to avoid to download the first part of
  117. // the file if it was opened only to do a stat or a readdir and so it is not a real download
  118. if vfs.IsLocalOrSFTPFs(fs) {
  119. file, r, cancelFn, err = fs.Open(fsPath, 0)
  120. if err != nil {
  121. c.Log(logger.LevelWarn, "could not open file %#v for reading: %+v", fsPath, err)
  122. return nil, c.GetFsError(fs, err)
  123. }
  124. }
  125. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, fsPath, virtualPath, common.TransferDownload,
  126. 0, 0, 0, false, fs)
  127. return newWebDavFile(baseTransfer, nil, r), nil
  128. }
  129. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  130. if !c.User.IsFileAllowed(virtualPath) {
  131. c.Log(logger.LevelWarn, "writing file %#v is not allowed", virtualPath)
  132. return nil, c.GetPermissionDeniedError()
  133. }
  134. filePath := fsPath
  135. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  136. filePath = fs.GetAtomicUploadPath(fsPath)
  137. }
  138. stat, statErr := fs.Lstat(fsPath)
  139. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  140. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualPath)) {
  141. return nil, c.GetPermissionDeniedError()
  142. }
  143. return c.handleUploadToNewFile(fs, fsPath, filePath, virtualPath)
  144. }
  145. if statErr != nil {
  146. c.Log(logger.LevelError, "error performing file stat %#v: %+v", fsPath, statErr)
  147. return nil, c.GetFsError(fs, statErr)
  148. }
  149. // This happen if we upload a file that has the same name of an existing directory
  150. if stat.IsDir() {
  151. c.Log(logger.LevelWarn, "attempted to open a directory for writing to: %#v", fsPath)
  152. return nil, c.GetOpUnsupportedError()
  153. }
  154. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualPath)) {
  155. return nil, c.GetPermissionDeniedError()
  156. }
  157. return c.handleUploadToExistingFile(fs, fsPath, filePath, stat.Size(), virtualPath)
  158. }
  159. func (c *Connection) handleUploadToNewFile(fs vfs.Fs, resolvedPath, filePath, requestPath string) (webdav.File, error) {
  160. quotaResult := c.HasSpace(true, false, requestPath)
  161. if !quotaResult.HasSpace {
  162. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  163. return nil, common.ErrQuotaExceeded
  164. }
  165. file, w, cancelFn, err := fs.Create(filePath, 0)
  166. if err != nil {
  167. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  168. return nil, c.GetFsError(fs, err)
  169. }
  170. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  171. // we can get an error only for resume
  172. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, 0, fs.IsUploadResumeSupported())
  173. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, requestPath,
  174. common.TransferUpload, 0, 0, maxWriteSize, true, fs)
  175. return newWebDavFile(baseTransfer, w, nil), nil
  176. }
  177. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  178. requestPath string) (webdav.File, error) {
  179. var err error
  180. quotaResult := c.HasSpace(false, false, requestPath)
  181. if !quotaResult.HasSpace {
  182. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  183. return nil, common.ErrQuotaExceeded
  184. }
  185. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  186. // will return false in this case and we deny the upload before
  187. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, fileSize, fs.IsUploadResumeSupported())
  188. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  189. err = fs.Rename(resolvedPath, filePath)
  190. if err != nil {
  191. c.Log(logger.LevelWarn, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  192. resolvedPath, filePath, err)
  193. return nil, c.GetFsError(fs, err)
  194. }
  195. }
  196. file, w, cancelFn, err := fs.Create(filePath, 0)
  197. if err != nil {
  198. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  199. return nil, c.GetFsError(fs, err)
  200. }
  201. initialSize := int64(0)
  202. if vfs.IsLocalOrSFTPFs(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. }
  215. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  216. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, requestPath,
  217. common.TransferUpload, 0, initialSize, maxWriteSize, false, fs)
  218. return newWebDavFile(baseTransfer, w, nil), nil
  219. }
  220. type objectMapping struct {
  221. fsPath string
  222. virtualPath string
  223. info os.FileInfo
  224. }
  225. func (c *Connection) removeDirTree(fs vfs.Fs, fsPath, virtualPath string) error {
  226. var dirsToRemove []objectMapping
  227. var filesToRemove []objectMapping
  228. err := fs.Walk(fsPath, func(walkedPath string, info os.FileInfo, err error) error {
  229. if err != nil {
  230. return err
  231. }
  232. obj := objectMapping{
  233. fsPath: walkedPath,
  234. virtualPath: fs.GetRelativePath(walkedPath),
  235. info: info,
  236. }
  237. if info.IsDir() {
  238. err = c.IsRemoveDirAllowed(fs, obj.fsPath, obj.virtualPath)
  239. isDuplicated := false
  240. for _, d := range dirsToRemove {
  241. if d.fsPath == obj.fsPath {
  242. isDuplicated = true
  243. break
  244. }
  245. }
  246. if !isDuplicated {
  247. dirsToRemove = append(dirsToRemove, obj)
  248. }
  249. } else {
  250. err = c.IsRemoveFileAllowed(obj.virtualPath)
  251. filesToRemove = append(filesToRemove, obj)
  252. }
  253. if err != nil {
  254. c.Log(logger.LevelDebug, "unable to remove dir tree, object %#v->%#v cannot be removed: %v",
  255. virtualPath, fsPath, err)
  256. return err
  257. }
  258. return nil
  259. })
  260. if err != nil {
  261. c.Log(logger.LevelWarn, "failed to remove dir tree %#v->%#v: error: %+v", virtualPath, fsPath, err)
  262. return err
  263. }
  264. for _, fileObj := range filesToRemove {
  265. err = c.RemoveFile(fs, fileObj.fsPath, fileObj.virtualPath, fileObj.info)
  266. if err != nil {
  267. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing file %#v->%#v: %v",
  268. fileObj.virtualPath, fileObj.fsPath, err)
  269. return err
  270. }
  271. }
  272. for _, dirObj := range c.orderDirsToRemove(fs, dirsToRemove) {
  273. err = c.RemoveDir(dirObj.virtualPath)
  274. if err != nil {
  275. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing directory %#v->%#v: %v",
  276. dirObj.virtualPath, dirObj.fsPath, err)
  277. return err
  278. }
  279. }
  280. return err
  281. }
  282. // order directories so that the empty ones will be at slice start
  283. func (c *Connection) orderDirsToRemove(fs vfs.Fs, dirsToRemove []objectMapping) []objectMapping {
  284. orderedDirs := make([]objectMapping, 0, len(dirsToRemove))
  285. removedDirs := make([]string, 0, len(dirsToRemove))
  286. pathSeparator := "/"
  287. if vfs.IsLocalOsFs(fs) {
  288. pathSeparator = string(os.PathSeparator)
  289. }
  290. for len(orderedDirs) < len(dirsToRemove) {
  291. for idx, d := range dirsToRemove {
  292. if utils.IsStringInSlice(d.fsPath, removedDirs) {
  293. continue
  294. }
  295. isEmpty := true
  296. for idx1, d1 := range dirsToRemove {
  297. if idx == idx1 {
  298. continue
  299. }
  300. if utils.IsStringInSlice(d1.fsPath, removedDirs) {
  301. continue
  302. }
  303. if strings.HasPrefix(d1.fsPath, d.fsPath+pathSeparator) {
  304. isEmpty = false
  305. break
  306. }
  307. }
  308. if isEmpty {
  309. orderedDirs = append(orderedDirs, d)
  310. removedDirs = append(removedDirs, d.fsPath)
  311. }
  312. }
  313. }
  314. return orderedDirs
  315. }