handler.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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/v2/common"
  11. "github.com/drakkan/sftpgo/v2/dataprovider"
  12. "github.com/drakkan/sftpgo/v2/logger"
  13. "github.com/drakkan/sftpgo/v2/util"
  14. "github.com/drakkan/sftpgo/v2/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. // GetLocalAddress returns local connection address
  29. func (c *Connection) GetLocalAddress() string {
  30. return util.GetHTTPLocalAddress(c.request)
  31. }
  32. // GetRemoteAddress returns the connected client's address
  33. func (c *Connection) GetRemoteAddress() string {
  34. if c.request != nil {
  35. return c.request.RemoteAddr
  36. }
  37. return ""
  38. }
  39. // Disconnect closes the active transfer
  40. func (c *Connection) Disconnect() error {
  41. return c.SignalTransfersAbort()
  42. }
  43. // GetCommand returns the request method
  44. func (c *Connection) GetCommand() string {
  45. if c.request != nil {
  46. return strings.ToUpper(c.request.Method)
  47. }
  48. return ""
  49. }
  50. // Mkdir creates a directory using the connection filesystem
  51. func (c *Connection) Mkdir(ctx context.Context, name string, perm os.FileMode) error {
  52. c.UpdateLastActivity()
  53. name = util.CleanPath(name)
  54. return c.CreateDir(name)
  55. }
  56. // Rename renames a file or a directory
  57. func (c *Connection) Rename(ctx context.Context, oldName, newName string) error {
  58. c.UpdateLastActivity()
  59. oldName = util.CleanPath(oldName)
  60. newName = util.CleanPath(newName)
  61. return c.BaseConnection.Rename(oldName, newName)
  62. }
  63. // Stat returns a FileInfo describing the named file/directory, or an error,
  64. // if any happens
  65. func (c *Connection) Stat(ctx context.Context, name string) (os.FileInfo, error) {
  66. c.UpdateLastActivity()
  67. name = util.CleanPath(name)
  68. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  69. return nil, c.GetPermissionDeniedError()
  70. }
  71. fi, err := c.DoStat(name, 0)
  72. if err != nil {
  73. c.Log(logger.LevelDebug, "error running stat on path %#v: %+v", name, err)
  74. return nil, err
  75. }
  76. return fi, err
  77. }
  78. // RemoveAll removes path and any children it contains.
  79. // If the path does not exist, RemoveAll returns nil (no error).
  80. func (c *Connection) RemoveAll(ctx context.Context, name string) error {
  81. c.UpdateLastActivity()
  82. name = util.CleanPath(name)
  83. fs, p, err := c.GetFsAndResolvedPath(name)
  84. if err != nil {
  85. return err
  86. }
  87. var fi os.FileInfo
  88. if fi, err = fs.Lstat(p); err != nil {
  89. c.Log(logger.LevelDebug, "failed to remove a file %#v: stat error: %+v", p, err)
  90. return c.GetFsError(fs, err)
  91. }
  92. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  93. return c.removeDirTree(fs, p, name)
  94. }
  95. return c.RemoveFile(fs, p, name, fi)
  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.LevelWarn, "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, common.TransferDownload,
  127. 0, 0, 0, false, fs)
  128. return newWebDavFile(baseTransfer, nil, r), nil
  129. }
  130. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  131. if !c.User.IsFileAllowed(virtualPath) {
  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.LevelWarn, "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. quotaResult := c.HasSpace(true, false, requestPath)
  162. if !quotaResult.HasSpace {
  163. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  164. return nil, common.ErrQuotaExceeded
  165. }
  166. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), 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, 0)
  171. if err != nil {
  172. c.Log(logger.LevelWarn, "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(quotaResult, false, 0, fs.IsUploadResumeSupported())
  178. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  179. common.TransferUpload, 0, 0, maxWriteSize, true, fs)
  180. return newWebDavFile(baseTransfer, w, nil), nil
  181. }
  182. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  183. requestPath string) (webdav.File, error) {
  184. var err error
  185. quotaResult := c.HasSpace(false, false, requestPath)
  186. if !quotaResult.HasSpace {
  187. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  188. return nil, common.ErrQuotaExceeded
  189. }
  190. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), fileSize, os.O_TRUNC); err != nil {
  191. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  192. return nil, c.GetPermissionDeniedError()
  193. }
  194. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  195. // will return false in this case and we deny the upload before
  196. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, fileSize, fs.IsUploadResumeSupported())
  197. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  198. err = fs.Rename(resolvedPath, filePath)
  199. if err != nil {
  200. c.Log(logger.LevelWarn, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  201. resolvedPath, filePath, err)
  202. return nil, c.GetFsError(fs, err)
  203. }
  204. }
  205. file, w, cancelFn, err := fs.Create(filePath, 0)
  206. if err != nil {
  207. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  208. return nil, c.GetFsError(fs, err)
  209. }
  210. initialSize := int64(0)
  211. if vfs.IsLocalOrSFTPFs(fs) {
  212. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  213. if err == nil {
  214. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  215. if vfolder.IsIncludedInUserQuota() {
  216. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  217. }
  218. } else {
  219. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  220. }
  221. } else {
  222. initialSize = fileSize
  223. }
  224. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  225. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  226. common.TransferUpload, 0, initialSize, maxWriteSize, false, fs)
  227. return newWebDavFile(baseTransfer, w, nil), nil
  228. }
  229. type objectMapping struct {
  230. fsPath string
  231. virtualPath string
  232. info os.FileInfo
  233. }
  234. func (c *Connection) removeDirTree(fs vfs.Fs, fsPath, virtualPath string) error {
  235. var dirsToRemove []objectMapping
  236. var filesToRemove []objectMapping
  237. err := fs.Walk(fsPath, func(walkedPath string, info os.FileInfo, err error) error {
  238. if err != nil {
  239. return err
  240. }
  241. obj := objectMapping{
  242. fsPath: walkedPath,
  243. virtualPath: fs.GetRelativePath(walkedPath),
  244. info: info,
  245. }
  246. if info.IsDir() {
  247. err = c.IsRemoveDirAllowed(fs, obj.fsPath, obj.virtualPath)
  248. isDuplicated := false
  249. for _, d := range dirsToRemove {
  250. if d.fsPath == obj.fsPath {
  251. isDuplicated = true
  252. break
  253. }
  254. }
  255. if !isDuplicated {
  256. dirsToRemove = append(dirsToRemove, obj)
  257. }
  258. } else {
  259. err = c.IsRemoveFileAllowed(obj.virtualPath)
  260. filesToRemove = append(filesToRemove, obj)
  261. }
  262. if err != nil {
  263. c.Log(logger.LevelDebug, "unable to remove dir tree, object %#v->%#v cannot be removed: %v",
  264. virtualPath, fsPath, err)
  265. return err
  266. }
  267. return nil
  268. })
  269. if err != nil {
  270. c.Log(logger.LevelWarn, "failed to remove dir tree %#v->%#v: error: %+v", virtualPath, fsPath, err)
  271. return err
  272. }
  273. for _, fileObj := range filesToRemove {
  274. err = c.RemoveFile(fs, fileObj.fsPath, fileObj.virtualPath, fileObj.info)
  275. if err != nil {
  276. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing file %#v->%#v: %v",
  277. fileObj.virtualPath, fileObj.fsPath, err)
  278. return err
  279. }
  280. }
  281. for _, dirObj := range c.orderDirsToRemove(fs, dirsToRemove) {
  282. err = c.RemoveDir(dirObj.virtualPath)
  283. if err != nil {
  284. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing directory %#v->%#v: %v",
  285. dirObj.virtualPath, dirObj.fsPath, err)
  286. return err
  287. }
  288. }
  289. return err
  290. }
  291. // order directories so that the empty ones will be at slice start
  292. func (c *Connection) orderDirsToRemove(fs vfs.Fs, dirsToRemove []objectMapping) []objectMapping {
  293. orderedDirs := make([]objectMapping, 0, len(dirsToRemove))
  294. removedDirs := make([]string, 0, len(dirsToRemove))
  295. pathSeparator := "/"
  296. if vfs.IsLocalOsFs(fs) {
  297. pathSeparator = string(os.PathSeparator)
  298. }
  299. for len(orderedDirs) < len(dirsToRemove) {
  300. for idx, d := range dirsToRemove {
  301. if util.IsStringInSlice(d.fsPath, removedDirs) {
  302. continue
  303. }
  304. isEmpty := true
  305. for idx1, d1 := range dirsToRemove {
  306. if idx == idx1 {
  307. continue
  308. }
  309. if util.IsStringInSlice(d1.fsPath, removedDirs) {
  310. continue
  311. }
  312. if strings.HasPrefix(d1.fsPath, d.fsPath+pathSeparator) {
  313. isEmpty = false
  314. break
  315. }
  316. }
  317. if isEmpty {
  318. orderedDirs = append(orderedDirs, d)
  319. removedDirs = append(removedDirs, d.fsPath)
  320. }
  321. }
  322. }
  323. return orderedDirs
  324. }