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. 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 = util.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 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 = util.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.IsLocalOrUnbufferedSFTPFs(fs) {
  119. file, r, cancelFn, err = fs.Open(fsPath, 0)
  120. if err != nil {
  121. c.Log(logger.LevelError, "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, 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.LevelError, "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. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  166. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  167. return nil, c.GetPermissionDeniedError()
  168. }
  169. file, w, cancelFn, err := fs.Create(filePath, 0)
  170. if err != nil {
  171. c.Log(logger.LevelError, "error creating file %#v: %+v", resolvedPath, err)
  172. return nil, c.GetFsError(fs, err)
  173. }
  174. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  175. // we can get an error only for resume
  176. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, 0, fs.IsUploadResumeSupported())
  177. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  178. common.TransferUpload, 0, 0, maxWriteSize, true, fs)
  179. return newWebDavFile(baseTransfer, w, nil), nil
  180. }
  181. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  182. requestPath string) (webdav.File, error) {
  183. var err error
  184. quotaResult := c.HasSpace(false, false, requestPath)
  185. if !quotaResult.HasSpace {
  186. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  187. return nil, common.ErrQuotaExceeded
  188. }
  189. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath,
  190. 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.LevelError, "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.LevelError, "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.LevelError, "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. }