handler.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. // Copyright (C) 2019 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 sftpd
  15. import (
  16. "io"
  17. "net"
  18. "os"
  19. "path"
  20. "time"
  21. "github.com/pkg/sftp"
  22. "github.com/sftpgo/sdk"
  23. "github.com/drakkan/sftpgo/v2/internal/common"
  24. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  25. "github.com/drakkan/sftpgo/v2/internal/logger"
  26. "github.com/drakkan/sftpgo/v2/internal/util"
  27. "github.com/drakkan/sftpgo/v2/internal/vfs"
  28. )
  29. // Connection details for an authenticated user
  30. type Connection struct {
  31. *common.BaseConnection
  32. // client's version string
  33. ClientVersion string
  34. // Remote address for this connection
  35. RemoteAddr net.Addr
  36. LocalAddr net.Addr
  37. channel io.ReadWriteCloser
  38. command string
  39. }
  40. // GetClientVersion returns the connected client's version
  41. func (c *Connection) GetClientVersion() string {
  42. return c.ClientVersion
  43. }
  44. // GetLocalAddress returns local connection address
  45. func (c *Connection) GetLocalAddress() string {
  46. if c.LocalAddr == nil {
  47. return ""
  48. }
  49. return c.LocalAddr.String()
  50. }
  51. // GetRemoteAddress returns the connected client's address
  52. func (c *Connection) GetRemoteAddress() string {
  53. if c.RemoteAddr == nil {
  54. return ""
  55. }
  56. return c.RemoteAddr.String()
  57. }
  58. // GetCommand returns the SSH command, if any
  59. func (c *Connection) GetCommand() string {
  60. return c.command
  61. }
  62. // Fileread creates a reader for a file on the system and returns the reader back.
  63. func (c *Connection) Fileread(request *sftp.Request) (io.ReaderAt, error) {
  64. c.UpdateLastActivity()
  65. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(request.Filepath)) {
  66. return nil, sftp.ErrSSHFxPermissionDenied
  67. }
  68. if err := common.Connections.IsNewTransferAllowed(c.User.Username); err != nil {
  69. c.Log(logger.LevelInfo, "denying file read due to transfer count limits")
  70. return nil, c.GetPermissionDeniedError()
  71. }
  72. transferQuota := c.GetTransferQuota()
  73. if !transferQuota.HasDownloadSpace() {
  74. c.Log(logger.LevelInfo, "denying file read due to quota limits")
  75. return nil, c.GetReadQuotaExceededError()
  76. }
  77. if ok, policy := c.User.IsFileAllowed(request.Filepath); !ok {
  78. c.Log(logger.LevelWarn, "reading file %q is not allowed", request.Filepath)
  79. return nil, c.GetErrorForDeniedFile(policy)
  80. }
  81. fs, p, err := c.GetFsAndResolvedPath(request.Filepath)
  82. if err != nil {
  83. return nil, err
  84. }
  85. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreDownload, p, request.Filepath, 0, 0); err != nil {
  86. c.Log(logger.LevelDebug, "download for file %q denied by pre action: %v", request.Filepath, err)
  87. return nil, c.GetPermissionDeniedError()
  88. }
  89. file, r, cancelFn, err := fs.Open(p, 0)
  90. if err != nil {
  91. c.Log(logger.LevelError, "could not open file %q for reading: %+v", p, err)
  92. return nil, c.GetFsError(fs, err)
  93. }
  94. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, p, p, request.Filepath, common.TransferDownload,
  95. 0, 0, 0, 0, false, fs, transferQuota)
  96. t := newTransfer(baseTransfer, nil, r, nil)
  97. return t, nil
  98. }
  99. // OpenFile implements OpenFileWriter interface
  100. func (c *Connection) OpenFile(request *sftp.Request) (sftp.WriterAtReaderAt, error) {
  101. return c.handleFilewrite(request)
  102. }
  103. // Filewrite handles the write actions for a file on the system.
  104. func (c *Connection) Filewrite(request *sftp.Request) (io.WriterAt, error) {
  105. return c.handleFilewrite(request)
  106. }
  107. func (c *Connection) handleFilewrite(request *sftp.Request) (sftp.WriterAtReaderAt, error) { //nolint:gocyclo
  108. c.UpdateLastActivity()
  109. if err := common.Connections.IsNewTransferAllowed(c.User.Username); err != nil {
  110. c.Log(logger.LevelInfo, "denying file write due to transfer count limits")
  111. return nil, c.GetPermissionDeniedError()
  112. }
  113. if ok, _ := c.User.IsFileAllowed(request.Filepath); !ok {
  114. c.Log(logger.LevelWarn, "writing file %q is not allowed", request.Filepath)
  115. return nil, c.GetPermissionDeniedError()
  116. }
  117. fs, p, err := c.GetFsAndResolvedPath(request.Filepath)
  118. if err != nil {
  119. return nil, err
  120. }
  121. filePath := p
  122. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  123. filePath = fs.GetAtomicUploadPath(p)
  124. }
  125. var errForRead error
  126. if !vfs.HasOpenRWSupport(fs) && request.Pflags().Read {
  127. // read and write mode is only supported for local filesystem
  128. errForRead = sftp.ErrSSHFxOpUnsupported
  129. }
  130. if !c.User.HasPerm(dataprovider.PermDownload, path.Dir(request.Filepath)) {
  131. // we can try to read only for local fs here, see above.
  132. // os.ErrPermission will become sftp.ErrSSHFxPermissionDenied when sent to
  133. // the client
  134. errForRead = os.ErrPermission
  135. }
  136. stat, statErr := fs.Lstat(p)
  137. if (statErr == nil && stat.Mode()&os.ModeSymlink != 0) || fs.IsNotExist(statErr) {
  138. if !c.User.HasPerm(dataprovider.PermUpload, path.Dir(request.Filepath)) {
  139. return nil, sftp.ErrSSHFxPermissionDenied
  140. }
  141. return c.handleSFTPUploadToNewFile(fs, request.Pflags(), p, filePath, request.Filepath, errForRead)
  142. }
  143. if statErr != nil {
  144. c.Log(logger.LevelError, "error performing file stat %q: %+v", p, statErr)
  145. return nil, c.GetFsError(fs, statErr)
  146. }
  147. // This happen if we upload a file that has the same name of an existing directory
  148. if stat.IsDir() {
  149. c.Log(logger.LevelError, "attempted to open a directory for writing to: %q", p)
  150. return nil, sftp.ErrSSHFxOpUnsupported
  151. }
  152. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(request.Filepath)) {
  153. return nil, sftp.ErrSSHFxPermissionDenied
  154. }
  155. return c.handleSFTPUploadToExistingFile(fs, request.Pflags(), p, filePath, stat.Size(), request.Filepath, errForRead)
  156. }
  157. // Filecmd hander for basic SFTP system calls related to files, but not anything to do with reading
  158. // or writing to those files.
  159. func (c *Connection) Filecmd(request *sftp.Request) error {
  160. c.UpdateLastActivity()
  161. switch request.Method {
  162. case "Setstat":
  163. return c.handleSFTPSetstat(request)
  164. case "Rename":
  165. if err := c.Rename(request.Filepath, request.Target); err != nil {
  166. return err
  167. }
  168. case "Rmdir":
  169. return c.RemoveDir(request.Filepath)
  170. case "Mkdir":
  171. err := c.CreateDir(request.Filepath, true)
  172. if err != nil {
  173. return err
  174. }
  175. case "Symlink":
  176. if err := c.CreateSymlink(request.Filepath, request.Target); err != nil {
  177. return err
  178. }
  179. case "Remove":
  180. return c.handleSFTPRemove(request)
  181. default:
  182. return sftp.ErrSSHFxOpUnsupported
  183. }
  184. return sftp.ErrSSHFxOk
  185. }
  186. // Filelist is the handler for SFTP filesystem list calls. This will handle calls to list the contents of
  187. // a directory as well as perform file/folder stat calls.
  188. func (c *Connection) Filelist(request *sftp.Request) (sftp.ListerAt, error) {
  189. c.UpdateLastActivity()
  190. switch request.Method {
  191. case "List":
  192. lister, err := c.ListDir(request.Filepath)
  193. if err != nil {
  194. return nil, err
  195. }
  196. modTime := time.Unix(0, 0)
  197. if request.Filepath != "/" {
  198. lister.Prepend(vfs.NewFileInfo("..", true, 0, modTime, false))
  199. }
  200. lister.Prepend(vfs.NewFileInfo(".", true, 0, modTime, false))
  201. return lister, nil
  202. case "Stat":
  203. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(request.Filepath)) {
  204. return nil, sftp.ErrSSHFxPermissionDenied
  205. }
  206. s, err := c.DoStat(request.Filepath, 0, true)
  207. if err != nil {
  208. return nil, err
  209. }
  210. return listerAt([]os.FileInfo{s}), nil
  211. default:
  212. return nil, sftp.ErrSSHFxOpUnsupported
  213. }
  214. }
  215. // Readlink implements the ReadlinkFileLister interface
  216. func (c *Connection) Readlink(filePath string) (string, error) {
  217. if err := c.canReadLink(filePath); err != nil {
  218. return "", err
  219. }
  220. fs, p, err := c.GetFsAndResolvedPath(filePath)
  221. if err != nil {
  222. return "", err
  223. }
  224. s, err := fs.Readlink(p)
  225. if err != nil {
  226. c.Log(logger.LevelDebug, "error running readlink on path %q: %+v", p, err)
  227. return "", c.GetFsError(fs, err)
  228. }
  229. if err := c.canReadLink(s); err != nil {
  230. return "", err
  231. }
  232. return s, nil
  233. }
  234. // Lstat implements LstatFileLister interface
  235. func (c *Connection) Lstat(request *sftp.Request) (sftp.ListerAt, error) {
  236. c.UpdateLastActivity()
  237. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(request.Filepath)) {
  238. return nil, sftp.ErrSSHFxPermissionDenied
  239. }
  240. s, err := c.DoStat(request.Filepath, 1, true)
  241. if err != nil {
  242. return nil, err
  243. }
  244. return listerAt([]os.FileInfo{s}), nil
  245. }
  246. // RealPath implements the RealPathFileLister interface
  247. func (c *Connection) RealPath(p string) (string, error) {
  248. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(p)) {
  249. return "", sftp.ErrSSHFxPermissionDenied
  250. }
  251. if c.User.Filters.StartDirectory == "" {
  252. p = util.CleanPath(p)
  253. } else {
  254. p = util.CleanPathWithBase(c.User.Filters.StartDirectory, p)
  255. }
  256. fs, fsPath, err := c.GetFsAndResolvedPath(p)
  257. if err != nil {
  258. return "", err
  259. }
  260. if realPather, ok := fs.(vfs.FsRealPather); ok {
  261. realPath, err := realPather.RealPath(fsPath)
  262. if err != nil {
  263. return "", c.GetFsError(fs, err)
  264. }
  265. return realPath, nil
  266. }
  267. return p, nil
  268. }
  269. // StatVFS implements StatVFSFileCmder interface
  270. func (c *Connection) StatVFS(r *sftp.Request) (*sftp.StatVFS, error) {
  271. c.UpdateLastActivity()
  272. // we are assuming that r.Filepath is a dir, this could be wrong but should
  273. // not produce any side effect here.
  274. // we don't consider c.User.Filters.MaxUploadFileSize, we return disk stats here
  275. // not the limit for a single file upload
  276. quotaResult, _ := c.HasSpace(true, true, path.Join(r.Filepath, "fakefile.txt"))
  277. fs, p, err := c.GetFsAndResolvedPath(r.Filepath)
  278. if err != nil {
  279. return nil, err
  280. }
  281. if !quotaResult.HasSpace {
  282. return c.getStatVFSFromQuotaResult(fs, p, quotaResult)
  283. }
  284. if quotaResult.QuotaSize == 0 && quotaResult.QuotaFiles == 0 {
  285. // no quota restrictions
  286. statvfs, err := fs.GetAvailableDiskSize(p)
  287. if err == vfs.ErrStorageSizeUnavailable {
  288. return c.getStatVFSFromQuotaResult(fs, p, quotaResult)
  289. }
  290. return statvfs, err
  291. }
  292. // there is free space but some limits are configured
  293. return c.getStatVFSFromQuotaResult(fs, p, quotaResult)
  294. }
  295. func (c *Connection) canReadLink(name string) error {
  296. if !c.User.HasPerm(dataprovider.PermListItems, path.Dir(name)) {
  297. return sftp.ErrSSHFxPermissionDenied
  298. }
  299. ok, policy := c.User.IsFileAllowed(name)
  300. if !ok && policy == sdk.DenyPolicyHide {
  301. return sftp.ErrSSHFxNoSuchFile
  302. }
  303. return nil
  304. }
  305. func (c *Connection) handleSFTPSetstat(request *sftp.Request) error {
  306. attrs := common.StatAttributes{
  307. Flags: 0,
  308. }
  309. if request.Attributes() != nil {
  310. if request.AttrFlags().Permissions {
  311. attrs.Flags |= common.StatAttrPerms
  312. attrs.Mode = request.Attributes().FileMode()
  313. }
  314. if request.AttrFlags().UidGid {
  315. attrs.Flags |= common.StatAttrUIDGID
  316. attrs.UID = int(request.Attributes().UID)
  317. attrs.GID = int(request.Attributes().GID)
  318. }
  319. if request.AttrFlags().Acmodtime {
  320. attrs.Flags |= common.StatAttrTimes
  321. attrs.Atime = time.Unix(int64(request.Attributes().Atime), 0)
  322. attrs.Mtime = time.Unix(int64(request.Attributes().Mtime), 0)
  323. }
  324. if request.AttrFlags().Size {
  325. attrs.Flags |= common.StatAttrSize
  326. attrs.Size = int64(request.Attributes().Size)
  327. }
  328. }
  329. return c.SetStat(request.Filepath, &attrs)
  330. }
  331. func (c *Connection) handleSFTPRemove(request *sftp.Request) error {
  332. fs, fsPath, err := c.GetFsAndResolvedPath(request.Filepath)
  333. if err != nil {
  334. return err
  335. }
  336. var fi os.FileInfo
  337. if fi, err = fs.Lstat(fsPath); err != nil {
  338. c.Log(logger.LevelDebug, "failed to remove file %q: stat error: %+v", fsPath, err)
  339. return c.GetFsError(fs, err)
  340. }
  341. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  342. c.Log(logger.LevelDebug, "cannot remove %q is not a file/symlink", fsPath)
  343. return sftp.ErrSSHFxFailure
  344. }
  345. return c.RemoveFile(fs, fsPath, request.Filepath, fi)
  346. }
  347. func (c *Connection) handleSFTPUploadToNewFile(fs vfs.Fs, pflags sftp.FileOpenFlags, resolvedPath, filePath, requestPath string, errForRead error) (sftp.WriterAtReaderAt, error) {
  348. diskQuota, transferQuota := c.HasSpace(true, false, requestPath)
  349. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  350. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  351. return nil, c.GetQuotaExceededError()
  352. }
  353. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, 0, 0); err != nil {
  354. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  355. return nil, c.GetPermissionDeniedError()
  356. }
  357. osFlags := getOSOpenFlags(pflags)
  358. file, w, cancelFn, err := fs.Create(filePath, osFlags, c.GetCreateChecks(requestPath, true, false))
  359. if err != nil {
  360. c.Log(logger.LevelError, "error creating file %q, os flags %d, pflags %+v: %+v", resolvedPath, osFlags, pflags, err)
  361. return nil, c.GetFsError(fs, err)
  362. }
  363. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  364. // we can get an error only for resume
  365. maxWriteSize, _ := c.GetMaxWriteSize(diskQuota, false, 0, fs.IsUploadResumeSupported())
  366. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  367. common.TransferUpload, 0, 0, maxWriteSize, 0, true, fs, transferQuota)
  368. t := newTransfer(baseTransfer, w, nil, errForRead)
  369. return t, nil
  370. }
  371. func (c *Connection) handleSFTPUploadToExistingFile(fs vfs.Fs, pflags sftp.FileOpenFlags, resolvedPath, filePath string,
  372. fileSize int64, requestPath string, errForRead error) (sftp.WriterAtReaderAt, error) {
  373. var err error
  374. diskQuota, transferQuota := c.HasSpace(false, false, requestPath)
  375. if !diskQuota.HasSpace || !transferQuota.HasUploadSpace() {
  376. c.Log(logger.LevelInfo, "denying file write due to quota limits")
  377. return nil, c.GetQuotaExceededError()
  378. }
  379. osFlags := getOSOpenFlags(pflags)
  380. minWriteOffset := int64(0)
  381. isTruncate := osFlags&os.O_TRUNC != 0
  382. // for upload resumes OpenSSH sets the APPEND flag while WinSCP does not set it,
  383. // so we suppose this is an upload resume if the TRUNCATE flag is not set
  384. isResume := !isTruncate
  385. // if there is a size limit the remaining size cannot be 0 here, since quotaResult.HasSpace
  386. // will return false in this case and we deny the upload before.
  387. // For Cloud FS GetMaxWriteSize will return unsupported operation
  388. maxWriteSize, err := c.GetMaxWriteSize(diskQuota, isResume, fileSize, vfs.IsUploadResumeSupported(fs, fileSize))
  389. if err != nil {
  390. c.Log(logger.LevelDebug, "unable to get max write size for file %q is resume? %t: %v",
  391. requestPath, isResume, err)
  392. return nil, err
  393. }
  394. if _, err := common.ExecutePreAction(c.BaseConnection, common.OperationPreUpload, resolvedPath, requestPath, fileSize, osFlags); err != nil {
  395. c.Log(logger.LevelDebug, "upload for file %q denied by pre action: %v", requestPath, err)
  396. return nil, c.GetPermissionDeniedError()
  397. }
  398. if common.Config.IsAtomicUploadEnabled() && fs.IsAtomicUploadSupported() {
  399. _, _, err = fs.Rename(resolvedPath, filePath, 0)
  400. if err != nil {
  401. c.Log(logger.LevelError, "error renaming existing file for atomic upload, source: %q, dest: %q, err: %+v",
  402. resolvedPath, filePath, err)
  403. return nil, c.GetFsError(fs, err)
  404. }
  405. }
  406. file, w, cancelFn, err := fs.Create(filePath, osFlags, c.GetCreateChecks(requestPath, false, isResume))
  407. if err != nil {
  408. c.Log(logger.LevelError, "error opening existing file, os flags %v, pflags: %+v, source: %q, err: %+v",
  409. osFlags, pflags, filePath, err)
  410. return nil, c.GetFsError(fs, err)
  411. }
  412. initialSize := int64(0)
  413. truncatedSize := int64(0) // bytes truncated and not included in quota
  414. if isResume {
  415. c.Log(logger.LevelDebug, "resuming upload requested, file path %q initial size: %d, has append flag %t",
  416. filePath, fileSize, pflags.Append)
  417. // enforce min write offset only if the client passed the APPEND flag or the filesystem
  418. // supports emulated resume
  419. if pflags.Append || !fs.IsUploadResumeSupported() {
  420. minWriteOffset = fileSize
  421. }
  422. initialSize = fileSize
  423. } else {
  424. if isTruncate && vfs.HasTruncateSupport(fs) {
  425. c.updateQuotaAfterTruncate(requestPath, fileSize)
  426. } else {
  427. initialSize = fileSize
  428. truncatedSize = fileSize
  429. }
  430. }
  431. vfs.SetPathPermissions(fs, filePath, c.User.GetUID(), c.User.GetGID())
  432. baseTransfer := common.NewBaseTransfer(file, c.BaseConnection, cancelFn, resolvedPath, filePath, requestPath,
  433. common.TransferUpload, minWriteOffset, initialSize, maxWriteSize, truncatedSize, false, fs, transferQuota)
  434. t := newTransfer(baseTransfer, w, nil, errForRead)
  435. return t, nil
  436. }
  437. // Disconnect disconnects the client by closing the channel
  438. func (c *Connection) Disconnect() error {
  439. if c.channel == nil {
  440. c.Log(logger.LevelWarn, "cannot disconnect a nil channel")
  441. return nil
  442. }
  443. return c.channel.Close()
  444. }
  445. func (c *Connection) getStatVFSFromQuotaResult(fs vfs.Fs, name string, quotaResult vfs.QuotaCheckResult) (*sftp.StatVFS, error) {
  446. s, err := fs.GetAvailableDiskSize(name)
  447. if err == nil {
  448. if quotaResult.QuotaSize == 0 || quotaResult.QuotaSize > int64(s.TotalSpace()) {
  449. quotaResult.QuotaSize = int64(s.TotalSpace())
  450. }
  451. if quotaResult.QuotaFiles == 0 || quotaResult.QuotaFiles > int(s.Files) {
  452. quotaResult.QuotaFiles = int(s.Files)
  453. }
  454. } else if err != vfs.ErrStorageSizeUnavailable {
  455. return nil, err
  456. }
  457. // if we are unable to get quota size or quota files we add some arbitrary values
  458. if quotaResult.QuotaSize == 0 {
  459. quotaResult.QuotaSize = quotaResult.UsedSize + 8*1024*1024*1024*1024 // 8TB
  460. }
  461. if quotaResult.QuotaFiles == 0 {
  462. quotaResult.QuotaFiles = quotaResult.UsedFiles + 1000000 // 1 million
  463. }
  464. bsize := uint64(4096)
  465. for bsize > uint64(quotaResult.QuotaSize) {
  466. bsize /= 4
  467. }
  468. blocks := uint64(quotaResult.QuotaSize) / bsize
  469. bfree := uint64(quotaResult.QuotaSize-quotaResult.UsedSize) / bsize
  470. files := uint64(quotaResult.QuotaFiles)
  471. ffree := uint64(quotaResult.QuotaFiles - quotaResult.UsedFiles)
  472. if !quotaResult.HasSpace {
  473. bfree = 0
  474. ffree = 0
  475. }
  476. return &sftp.StatVFS{
  477. Bsize: bsize,
  478. Frsize: bsize,
  479. Blocks: blocks,
  480. Bfree: bfree,
  481. Bavail: bfree,
  482. Files: files,
  483. Ffree: ffree,
  484. Favail: ffree,
  485. Namemax: 255,
  486. }, nil
  487. }
  488. func (c *Connection) updateQuotaAfterTruncate(requestPath string, fileSize int64) {
  489. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  490. if err == nil {
  491. dataprovider.UpdateUserFolderQuota(&vfolder, &c.User, 0, -fileSize, false)
  492. return
  493. }
  494. dataprovider.UpdateUserQuota(&c.User, 0, -fileSize, false) //nolint:errcheck
  495. }
  496. func getOSOpenFlags(requestFlags sftp.FileOpenFlags) (flags int) {
  497. var osFlags int
  498. if requestFlags.Read && requestFlags.Write {
  499. osFlags |= os.O_RDWR
  500. } else if requestFlags.Write {
  501. osFlags |= os.O_WRONLY
  502. }
  503. // we ignore Append flag since pkg/sftp use WriteAt that cannot work with os.O_APPEND
  504. /*if requestFlags.Append {
  505. osFlags |= os.O_APPEND
  506. }*/
  507. if requestFlags.Creat {
  508. osFlags |= os.O_CREATE
  509. }
  510. if requestFlags.Trunc {
  511. osFlags |= os.O_TRUNC
  512. }
  513. if requestFlags.Excl {
  514. osFlags |= os.O_EXCL
  515. }
  516. return osFlags
  517. }