handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package ftpd
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "os"
  7. "path"
  8. "strings"
  9. "time"
  10. ftpserver "github.com/fclairamb/ftpserverlib"
  11. "github.com/spf13/afero"
  12. "github.com/drakkan/sftpgo/v2/common"
  13. "github.com/drakkan/sftpgo/v2/dataprovider"
  14. "github.com/drakkan/sftpgo/v2/logger"
  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. if c.isListDirWithWildcards(path.Base(name), os.ErrNotExist) {
  124. return vfs.NewFileInfo(name, true, 0, time.Now(), false), nil
  125. }
  126. return nil, err
  127. }
  128. return fi, nil
  129. }
  130. // Name returns the name of this connection
  131. func (c *Connection) Name() string {
  132. return c.GetID()
  133. }
  134. // Chown changes the uid and gid of the named file
  135. func (c *Connection) Chown(name string, uid, gid int) error {
  136. c.UpdateLastActivity()
  137. return common.ErrOpUnsupported
  138. /*p, err := c.Fs.ResolvePath(name)
  139. if err != nil {
  140. return c.GetFsError(err)
  141. }
  142. attrs := common.StatAttributes{
  143. Flags: common.StatAttrUIDGID,
  144. UID: uid,
  145. GID: gid,
  146. }
  147. return c.SetStat(p, name, &attrs)*/
  148. }
  149. // Chmod changes the mode of the named file/directory
  150. func (c *Connection) Chmod(name string, mode os.FileMode) error {
  151. c.UpdateLastActivity()
  152. attrs := common.StatAttributes{
  153. Flags: common.StatAttrPerms,
  154. Mode: mode,
  155. }
  156. return c.SetStat(name, &attrs)
  157. }
  158. // Chtimes changes the access and modification times of the named file
  159. func (c *Connection) Chtimes(name string, atime time.Time, mtime time.Time) error {
  160. c.UpdateLastActivity()
  161. attrs := common.StatAttributes{
  162. Flags: common.StatAttrTimes,
  163. Atime: atime,
  164. Mtime: mtime,
  165. }
  166. return c.SetStat(name, &attrs)
  167. }
  168. // GetAvailableSpace implements ClientDriverExtensionAvailableSpace interface
  169. func (c *Connection) GetAvailableSpace(dirName string) (int64, error) {
  170. c.UpdateLastActivity()
  171. diskQuota, transferQuota := c.HasSpace(false, false, path.Join(dirName, "fakefile.txt"))
  172. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  173. return 0, nil
  174. }
  175. if diskQuota.AllowedSize == 0 && transferQuota.AllowedULSize == 0 && transferQuota.AllowedTotalSize == 0 {
  176. // no quota restrictions
  177. if c.User.Filters.MaxUploadFileSize > 0 {
  178. return c.User.Filters.MaxUploadFileSize, nil
  179. }
  180. fs, p, err := c.GetFsAndResolvedPath(dirName)
  181. if err != nil {
  182. return 0, err
  183. }
  184. statVFS, err := fs.GetAvailableDiskSize(p)
  185. if err != nil {
  186. return 0, c.GetFsError(fs, err)
  187. }
  188. return int64(statVFS.FreeSpace()), nil
  189. }
  190. allowedDiskSize := diskQuota.AllowedSize
  191. allowedUploadSize := transferQuota.AllowedULSize
  192. if transferQuota.AllowedTotalSize > 0 {
  193. allowedUploadSize = transferQuota.AllowedTotalSize
  194. }
  195. allowedSize := allowedDiskSize
  196. if allowedSize == 0 {
  197. allowedSize = allowedUploadSize
  198. } else {
  199. if allowedUploadSize > 0 && allowedUploadSize < allowedSize {
  200. allowedSize = allowedUploadSize
  201. }
  202. }
  203. // the available space is the minimum between MaxUploadFileSize, if setted,
  204. // and quota allowed size
  205. if c.User.Filters.MaxUploadFileSize > 0 {
  206. if c.User.Filters.MaxUploadFileSize < allowedSize {
  207. return c.User.Filters.MaxUploadFileSize, nil
  208. }
  209. }
  210. return allowedSize, nil
  211. }
  212. // AllocateSpace implements ClientDriverExtensionAllocate interface
  213. func (c *Connection) AllocateSpace(size int) error {
  214. c.UpdateLastActivity()
  215. // we treat ALLO as NOOP see RFC 959
  216. return nil
  217. }
  218. // RemoveDir implements ClientDriverExtensionRemoveDir
  219. func (c *Connection) RemoveDir(name string) error {
  220. c.UpdateLastActivity()
  221. return c.BaseConnection.RemoveDir(name)
  222. }
  223. // Symlink implements ClientDriverExtensionSymlink
  224. func (c *Connection) Symlink(oldname, newname string) error {
  225. c.UpdateLastActivity()
  226. return c.BaseConnection.CreateSymlink(oldname, newname)
  227. }
  228. // ReadDir implements ClientDriverExtensionFilelist
  229. func (c *Connection) ReadDir(name string) ([]os.FileInfo, error) {
  230. c.UpdateLastActivity()
  231. files, err := c.ListDir(name)
  232. if err != nil {
  233. baseName := path.Base(name)
  234. if c.isListDirWithWildcards(baseName, err) {
  235. // we only support wildcards for the last path level, for example:
  236. // - *.xml is supported
  237. // - dir*/*.xml is not supported
  238. return c.getListDirWithWildcards(path.Dir(name), baseName)
  239. }
  240. }
  241. return files, err
  242. }
  243. // GetHandle implements ClientDriverExtentionFileTransfer
  244. func (c *Connection) GetHandle(name string, flags int, offset int64) (ftpserver.FileTransfer, error) {
  245. c.UpdateLastActivity()
  246. fs, p, err := c.GetFsAndResolvedPath(name)
  247. if err != nil {
  248. return nil, err
  249. }
  250. if c.GetCommand() == "COMB" && !vfs.IsLocalOsFs(fs) {
  251. return nil, errCOMBNotSupported
  252. }
  253. if flags&os.O_WRONLY != 0 {
  254. return c.uploadFile(fs, p, name, flags)
  255. }
  256. return c.downloadFile(fs, p, name, offset)
  257. }
  258. func (c *Connection) downloadFile(fs vfs.Fs, fsPath, ftpPath string, offset int64) (ftpserver.FileTransfer, error) {
  259. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(ftpPath)) {
  260. return nil, c.GetPermissionDeniedError()
  261. }
  262. transferQuota := c.GetTransferQuota()
  263. if !transferQuota.HasDownloadSpace() {
  264. c.Log(logger.LevelInfo, "denying file read due to quota limits")
  265. return nil, c.GetReadQuotaExceededError()
  266. }
  267. if ok, policy := c.User.IsFileAllowed(ftpPath); !ok {
  268. c.Log(logger.LevelWarn, "reading file %#v is not allowed", ftpPath)
  269. return nil, c.GetErrorForDeniedFile(policy)
  270. }
  271. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreDownload, fsPath, ftpPath, 0, 0); err != nil {
  272. c.Log(logger.LevelDebug, "download for file %#v denied by pre action: %v", ftpPath, err)
  273. return nil, c.GetPermissionDeniedError()
  274. }
  275. file, r, cancelFn, err := fs.Open(fsPath, offset)
  276. if err != nil {
  277. c.Log(logger.LevelError, "could not open file %#v for reading: %+v", fsPath, err)
  278. return nil, c.GetFsError(fs, err)
  279. }
  280. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, fsPath, fsPath, ftpPath,
  281. common.TransferDownload, 0, 0, 0, 0, false, fs, transferQuota)
  282. baseTransfer.SetFtpMode(c.getFTPMode())
  283. t := newTransfer(baseTransfer, nil, r, offset)
  284. return t, nil
  285. }
  286. func (c *Connection) uploadFile(fs vfs.Fs, fsPath, ftpPath string, flags int) (ftpserver.FileTransfer, error) {
  287. if ok, _ := c.User.IsFileAllowed(ftpPath); !ok {
  288. c.Log(logger.LevelWarn, "writing file %#v is not allowed", ftpPath)
  289. return nil, ftpserver.ErrFileNameNotAllowed
  290. }
  291. filePath := fsPath
  292. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  293. filePath = fs.GetAtomicUploadPath(fsPath)
  294. }
  295. stat, statErr := fs.Lstat(fsPath)
  296. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  297. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(ftpPath)) {
  298. return nil, fmt.Errorf("%w, no upload permission", ftpserver.ErrFileNameNotAllowed)
  299. }
  300. return c.handleFTPUploadToNewFile(fs, flags, fsPath, filePath, ftpPath)
  301. }
  302. if statErr != nil {
  303. c.Log(logger.LevelError, "error performing file stat %#v: %+v", fsPath, statErr)
  304. return nil, c.GetFsError(fs, statErr)
  305. }
  306. // This happen if we upload a file that has the same name of an existing directory
  307. if stat.IsDir() {
  308. c.Log(logger.LevelError, "attempted to open a directory for writing to: %#v", fsPath)
  309. return nil, c.GetOpUnsupportedError()
  310. }
  311. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(ftpPath)) {
  312. return nil, fmt.Errorf("%w, no overwrite permission", ftpserver.ErrFileNameNotAllowed)
  313. }
  314. return c.handleFTPUploadToExistingFile(fs, flags, fsPath, filePath, stat.Size(), ftpPath)
  315. }
  316. func (c *Connection) handleFTPUploadToNewFile(fs vfs.Fs, flags int, resolvedPath, filePath, requestPath string) (ftpserver.FileTransfer, error) {
  317. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  318. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  319. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  320. return nil, ftpserver.ErrStorageExceeded
  321. }
  322. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  323. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  324. return nil, fmt.Errorf("%w, denied by pre-upload action", ftpserver.ErrFileNameNotAllowed)
  325. }
  326. file, w, cancelFn, err := fs.Create(filePath, flags)
  327. if err != nil {
  328. c.Log(logger.LevelError, "error creating file %#v, flags %v: %+v", resolvedPath, flags, err)
  329. return nil, c.GetFsError(fs, err)
  330. }
  331. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  332. // we can get an error only for resume
  333. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, 0, fs.IsUploadResumeSupported())
  334. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  335. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  336. baseTransfer.SetFtpMode(c.getFTPMode())
  337. t := newTransfer(baseTransfer, w, nil, 0)
  338. return t, nil
  339. }
  340. func (c *Connection) handleFTPUploadToExistingFile(fs vfs.Fs, flags int, resolvedPath, filePath string, fileSize int64,
  341. requestPath string) (ftpserver.FileTransfer, error) {
  342. var err error
  343. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  344. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  345. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  346. return nil, ftpserver.ErrStorageExceeded
  347. }
  348. minWriteOffset := int64(0)
  349. // ftpserverlib sets:
  350. // - os.O_WRONLY | os.O_APPEND for APPE and COMB
  351. // - os.O_WRONLY | os.O_CREATE for REST.
  352. // - os.O_WRONLY | os.O_CREATE | os.O_TRUNC if the command is not APPE and REST = 0
  353. // so if we don't have O_TRUNC is a resume.
  354. isResume := flags&os.O_TRUNC == 0
  355. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  356. // will return false in this case and we deny the upload before
  357. maxWriteSize, err := c.GetMaxWriteSize(diskQuota, isResume, fileSize, fs.IsUploadResumeSupported())
  358. if err != nil {
  359. c.Log(logger.LevelDebug, "unable to get max write size: %v", err)
  360. return nil, err
  361. }
  362. if err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, fileSize, flags); err != nil {
  363. c.Log(logger.LevelDebug, "upload for file %#v denied by pre action: %v", requestPath, err)
  364. return nil, fmt.Errorf("%w, denied by pre-upload action", ftpserver.ErrFileNameNotAllowed)
  365. }
  366. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  367. err = fs.Rename(resolvedPath, filePath)
  368. if err != nil {
  369. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %#v, dest: %#v, err: %+v",
  370. resolvedPath, filePath, err)
  371. return nil, c.GetFsError(fs, err)
  372. }
  373. }
  374. file, w, cancelFn, err := fs.Create(filePath, flags)
  375. if err != nil {
  376. c.Log(logger.LevelError, "error opening existing file, flags: %v, source: %#v, err: %+v", flags, filePath, err)
  377. return nil, c.GetFsError(fs, err)
  378. }
  379. initialSize := int64(0)
  380. truncatedSize := int64(0) // bytes truncated and not included in quota
  381. if isResume {
  382. c.Log(logger.LevelDebug, "resuming upload requested, file path: %#v initial size: %v", filePath, fileSize)
  383. minWriteOffset = fileSize
  384. initialSize = fileSize
  385. if vfs.IsSFTPFs(fs) && fs.IsUploadResumeSupported() {
  386. // we need this since we don't allow resume with wrong offset, we should fix this in pkg/sftp
  387. file.Seek(initialSize, io.SeekStart) //nolint:errcheck // for sftp seek simply set the offset
  388. }
  389. } else {
  390. if vfs.IsLocalOrSFTPFs(fs) {
  391. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  392. if err == nil {
  393. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  394. if vfolder.IsIncludedInUserQuota() {
  395. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  396. }
  397. } else {
  398. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  399. }
  400. } else {
  401. initialSize = fileSize
  402. truncatedSize = fileSize
  403. }
  404. }
  405. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  406. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  407. common.TransferUpload, minWriteOffset, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  408. baseTransfer.SetFtpMode(c.getFTPMode())
  409. t := newTransfer(baseTransfer, w, nil, 0)
  410. return t, nil
  411. }
  412. func (c *Connection) getListDirWithWildcards(dirName, pattern string) ([]os.FileInfo, error) {
  413. files, err := c.ListDir(dirName)
  414. if err != nil {
  415. return files, err
  416. }
  417. validIdx := 0
  418. relativeBase := getPathRelativeTo(c.clientContext.Path(), dirName)
  419. for _, fi := range files {
  420. match, err := path.Match(pattern, fi.Name())
  421. if err != nil {
  422. return files, err
  423. }
  424. if match {
  425. files[validIdx] = vfs.NewFileInfo(path.Join(relativeBase, fi.Name()), fi.IsDir(), fi.Size(),
  426. fi.ModTime(), true)
  427. validIdx++
  428. }
  429. }
  430. return files[:validIdx], nil
  431. }
  432. func (c *Connection) isListDirWithWildcards(name string, err error) bool {
  433. if errors.Is(err, c.GetNotExistError()) {
  434. lastCommand := c.clientContext.GetLastCommand()
  435. if lastCommand == "LIST" || lastCommand == "NLST" {
  436. return strings.ContainsAny(name, "*?[]")
  437. }
  438. }
  439. return false
  440. }
  441. func getPathRelativeTo(base, target string) string {
  442. var sb strings.Builder
  443. for {
  444. if base == target {
  445. return sb.String()
  446. }
  447. if !strings.HasSuffix(base, "/") {
  448. base += "/"
  449. }
  450. if strings.HasPrefix(target, base) {
  451. sb.WriteString(strings.TrimPrefix(target, base))
  452. return sb.String()
  453. }
  454. if base == "/" || base == "./" {
  455. return target
  456. }
  457. sb.WriteString("../")
  458. base = path.Dir(path.Clean(base))
  459. }
  460. }