handler.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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, true)
  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, true)
  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,
  126. common.TransferDownload, 0, 0, 0, 0, false, fs, c.GetTransferQuota())
  127. return newWebDavFile(baseTransfer, nil, r), nil
  128. }
  129. func (c *Connection) putFile(fs vfs.Fs, fsPath, virtualPath string) (webdav.File, error) {
  130. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  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. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  161. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  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, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  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(diskQuota, false, 0, fs.IsUploadResumeSupported())
  177. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  178. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  179. return newWebDavFile(baseTransfer, w, nil), nil
  180. }
  181. func (c *Connection) handleUploadToExistingFile(fs vfs.Fs, resolvedPath, filePath string, fileSize int64,
  182. requestPath string,
  183. ) (webdav.File, error) {
  184. var err error
  185. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  186. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  187. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  188. return nil, common.ErrQuotaExceeded
  189. }
  190. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath,
  191. fileSize, os.O_TRUNC); err != nil {
  192. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  193. return nil, c.GetPermissionDeniedError()
  194. }
  195. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  196. // will return false in this case and we deny the upload before
  197. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, fileSize, fs.IsUploadResumeSupported())
  198. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  199. err = fs.Rename(resolvedPath, filePath)
  200. if err != nil {
  201. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  202. resolvedPath, filePath, err)
  203. return nil, c.GetFsError(fs, err)
  204. }
  205. }
  206. file, w, cancelFn, err := fs.Create(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
  207. if err != nil {
  208. c.Log(logger.LevelError, "error creating file %#v: %+v", resolvedPath, err)
  209. return nil, c.GetFsError(fs, err)
  210. }
  211. initialSize := int64(0)
  212. truncatedSize := int64(0) // bytes truncated and not included in quota
  213. if vfs.IsLocalOrSFTPFs(fs) {
  214. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  215. if err == nil {
  216. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  217. if vfolder.IsIncludedInUserQuota() {
  218. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  219. }
  220. } else {
  221. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  222. }
  223. } else {
  224. initialSize = fileSize
  225. truncatedSize = fileSize
  226. }
  227. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  228. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  229. common.TransferUpload, 0, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  230. return newWebDavFile(baseTransfer, w, nil), nil
  231. }
  232. type objectMapping struct {
  233. fsPath string
  234. virtualPath string
  235. info os.FileInfo
  236. }
  237. func (c *Connection) removeDirTree(fs vfs.Fs, fsPath, virtualPath string) error {
  238. var dirsToRemove []objectMapping
  239. var filesToRemove []objectMapping
  240. err := fs.Walk(fsPath, func(walkedPath string, info os.FileInfo, err error) error {
  241. if err != nil {
  242. return err
  243. }
  244. obj := objectMapping{
  245. fsPath: walkedPath,
  246. virtualPath: fs.GetRelativePath(walkedPath),
  247. info: info,
  248. }
  249. if info.IsDir() {
  250. err = c.IsRemoveDirAllowed(fs, obj.fsPath, obj.virtualPath)
  251. isDuplicated := false
  252. for _, d := range dirsToRemove {
  253. if d.fsPath == obj.fsPath {
  254. isDuplicated = true
  255. break
  256. }
  257. }
  258. if !isDuplicated {
  259. dirsToRemove = append(dirsToRemove, obj)
  260. }
  261. } else {
  262. err = c.IsRemoveFileAllowed(obj.virtualPath)
  263. filesToRemove = append(filesToRemove, obj)
  264. }
  265. if err != nil {
  266. c.Log(logger.LevelDebug, "unable to remove dir tree, object %#v->%#v cannot be removed: %v",
  267. virtualPath, fsPath, err)
  268. return err
  269. }
  270. return nil
  271. })
  272. if err != nil {
  273. c.Log(logger.LevelError, "failed to remove dir tree %#v->%#v: error: %+v", virtualPath, fsPath, err)
  274. return err
  275. }
  276. for _, fileObj := range filesToRemove {
  277. err = c.RemoveFile(fs, fileObj.fsPath, fileObj.virtualPath, fileObj.info)
  278. if err != nil {
  279. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing file %#v->%#v: %v",
  280. fileObj.virtualPath, fileObj.fsPath, err)
  281. return err
  282. }
  283. }
  284. for _, dirObj := range c.orderDirsToRemove(fs, dirsToRemove) {
  285. err = c.RemoveDir(dirObj.virtualPath)
  286. if err != nil {
  287. c.Log(logger.LevelDebug, "unable to remove dir tree, error removing directory %#v->%#v: %v",
  288. dirObj.virtualPath, dirObj.fsPath, err)
  289. return err
  290. }
  291. }
  292. return err
  293. }
  294. // order directories so that the empty ones will be at slice start
  295. func (c *Connection) orderDirsToRemove(fs vfs.Fs, dirsToRemove []objectMapping) []objectMapping {
  296. orderedDirs := make([]objectMapping, 0, len(dirsToRemove))
  297. removedDirs := make([]string, 0, len(dirsToRemove))
  298. pathSeparator := "/"
  299. if vfs.IsLocalOsFs(fs) {
  300. pathSeparator = string(os.PathSeparator)
  301. }
  302. for len(orderedDirs) < len(dirsToRemove) {
  303. for idx, d := range dirsToRemove {
  304. if util.IsStringInSlice(d.fsPath, removedDirs) {
  305. continue
  306. }
  307. isEmpty := true
  308. for idx1, d1 := range dirsToRemove {
  309. if idx == idx1 {
  310. continue
  311. }
  312. if util.IsStringInSlice(d1.fsPath, removedDirs) {
  313. continue
  314. }
  315. if strings.HasPrefix(d1.fsPath, d.fsPath+pathSeparator) {
  316. isEmpty = false
  317. break
  318. }
  319. }
  320. if isEmpty {
  321. orderedDirs = append(orderedDirs, d)
  322. removedDirs = append(removedDirs, d.fsPath)
  323. }
  324. }
  325. }
  326. return orderedDirs
  327. }