handler.go 15 KB

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