handler.go 11 KB

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