handler.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package ftpd
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "time"
  9. ftpserver "github.com/fclairamb/ftpserverlib"
  10. "github.com/spf13/afero"
  11. "github.com/drakkan/sftpgo/v2/common"
  12. "github.com/drakkan/sftpgo/v2/dataprovider"
  13. "github.com/drakkan/sftpgo/v2/logger"
  14. "github.com/drakkan/sftpgo/v2/util"
  15. "github.com/drakkan/sftpgo/v2/vfs"
  16. )
  17. var (
  18. errNotImplemented = errors.New("not implemented")
  19. errCOMBNotSupported = errors.New("COMB is not supported for this filesystem")
  20. )
  21. // Connection details for an FTP connection.
  22. // It implements common.ActiveConnection and ftpserver.ClientDriver interfaces
  23. type Connection struct {
  24. *common.BaseConnection
  25. clientContext ftpserver.ClientContext
  26. }
  27. // GetClientVersion returns the connected client's version.
  28. // It returns "Unknown" if the client does not advertise its
  29. // version
  30. func (c *Connection) GetClientVersion() string {
  31. version := c.clientContext.GetClientVersion()
  32. if len(version) > 0 {
  33. return version
  34. }
  35. return "Unknown"
  36. }
  37. // GetLocalAddress returns local connection address
  38. func (c *Connection) GetLocalAddress() string {
  39. return c.clientContext.LocalAddr().String()
  40. }
  41. // GetRemoteAddress returns the connected client's address
  42. func (c *Connection) GetRemoteAddress() string {
  43. return c.clientContext.RemoteAddr().String()
  44. }
  45. // Disconnect disconnects the client
  46. func (c *Connection) Disconnect() error {
  47. return c.clientContext.Close()
  48. }
  49. // GetCommand returns the last received FTP command
  50. func (c *Connection) GetCommand() string {
  51. return c.clientContext.GetLastCommand()
  52. }
  53. // Create is not implemented we use ClientDriverExtentionFileTransfer
  54. func (c *Connection) Create(name string) (afero.File, error) {
  55. return nil, errNotImplemented
  56. }
  57. // Mkdir creates a directory using the connection filesystem
  58. func (c *Connection) Mkdir(name string, perm os.FileMode) error {
  59. c.UpdateLastActivity()
  60. return c.CreateDir(name)
  61. }
  62. // MkdirAll is not implemented, we don't need it
  63. func (c *Connection) MkdirAll(path string, perm os.FileMode) error {
  64. return errNotImplemented
  65. }
  66. // Open is not implemented we use ClientDriverExtentionFileTransfer and ClientDriverExtensionFileList
  67. func (c *Connection) Open(name string) (afero.File, error) {
  68. return nil, errNotImplemented
  69. }
  70. // OpenFile is not implemented we use ClientDriverExtentionFileTransfer
  71. func (c *Connection) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
  72. return nil, errNotImplemented
  73. }
  74. // Remove removes a file.
  75. // We implements ClientDriverExtensionRemoveDir for directories
  76. func (c *Connection) Remove(name string) error {
  77. c.UpdateLastActivity()
  78. fs, p, err := c.GetFsAndResolvedPath(name)
  79. if err != nil {
  80. return err
  81. }
  82. var fi os.FileInfo
  83. if fi, err = fs.Lstat(p); err != nil {
  84. c.Log(logger.LevelWarn, "failed to remove a file %#v: stat error: %+v", p, err)
  85. return c.GetFsError(fs, err)
  86. }
  87. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  88. c.Log(logger.LevelDebug, "cannot remove %#v is not a file/symlink", p)
  89. return c.GetGenericError(nil)
  90. }
  91. return c.RemoveFile(fs, p, name, fi)
  92. }
  93. // RemoveAll is not implemented, we don't need it
  94. func (c *Connection) RemoveAll(path string) error {
  95. return errNotImplemented
  96. }
  97. // Rename renames a file or a directory
  98. func (c *Connection) Rename(oldname, newname string) error {
  99. c.UpdateLastActivity()
  100. return c.BaseConnection.Rename(oldname, newname)
  101. }
  102. // Stat returns a FileInfo describing the named file/directory, or an error,
  103. // if any happens
  104. func (c *Connection) Stat(name string) (os.FileInfo, error) {
  105. c.UpdateLastActivity()
  106. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  107. return nil, c.GetPermissionDeniedError()
  108. }
  109. fi, err := c.DoStat(name, 0)
  110. if err != nil {
  111. c.Log(logger.LevelDebug, "error running stat on path %#v: %+v", name, err)
  112. return nil, err
  113. }
  114. return fi, nil
  115. }
  116. // Name returns the name of this connection
  117. func (c *Connection) Name() string {
  118. return c.GetID()
  119. }
  120. // Chown changes the uid and gid of the named file
  121. func (c *Connection) Chown(name string, uid, gid int) error {
  122. c.UpdateLastActivity()
  123. return common.ErrOpUnsupported
  124. /*p, err := c.Fs.ResolvePath(name)
  125. if err != nil {
  126. return c.GetFsError(err)
  127. }
  128. attrs := common.StatAttributes{
  129. Flags: common.StatAttrUIDGID,
  130. UID: uid,
  131. GID: gid,
  132. }
  133. return c.SetStat(p, name, &attrs)*/
  134. }
  135. // Chmod changes the mode of the named file/directory
  136. func (c *Connection) Chmod(name string, mode os.FileMode) error {
  137. c.UpdateLastActivity()
  138. attrs := common.StatAttributes{
  139. Flags: common.StatAttrPerms,
  140. Mode: mode,
  141. }
  142. return c.SetStat(name, &attrs)
  143. }
  144. // Chtimes changes the access and modification times of the named file
  145. func (c *Connection) Chtimes(name string, atime time.Time, mtime time.Time) error {
  146. c.UpdateLastActivity()
  147. attrs := common.StatAttributes{
  148. Flags: common.StatAttrTimes,
  149. Atime: atime,
  150. Mtime: mtime,
  151. }
  152. return c.SetStat(name, &attrs)
  153. }
  154. // GetAvailableSpace implements ClientDriverExtensionAvailableSpace interface
  155. func (c *Connection) GetAvailableSpace(dirName string) (int64, error) {
  156. c.UpdateLastActivity()
  157. quotaResult := c.HasSpace(false, false, path.Join(dirName, "fakefile.txt"))
  158. if !quotaResult.HasSpace {
  159. return 0, nil
  160. }
  161. if quotaResult.AllowedSize == 0 {
  162. // no quota restrictions
  163. if c.User.Filters.MaxUploadFileSize > 0 {
  164. return c.User.Filters.MaxUploadFileSize, nil
  165. }
  166. fs, p, err := c.GetFsAndResolvedPath(dirName)
  167. if err != nil {
  168. return 0, err
  169. }
  170. statVFS, err := fs.GetAvailableDiskSize(p)
  171. if err != nil {
  172. return 0, c.GetFsError(fs, err)
  173. }
  174. return int64(statVFS.FreeSpace()), nil
  175. }
  176. // the available space is the minimum between MaxUploadFileSize, if setted,
  177. // and quota allowed size
  178. if c.User.Filters.MaxUploadFileSize > 0 {
  179. if c.User.Filters.MaxUploadFileSize < quotaResult.AllowedSize {
  180. return c.User.Filters.MaxUploadFileSize, nil
  181. }
  182. }
  183. return quotaResult.AllowedSize, nil
  184. }
  185. // AllocateSpace implements ClientDriverExtensionAllocate interface
  186. func (c *Connection) AllocateSpace(size int) error {
  187. c.UpdateLastActivity()
  188. // check the max allowed file size first
  189. if c.User.Filters.MaxUploadFileSize > 0 && int64(size) > c.User.Filters.MaxUploadFileSize {
  190. return c.GetQuotaExceededError()
  191. }
  192. // we don't have a path here so we check home dir and any virtual folders
  193. // we return no error if there is space in any folder
  194. folders := []string{"/"}
  195. for _, v := range c.User.VirtualFolders {
  196. // the space is checked for the parent folder
  197. folders = append(folders, path.Join(v.VirtualPath, "fakefile.txt"))
  198. }
  199. for _, f := range folders {
  200. quotaResult := c.HasSpace(false, false, f)
  201. if quotaResult.HasSpace {
  202. if quotaResult.QuotaSize == 0 {
  203. // unlimited size is allowed
  204. return nil
  205. }
  206. if quotaResult.GetRemainingSize() > int64(size) {
  207. return nil
  208. }
  209. }
  210. }
  211. return c.GetQuotaExceededError()
  212. }
  213. // RemoveDir implements ClientDriverExtensionRemoveDir
  214. func (c *Connection) RemoveDir(name string) error {
  215. c.UpdateLastActivity()
  216. return c.BaseConnection.RemoveDir(name)
  217. }
  218. // Symlink implements ClientDriverExtensionSymlink
  219. func (c *Connection) Symlink(oldname, newname string) error {
  220. c.UpdateLastActivity()
  221. return c.BaseConnection.CreateSymlink(oldname, newname)
  222. }
  223. // ReadDir implements ClientDriverExtensionFilelist
  224. func (c *Connection) ReadDir(name string) ([]os.FileInfo, error) {
  225. c.UpdateLastActivity()
  226. files, err := c.ListDir(name)
  227. if err != nil {
  228. return files, err
  229. }
  230. if name != "/" {
  231. files = util.PrependFileInfo(files, vfs.NewFileInfo("..", true, 0, time.Now(), false))
  232. }
  233. files = util.PrependFileInfo(files, vfs.NewFileInfo(".", true, 0, time.Now(), false))
  234. return files, nil
  235. }
  236. // GetHandle implements ClientDriverExtentionFileTransfer
  237. func (c *Connection) GetHandle(name string, flags int, offset int64) (ftpserver.FileTransfer, error) {
  238. c.UpdateLastActivity()
  239. fs, p, err := c.GetFsAndResolvedPath(name)
  240. if err != nil {
  241. return nil, err
  242. }
  243. if c.GetCommand() == "COMB" && !vfs.IsLocalOsFs(fs) {
  244. return nil, errCOMBNotSupported
  245. }
  246. if flags&os.O_WRONLY != 0 {
  247. return c.uploadFile(fs, p, name, flags)
  248. }
  249. return c.downloadFile(fs, p, name, offset)
  250. }
  251. func (c *Connection) downloadFile(fs vfs.Fs, fsPath, ftpPath string, offset int64) (ftpserver.FileTransfer, error) {
  252. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(ftpPath)) {
  253. return nil, c.GetPermissionDeniedError()
  254. }
  255. if !c.User.IsFileAllowed(ftpPath) {
  256. c.Log(logger.LevelWarn, "reading file %#v is not allowed", ftpPath)
  257. return nil, c.GetPermissionDeniedError()
  258. }
  259. if err := common.ExecutePreAction(&c.User, common.OperationPreDownload, fsPath, ftpPath, c.GetProtocol(), 0, 0); err != nil {
  260. c.Log(logger.LevelDebug, "download for file %#v denied by pre action: %v", ftpPath, err)
  261. return nil, c.GetPermissionDeniedError()
  262. }
  263. file, r, cancelFn, err := fs.Open(fsPath, offset)
  264. if err != nil {
  265. c.Log(logger.LevelWarn, "could not open file %#v for reading: %+v", fsPath, err)
  266. return nil, c.GetFsError(fs, err)
  267. }
  268. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, fsPath, fsPath, ftpPath, common.TransferDownload,
  269. 0, 0, 0, false, fs)
  270. t := newTransfer(baseTransfer, nil, r, offset)
  271. return t, nil
  272. }
  273. func (c *Connection) uploadFile(fs vfs.Fs, fsPath, ftpPath string, flags int) (ftpserver.FileTransfer, error) {
  274. if !c.User.IsFileAllowed(ftpPath) {
  275. c.Log(logger.LevelWarn, "writing file %#v is not allowed", ftpPath)
  276. return nil, ftpserver.ErrFileNameNotAllowed
  277. }
  278. filePath := fsPath
  279. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  280. filePath = fs.GetAtomicUploadPath(fsPath)
  281. }
  282. stat, statErr := fs.Lstat(fsPath)
  283. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  284. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(ftpPath)) {
  285. return nil, fmt.Errorf("%w, no upload permission", ftpserver.ErrFileNameNotAllowed)
  286. }
  287. return c.handleFTPUploadToNewFile(fs, fsPath, filePath, ftpPath)
  288. }
  289. if statErr != nil {
  290. c.Log(logger.LevelError, "error performing file stat %#v: %+v", fsPath, statErr)
  291. return nil, c.GetFsError(fs, statErr)
  292. }
  293. // This happen if we upload a file that has the same name of an existing directory
  294. if stat.IsDir() {
  295. c.Log(logger.LevelWarn, "attempted to open a directory for writing to: %#v", fsPath)
  296. return nil, c.GetOpUnsupportedError()
  297. }
  298. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(ftpPath)) {
  299. return nil, fmt.Errorf("%w, no overwrite permission", ftpserver.ErrFileNameNotAllowed)
  300. }
  301. return c.handleFTPUploadToExistingFile(fs, flags, fsPath, filePath, stat.Size(), ftpPath)
  302. }
  303. func (c *Connection) handleFTPUploadToNewFile(fs vfs.Fs, resolvedPath, filePath, requestPath string) (ftpserver.FileTransfer, error) {
  304. quotaResult := c.HasSpace(true, false, requestPath)
  305. if !quotaResult.HasSpace {
  306. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  307. return nil, ftpserver.ErrStorageExceeded
  308. }
  309. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), 0, 0); err != nil {
  310. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  311. return nil, fmt.Errorf("%w, denied by pre-upload action", ftpserver.ErrFileNameNotAllowed)
  312. }
  313. file, w, cancelFn, err := fs.Create(filePath, 0)
  314. if err != nil {
  315. c.Log(logger.LevelWarn, "error creating file %#v: %+v", resolvedPath, err)
  316. return nil, c.GetFsError(fs, err)
  317. }
  318. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  319. // we can get an error only for resume
  320. maxWriteSize, _ := c.GetMaxWriteSize(quotaResult, false, 0, fs.IsUploadResumeSupported())
  321. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  322. common.TransferUpload, 0, 0, maxWriteSize, true, fs)
  323. t := newTransfer(baseTransfer, w, nil, 0)
  324. return t, nil
  325. }
  326. func (c *Connection) handleFTPUploadToExistingFile(fs vfs.Fs, flags int, resolvedPath, filePath string, fileSize int64,
  327. requestPath string) (ftpserver.FileTransfer, error) {
  328. var err error
  329. quotaResult := c.HasSpace(false, false, requestPath)
  330. if !quotaResult.HasSpace {
  331. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  332. return nil, ftpserver.ErrStorageExceeded
  333. }
  334. minWriteOffset := int64(0)
  335. // ftpserverlib sets:
  336. // - os.O_WRONLY | os.O_APPEND for APPE and COMB
  337. // - os.O_WRONLY | os.O_CREATE for REST.
  338. // - os.O_WRONLY | os.O_CREATE | os.O_TRUNC if the command is not APPE and REST = 0
  339. // so if we don't have O_TRUNC is a resume.
  340. isResume := flags&os.O_TRUNC == 0
  341. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  342. // will return false in this case and we deny the upload before
  343. maxWriteSize, err := c.GetMaxWriteSize(quotaResult, isResume, fileSize, fs.IsUploadResumeSupported())
  344. if err != nil {
  345. c.Log(logger.LevelDebug, "unable to get max write size: %v", err)
  346. return nil, err
  347. }
  348. if err := common.ExecutePreAction(&c.User, common.OperationPreUpload, resolvedPath, requestPath, c.GetProtocol(), fileSize, flags); err != nil {
  349. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  350. return nil, fmt.Errorf("%w, denied by pre-upload action", ftpserver.ErrFileNameNotAllowed)
  351. }
  352. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  353. err = fs.Rename(resolvedPath, filePath)
  354. if err != nil {
  355. c.Log(logger.LevelWarn, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  356. resolvedPath, filePath, err)
  357. return nil, c.GetFsError(fs, err)
  358. }
  359. }
  360. file, w, cancelFn, err := fs.Create(filePath, flags)
  361. if err != nil {
  362. c.Log(logger.LevelWarn, "error opening existing file, flags: %v, source: %#v, err: %+v", flags, filePath, err)
  363. return nil, c.GetFsError(fs, err)
  364. }
  365. initialSize := int64(0)
  366. if isResume {
  367. c.Log(logger.LevelDebug, "resuming upload requested, file path: %#v initial size: %v", filePath, fileSize)
  368. minWriteOffset = fileSize
  369. initialSize = fileSize
  370. if vfs.IsSFTPFs(fs) && fs.IsUploadResumeSupported() {
  371. // we need this since we don't allow resume with wrong offset, we should fix this in pkg/sftp
  372. file.Seek(initialSize, io.SeekStart) //nolint:errcheck // for sftp seek simply set the offset
  373. }
  374. } else {
  375. if vfs.IsLocalOrSFTPFs(fs) {
  376. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  377. if err == nil {
  378. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  379. if vfolder.IsIncludedInUserQuota() {
  380. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  381. }
  382. } else {
  383. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  384. }
  385. } else {
  386. initialSize = fileSize
  387. }
  388. }
  389. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  390. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  391. common.TransferUpload, minWriteOffset, initialSize, maxWriteSize, false, fs)
  392. t := newTransfer(baseTransfer, w, nil, 0)
  393. return t, nil
  394. }