handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package ftpd
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path"
  21. "strings"
  22. "time"
  23. ftpserver "github.com/fclairamb/ftpserverlib"
  24. "github.com/spf13/afero"
  25. "github.com/drakkan/sftpgo/v2/internal/common"
  26. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/vfs"
  29. )
  30. var (
  31. errNotImplemented = errors.New("not implemented")
  32. errCOMBNotSupported = errors.New("COMB is not supported for this filesystem")
  33. )
  34. // Connection details for an FTP connection.
  35. // It implements common.ActiveConnection and ftpserver.ClientDriver interfaces
  36. type Connection struct {
  37. *common.BaseConnection
  38. clientContext ftpserver.ClientContext
  39. doWildcardListDir bool
  40. }
  41. func (c *Connection) getFTPMode() string {
  42. if c.clientContext == nil {
  43. return ""
  44. }
  45. switch c.clientContext.GetLastDataChannel() {
  46. case ftpserver.DataChannelActive:
  47. return "active"
  48. case ftpserver.DataChannelPassive:
  49. return "passive"
  50. }
  51. return ""
  52. }
  53. // GetClientVersion returns the connected client's version.
  54. // It returns "Unknown" if the client does not advertise its
  55. // version
  56. func (c *Connection) GetClientVersion() string {
  57. version := c.clientContext.GetClientVersion()
  58. if len(version) > 0 {
  59. return version
  60. }
  61. return "Unknown"
  62. }
  63. // GetLocalAddress returns local connection address
  64. func (c *Connection) GetLocalAddress() string {
  65. return c.clientContext.LocalAddr().String()
  66. }
  67. // GetRemoteAddress returns the connected client's address
  68. func (c *Connection) GetRemoteAddress() string {
  69. return c.clientContext.RemoteAddr().String()
  70. }
  71. // Disconnect disconnects the client
  72. func (c *Connection) Disconnect() error {
  73. return c.clientContext.Close()
  74. }
  75. // GetCommand returns the last received FTP command
  76. func (c *Connection) GetCommand() string {
  77. return c.clientContext.GetLastCommand()
  78. }
  79. // Create is not implemented we use ClientDriverExtentionFileTransfer
  80. func (c *Connection) Create(name string) (afero.File, error) {
  81. return nil, errNotImplemented
  82. }
  83. // Mkdir creates a directory using the connection filesystem
  84. func (c *Connection) Mkdir(name string, perm os.FileMode) error {
  85. c.UpdateLastActivity()
  86. return c.CreateDir(name, true)
  87. }
  88. // MkdirAll is not implemented, we don't need it
  89. func (c *Connection) MkdirAll(path string, perm os.FileMode) error {
  90. return errNotImplemented
  91. }
  92. // Open is not implemented we use ClientDriverExtentionFileTransfer and ClientDriverExtensionFileList
  93. func (c *Connection) Open(name string) (afero.File, error) {
  94. return nil, errNotImplemented
  95. }
  96. // OpenFile is not implemented we use ClientDriverExtentionFileTransfer
  97. func (c *Connection) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
  98. return nil, errNotImplemented
  99. }
  100. // Remove removes a file.
  101. // We implements ClientDriverExtensionRemoveDir for directories
  102. func (c *Connection) Remove(name string) error {
  103. c.UpdateLastActivity()
  104. fs, p, err := c.GetFsAndResolvedPath(name)
  105. if err != nil {
  106. return err
  107. }
  108. var fi os.FileInfo
  109. if fi, err = fs.Lstat(p); err != nil {
  110. c.Log(logger.LevelError, "failed to remove file %q: stat error: %+v", p, err)
  111. return c.GetFsError(fs, err)
  112. }
  113. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  114. c.Log(logger.LevelError, "cannot remove %q is not a file/symlink", p)
  115. return c.GetGenericError(nil)
  116. }
  117. return c.RemoveFile(fs, p, name, fi)
  118. }
  119. // RemoveAll is not implemented, we don't need it
  120. func (c *Connection) RemoveAll(path string) error {
  121. return errNotImplemented
  122. }
  123. // Rename renames a file or a directory
  124. func (c *Connection) Rename(oldname, newname string) error {
  125. c.UpdateLastActivity()
  126. return c.BaseConnection.Rename(oldname, newname)
  127. }
  128. // Stat returns a FileInfo describing the named file/directory, or an error,
  129. // if any happens
  130. func (c *Connection) Stat(name string) (os.FileInfo, error) {
  131. c.UpdateLastActivity()
  132. c.doWildcardListDir = false
  133. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  134. return nil, c.GetPermissionDeniedError()
  135. }
  136. fi, err := c.DoStat(name, 0, true)
  137. if err != nil {
  138. if c.isListDirWithWildcards(path.Base(name)) {
  139. c.doWildcardListDir = true
  140. return vfs.NewFileInfo(name, true, 0, time.Unix(0, 0), false), nil
  141. }
  142. return nil, err
  143. }
  144. return fi, nil
  145. }
  146. // Name returns the name of this connection
  147. func (c *Connection) Name() string {
  148. return c.GetID()
  149. }
  150. // Chown changes the uid and gid of the named file
  151. func (c *Connection) Chown(name string, uid, gid int) error {
  152. c.UpdateLastActivity()
  153. return common.ErrOpUnsupported
  154. /*p, err := c.Fs.ResolvePath(name)
  155. if err != nil {
  156. return c.GetFsError(err)
  157. }
  158. attrs := common.StatAttributes{
  159. Flags: common.StatAttrUIDGID,
  160. UID: uid,
  161. GID: gid,
  162. }
  163. return c.SetStat(p, name, &attrs)*/
  164. }
  165. // Chmod changes the mode of the named file/directory
  166. func (c *Connection) Chmod(name string, mode os.FileMode) error {
  167. c.UpdateLastActivity()
  168. attrs := common.StatAttributes{
  169. Flags: common.StatAttrPerms,
  170. Mode: mode,
  171. }
  172. return c.SetStat(name, &attrs)
  173. }
  174. // Chtimes changes the access and modification times of the named file
  175. func (c *Connection) Chtimes(name string, atime time.Time, mtime time.Time) error {
  176. c.UpdateLastActivity()
  177. attrs := common.StatAttributes{
  178. Flags: common.StatAttrTimes,
  179. Atime: atime,
  180. Mtime: mtime,
  181. }
  182. return c.SetStat(name, &attrs)
  183. }
  184. // GetAvailableSpace implements ClientDriverExtensionAvailableSpace interface
  185. func (c *Connection) GetAvailableSpace(dirName string) (int64, error) {
  186. c.UpdateLastActivity()
  187. diskQuota, transferQuota := c.HasSpace(false, false, path.Join(dirName, "fakefile.txt"))
  188. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  189. return 0, nil
  190. }
  191. if diskQuota.AllowedSize == 0 && transferQuota.AllowedULSize == 0 && transferQuota.AllowedTotalSize == 0 {
  192. // no quota restrictions
  193. if c.User.Filters.MaxUploadFileSize > 0 {
  194. return c.User.Filters.MaxUploadFileSize, nil
  195. }
  196. fs, p, err := c.GetFsAndResolvedPath(dirName)
  197. if err != nil {
  198. return 0, err
  199. }
  200. statVFS, err := fs.GetAvailableDiskSize(p)
  201. if err != nil {
  202. return 0, c.GetFsError(fs, err)
  203. }
  204. return int64(statVFS.FreeSpace()), nil
  205. }
  206. allowedDiskSize := diskQuota.AllowedSize
  207. allowedUploadSize := transferQuota.AllowedULSize
  208. if transferQuota.AllowedTotalSize > 0 {
  209. allowedUploadSize = transferQuota.AllowedTotalSize
  210. }
  211. allowedSize := allowedDiskSize
  212. if allowedSize == 0 {
  213. allowedSize = allowedUploadSize
  214. } else {
  215. if allowedUploadSize > 0 && allowedUploadSize < allowedSize {
  216. allowedSize = allowedUploadSize
  217. }
  218. }
  219. // the available space is the minimum between MaxUploadFileSize, if setted,
  220. // and quota allowed size
  221. if c.User.Filters.MaxUploadFileSize > 0 {
  222. if c.User.Filters.MaxUploadFileSize < allowedSize {
  223. return c.User.Filters.MaxUploadFileSize, nil
  224. }
  225. }
  226. return allowedSize, nil
  227. }
  228. // AllocateSpace implements ClientDriverExtensionAllocate interface
  229. func (c *Connection) AllocateSpace(size int) error {
  230. c.UpdateLastActivity()
  231. // we treat ALLO as NOOP see RFC 959
  232. return nil
  233. }
  234. // RemoveDir implements ClientDriverExtensionRemoveDir
  235. func (c *Connection) RemoveDir(name string) error {
  236. c.UpdateLastActivity()
  237. return c.BaseConnection.RemoveDir(name)
  238. }
  239. // Symlink implements ClientDriverExtensionSymlink
  240. func (c *Connection) Symlink(oldname, newname string) error {
  241. c.UpdateLastActivity()
  242. return c.BaseConnection.CreateSymlink(oldname, newname)
  243. }
  244. // ReadDir implements ClientDriverExtensionFilelist
  245. func (c *Connection) ReadDir(name string) ([]os.FileInfo, error) {
  246. c.UpdateLastActivity()
  247. if c.doWildcardListDir {
  248. c.doWildcardListDir = false
  249. baseName := path.Base(name)
  250. // we only support wildcards for the last path level, for example:
  251. // - *.xml is supported
  252. // - dir*/*.xml is not supported
  253. name = path.Dir(name)
  254. c.clientContext.SetListPath(name)
  255. return c.getListDirWithWildcards(name, baseName)
  256. }
  257. return c.ListDir(name)
  258. }
  259. // GetHandle implements ClientDriverExtentionFileTransfer
  260. func (c *Connection) GetHandle(name string, flags int, offset int64) (ftpserver.FileTransfer, error) {
  261. c.UpdateLastActivity()
  262. fs, p, err := c.GetFsAndResolvedPath(name)
  263. if err != nil {
  264. return nil, err
  265. }
  266. if c.GetCommand() == "COMB" && !vfs.IsLocalOsFs(fs) {
  267. return nil, errCOMBNotSupported
  268. }
  269. if flags&os.O_WRONLY != 0 {
  270. return c.uploadFile(fs, p, name, flags)
  271. }
  272. return c.downloadFile(fs, p, name, offset)
  273. }
  274. func (c *Connection) downloadFile(fs vfs.Fs, fsPath, ftpPath string, offset int64) (ftpserver.FileTransfer, error) {
  275. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(ftpPath)) {
  276. return nil, c.GetPermissionDeniedError()
  277. }
  278. transferQuota := c.GetTransferQuota()
  279. if !transferQuota.HasDownloadSpace() {
  280. c.Log(logger.LevelInfo, "denying file read due to quota limits")
  281. return nil, c.GetReadQuotaExceededError()
  282. }
  283. if ok, policy := c.User.IsFileAllowed(ftpPath); !ok {
  284. c.Log(logger.LevelWarn, "reading file %q is not allowed", ftpPath)
  285. return nil, c.GetErrorForDeniedFile(policy)
  286. }
  287. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreDownload, fsPath, ftpPath, 0, 0); err != nil {
  288. c.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", ftpPath, err)
  289. return nil, c.GetPermissionDeniedError()
  290. }
  291. file, r, cancelFn, err := fs.Open(fsPath, offset)
  292. if err != nil {
  293. c.Log(logger.LevelError, "could not open file %q for reading: %+v", fsPath, err)
  294. return nil, c.GetFsError(fs, err)
  295. }
  296. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, fsPath, fsPath, ftpPath,
  297. common.TransferDownload, 0, 0, 0, 0, false, fs, transferQuota)
  298. baseTransfer.SetFtpMode(c.getFTPMode())
  299. t := newTransfer(baseTransfer, nil, r, offset)
  300. return t, nil
  301. }
  302. func (c *Connection) uploadFile(fs vfs.Fs, fsPath, ftpPath string, flags int) (ftpserver.FileTransfer, error) {
  303. if ok, _ := c.User.IsFileAllowed(ftpPath); !ok {
  304. c.Log(logger.LevelWarn, "writing file %q is not allowed", ftpPath)
  305. return nil, ftpserver.ErrFileNameNotAllowed
  306. }
  307. filePath := fsPath
  308. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  309. filePath = fs.GetAtomicUploadPath(fsPath)
  310. }
  311. stat, statErr := fs.Lstat(fsPath)
  312. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  313. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(ftpPath)) {
  314. return nil, fmt.Errorf("%w, no upload permission", ftpserver.ErrFileNameNotAllowed)
  315. }
  316. return c.handleFTPUploadToNewFile(fs, flags, fsPath, filePath, ftpPath)
  317. }
  318. if statErr != nil {
  319. c.Log(logger.LevelError, "error performing file stat %q: %+v", fsPath, statErr)
  320. return nil, c.GetFsError(fs, statErr)
  321. }
  322. // This happen if we upload a file that has the same name of an existing directory
  323. if stat.IsDir() {
  324. c.Log(logger.LevelError, "attempted to open a directory for writing to: %q", fsPath)
  325. return nil, c.GetOpUnsupportedError()
  326. }
  327. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(ftpPath)) {
  328. return nil, fmt.Errorf("%w, no overwrite permission", ftpserver.ErrFileNameNotAllowed)
  329. }
  330. return c.handleFTPUploadToExistingFile(fs, flags, fsPath, filePath, stat.Size(), ftpPath)
  331. }
  332. func (c *Connection) handleFTPUploadToNewFile(fs vfs.Fs, flags int, resolvedPath, filePath, requestPath string) (ftpserver.FileTransfer, error) {
  333. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  334. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  335. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  336. return nil, ftpserver.ErrStorageExceeded
  337. }
  338. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  339. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  340. return nil, ftpserver.ErrFileNameNotAllowed
  341. }
  342. file, w, cancelFn, err := fs.Create(filePath, flags)
  343. if err != nil {
  344. c.Log(logger.LevelError, "error creating file %q, flags %v: %+v", resolvedPath, flags, err)
  345. return nil, c.GetFsError(fs, err)
  346. }
  347. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  348. // we can get an error only for resume
  349. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, 0, fs.IsUploadResumeSupported())
  350. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  351. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  352. baseTransfer.SetFtpMode(c.getFTPMode())
  353. t := newTransfer(baseTransfer, w, nil, 0)
  354. return t, nil
  355. }
  356. func (c *Connection) handleFTPUploadToExistingFile(fs vfs.Fs, flags int, resolvedPath, filePath string, fileSize int64,
  357. requestPath string) (ftpserver.FileTransfer, error) {
  358. var err error
  359. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  360. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  361. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  362. return nil, ftpserver.ErrStorageExceeded
  363. }
  364. minWriteOffset := int64(0)
  365. // ftpserverlib sets:
  366. // - os.O_WRONLY | os.O_APPEND for APPE and COMB
  367. // - os.O_WRONLY | os.O_CREATE for REST.
  368. // - os.O_WRONLY | os.O_CREATE | os.O_TRUNC if the command is not APPE and REST = 0
  369. // so if we don't have O_TRUNC is a resume.
  370. isResume := flags&os.O_TRUNC == 0
  371. // if there is a size limit remaining size cannot be 0 here, since quotaResult.HasSpace
  372. // will return false in this case and we deny the upload before
  373. maxWriteSize, err := c.GetMaxWriteSize(diskQuota, isResume, fileSize, fs.IsUploadResumeSupported())
  374. if err != nil {
  375. c.Log(logger.LevelDebug, "unable to get max write size: %v", err)
  376. return nil, err
  377. }
  378. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, fileSize, flags); err != nil {
  379. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  380. return nil, ftpserver.ErrFileNameNotAllowed
  381. }
  382. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  383. _, _, err = fs.Rename(resolvedPath, filePath)
  384. if err != nil {
  385. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %+v",
  386. resolvedPath, filePath, err)
  387. return nil, c.GetFsError(fs, err)
  388. }
  389. }
  390. file, w, cancelFn, err := fs.Create(filePath, flags)
  391. if err != nil {
  392. c.Log(logger.LevelError, "error opening existing file, flags: %v, source: %q, err: %+v", flags, filePath, err)
  393. return nil, c.GetFsError(fs, err)
  394. }
  395. initialSize := int64(0)
  396. truncatedSize := int64(0) // bytes truncated and not included in quota
  397. if isResume {
  398. c.Log(logger.LevelDebug, "resuming upload requested, file path: %q initial size: %v", filePath, fileSize)
  399. minWriteOffset = fileSize
  400. initialSize = fileSize
  401. if vfs.IsSFTPFs(fs) && fs.IsUploadResumeSupported() {
  402. // we need this since we don't allow resume with wrong offset, we should fix this in pkg/sftp
  403. file.Seek(initialSize, io.SeekStart) //nolint:errcheck // for sftp seek simply set the offset
  404. }
  405. } else {
  406. if vfs.HasTruncateSupport(fs) {
  407. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  408. if err == nil {
  409. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -fileSize, false) //nolint:errcheck
  410. if vfolder.IsIncludedInUserQuota() {
  411. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  412. }
  413. } else {
  414. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  415. }
  416. } else {
  417. initialSize = fileSize
  418. truncatedSize = fileSize
  419. }
  420. }
  421. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  422. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  423. common.TransferUpload, minWriteOffset, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  424. baseTransfer.SetFtpMode(c.getFTPMode())
  425. t := newTransfer(baseTransfer, w, nil, 0)
  426. return t, nil
  427. }
  428. func (c *Connection) getListDirWithWildcards(dirName, pattern string) ([]os.FileInfo, error) {
  429. files, err := c.ListDir(dirName)
  430. if err != nil {
  431. return files, err
  432. }
  433. validIdx := 0
  434. var relativeBase string
  435. if c.clientContext.GetLastCommand() != "NLST" {
  436. relativeBase = getPathRelativeTo(c.clientContext.Path(), dirName)
  437. }
  438. for _, fi := range files {
  439. match, err := path.Match(pattern, fi.Name())
  440. if err != nil {
  441. return files, err
  442. }
  443. if match {
  444. files[validIdx] = vfs.NewFileInfo(path.Join(relativeBase, fi.Name()), fi.IsDir(), fi.Size(),
  445. fi.ModTime(), true)
  446. validIdx++
  447. }
  448. }
  449. return files[:validIdx], nil
  450. }
  451. func (c *Connection) isListDirWithWildcards(name string) bool {
  452. if strings.ContainsAny(name, "*?[]^") {
  453. lastCommand := c.clientContext.GetLastCommand()
  454. return lastCommand == "LIST" || lastCommand == "NLST"
  455. }
  456. return false
  457. }
  458. func getPathRelativeTo(base, target string) string {
  459. var sb strings.Builder
  460. for {
  461. if base == target {
  462. return sb.String()
  463. }
  464. if !strings.HasSuffix(base, "/") {
  465. base += "/"
  466. }
  467. if strings.HasPrefix(target, base) {
  468. sb.WriteString(strings.TrimPrefix(target, base))
  469. return sb.String()
  470. }
  471. if base == "/" || base == "./" {
  472. return target
  473. }
  474. sb.WriteString("../")
  475. base = path.Dir(path.Clean(base))
  476. }
  477. }