connection.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. package common
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. ftpserver "github.com/fclairamb/ftpserverlib"
  12. "github.com/pkg/sftp"
  13. "github.com/drakkan/sftpgo/v2/dataprovider"
  14. "github.com/drakkan/sftpgo/v2/logger"
  15. "github.com/drakkan/sftpgo/v2/sdk"
  16. "github.com/drakkan/sftpgo/v2/util"
  17. "github.com/drakkan/sftpgo/v2/vfs"
  18. )
  19. // BaseConnection defines common fields for a connection using any supported protocol
  20. type BaseConnection struct {
  21. // last activity for this connection.
  22. // Since this is accessed atomically we put as first element of the struct achieve 64 bit alignment
  23. lastActivity int64
  24. // Unique identifier for the connection
  25. ID string
  26. // user associated with this connection if any
  27. User dataprovider.User
  28. // start time for this connection
  29. startTime time.Time
  30. protocol string
  31. remoteAddr string
  32. localAddr string
  33. sync.RWMutex
  34. transferID uint64
  35. activeTransfers []ActiveTransfer
  36. }
  37. // NewBaseConnection returns a new BaseConnection
  38. func NewBaseConnection(id, protocol, localAddr, remoteAddr string, user dataprovider.User) *BaseConnection {
  39. connID := id
  40. if util.IsStringInSlice(protocol, supportedProtocols) {
  41. connID = fmt.Sprintf("%v_%v", protocol, id)
  42. }
  43. return &BaseConnection{
  44. ID: connID,
  45. User: user,
  46. startTime: time.Now(),
  47. protocol: protocol,
  48. localAddr: localAddr,
  49. remoteAddr: remoteAddr,
  50. lastActivity: time.Now().UnixNano(),
  51. transferID: 0,
  52. }
  53. }
  54. // Log outputs a log entry to the configured logger
  55. func (c *BaseConnection) Log(level logger.LogLevel, format string, v ...interface{}) {
  56. logger.Log(level, c.protocol, c.ID, format, v...)
  57. }
  58. // GetTransferID returns an unique transfer ID for this connection
  59. func (c *BaseConnection) GetTransferID() uint64 {
  60. return atomic.AddUint64(&c.transferID, 1)
  61. }
  62. // GetID returns the connection ID
  63. func (c *BaseConnection) GetID() string {
  64. return c.ID
  65. }
  66. // GetUsername returns the authenticated username associated with this connection if any
  67. func (c *BaseConnection) GetUsername() string {
  68. return c.User.Username
  69. }
  70. // GetProtocol returns the protocol for the connection
  71. func (c *BaseConnection) GetProtocol() string {
  72. return c.protocol
  73. }
  74. // SetProtocol sets the protocol for this connection
  75. func (c *BaseConnection) SetProtocol(protocol string) {
  76. c.protocol = protocol
  77. if util.IsStringInSlice(c.protocol, supportedProtocols) {
  78. c.ID = fmt.Sprintf("%v_%v", c.protocol, c.ID)
  79. }
  80. }
  81. // GetConnectionTime returns the initial connection time
  82. func (c *BaseConnection) GetConnectionTime() time.Time {
  83. return c.startTime
  84. }
  85. // UpdateLastActivity updates last activity for this connection
  86. func (c *BaseConnection) UpdateLastActivity() {
  87. atomic.StoreInt64(&c.lastActivity, time.Now().UnixNano())
  88. }
  89. // GetLastActivity returns the last connection activity
  90. func (c *BaseConnection) GetLastActivity() time.Time {
  91. return time.Unix(0, atomic.LoadInt64(&c.lastActivity))
  92. }
  93. // CloseFS closes the underlying fs
  94. func (c *BaseConnection) CloseFS() error {
  95. return c.User.CloseFs()
  96. }
  97. // AddTransfer associates a new transfer to this connection
  98. func (c *BaseConnection) AddTransfer(t ActiveTransfer) {
  99. c.Lock()
  100. defer c.Unlock()
  101. c.activeTransfers = append(c.activeTransfers, t)
  102. c.Log(logger.LevelDebug, "transfer added, id: %v, active transfers: %v", t.GetID(), len(c.activeTransfers))
  103. }
  104. // RemoveTransfer removes the specified transfer from the active ones
  105. func (c *BaseConnection) RemoveTransfer(t ActiveTransfer) {
  106. c.Lock()
  107. defer c.Unlock()
  108. indexToRemove := -1
  109. for i, v := range c.activeTransfers {
  110. if v.GetID() == t.GetID() {
  111. indexToRemove = i
  112. break
  113. }
  114. }
  115. if indexToRemove >= 0 {
  116. c.activeTransfers[indexToRemove] = c.activeTransfers[len(c.activeTransfers)-1]
  117. c.activeTransfers[len(c.activeTransfers)-1] = nil
  118. c.activeTransfers = c.activeTransfers[:len(c.activeTransfers)-1]
  119. c.Log(logger.LevelDebug, "transfer removed, id: %v active transfers: %v", t.GetID(), len(c.activeTransfers))
  120. } else {
  121. c.Log(logger.LevelWarn, "transfer to remove not found!")
  122. }
  123. }
  124. // GetTransfers returns the active transfers
  125. func (c *BaseConnection) GetTransfers() []ConnectionTransfer {
  126. c.RLock()
  127. defer c.RUnlock()
  128. transfers := make([]ConnectionTransfer, 0, len(c.activeTransfers))
  129. for _, t := range c.activeTransfers {
  130. var operationType string
  131. switch t.GetType() {
  132. case TransferDownload:
  133. operationType = operationDownload
  134. case TransferUpload:
  135. operationType = operationUpload
  136. }
  137. transfers = append(transfers, ConnectionTransfer{
  138. ID: t.GetID(),
  139. OperationType: operationType,
  140. StartTime: util.GetTimeAsMsSinceEpoch(t.GetStartTime()),
  141. Size: t.GetSize(),
  142. VirtualPath: t.GetVirtualPath(),
  143. })
  144. }
  145. return transfers
  146. }
  147. // SignalTransfersAbort signals to the active transfers to exit as soon as possible
  148. func (c *BaseConnection) SignalTransfersAbort() error {
  149. c.RLock()
  150. defer c.RUnlock()
  151. if len(c.activeTransfers) == 0 {
  152. return errors.New("no active transfer found")
  153. }
  154. for _, t := range c.activeTransfers {
  155. t.SignalClose()
  156. }
  157. return nil
  158. }
  159. func (c *BaseConnection) getRealFsPath(fsPath string) string {
  160. c.RLock()
  161. defer c.RUnlock()
  162. for _, t := range c.activeTransfers {
  163. if p := t.GetRealFsPath(fsPath); len(p) > 0 {
  164. return p
  165. }
  166. }
  167. return fsPath
  168. }
  169. func (c *BaseConnection) truncateOpenHandle(fsPath string, size int64) (int64, error) {
  170. c.RLock()
  171. defer c.RUnlock()
  172. for _, t := range c.activeTransfers {
  173. initialSize, err := t.Truncate(fsPath, size)
  174. if err != errTransferMismatch {
  175. return initialSize, err
  176. }
  177. }
  178. return 0, errNoTransfer
  179. }
  180. // ListDir reads the directory matching virtualPath and returns a list of directory entries
  181. func (c *BaseConnection) ListDir(virtualPath string) ([]os.FileInfo, error) {
  182. if !c.User.HasPerm(dataprovider.PermListItems, virtualPath) {
  183. return nil, c.GetPermissionDeniedError()
  184. }
  185. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  186. if err != nil {
  187. return nil, err
  188. }
  189. files, err := fs.ReadDir(fsPath)
  190. if err != nil {
  191. c.Log(logger.LevelWarn, "error listing directory: %+v", err)
  192. return nil, c.GetFsError(fs, err)
  193. }
  194. return c.User.AddVirtualDirs(files, virtualPath), nil
  195. }
  196. // CreateDir creates a new directory at the specified fsPath
  197. func (c *BaseConnection) CreateDir(virtualPath string) error {
  198. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  199. return c.GetPermissionDeniedError()
  200. }
  201. if c.User.IsVirtualFolder(virtualPath) {
  202. c.Log(logger.LevelWarn, "mkdir not allowed %#v is a virtual folder", virtualPath)
  203. return c.GetPermissionDeniedError()
  204. }
  205. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  206. if err != nil {
  207. return err
  208. }
  209. if err := fs.Mkdir(fsPath); err != nil {
  210. c.Log(logger.LevelWarn, "error creating dir: %#v error: %+v", fsPath, err)
  211. return c.GetFsError(fs, err)
  212. }
  213. vfs.SetPathPermissions(fs, fsPath, c.User.GetUID(), c.User.GetGID())
  214. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  215. c.localAddr, c.remoteAddr)
  216. ExecuteActionNotification(&c.User, operationMkdir, fsPath, virtualPath, "", "", c.protocol, 0, nil)
  217. return nil
  218. }
  219. // IsRemoveFileAllowed returns an error if removing this file is not allowed
  220. func (c *BaseConnection) IsRemoveFileAllowed(virtualPath string) error {
  221. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualPath)) {
  222. return c.GetPermissionDeniedError()
  223. }
  224. if !c.User.IsFileAllowed(virtualPath) {
  225. c.Log(logger.LevelDebug, "removing file %#v is not allowed", virtualPath)
  226. return c.GetPermissionDeniedError()
  227. }
  228. return nil
  229. }
  230. // RemoveFile removes a file at the specified fsPath
  231. func (c *BaseConnection) RemoveFile(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  232. if err := c.IsRemoveFileAllowed(virtualPath); err != nil {
  233. return err
  234. }
  235. size := info.Size()
  236. actionErr := ExecutePreAction(&c.User, operationPreDelete, fsPath, virtualPath, c.protocol, size, 0)
  237. if actionErr == nil {
  238. c.Log(logger.LevelDebug, "remove for path %#v handled by pre-delete action", fsPath)
  239. } else {
  240. if err := fs.Remove(fsPath, false); err != nil {
  241. c.Log(logger.LevelWarn, "failed to remove a file/symlink %#v: %+v", fsPath, err)
  242. return c.GetFsError(fs, err)
  243. }
  244. }
  245. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  246. c.localAddr, c.remoteAddr)
  247. if info.Mode()&os.ModeSymlink == 0 {
  248. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  249. if err == nil {
  250. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, -1, -size, false) //nolint:errcheck
  251. if vfolder.IsIncludedInUserQuota() {
  252. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  253. }
  254. } else {
  255. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  256. }
  257. }
  258. if actionErr != nil {
  259. ExecuteActionNotification(&c.User, operationDelete, fsPath, virtualPath, "", "", c.protocol, size, nil)
  260. }
  261. return nil
  262. }
  263. // IsRemoveDirAllowed returns an error if removing this directory is not allowed
  264. func (c *BaseConnection) IsRemoveDirAllowed(fs vfs.Fs, fsPath, virtualPath string) error {
  265. if fs.GetRelativePath(fsPath) == "/" {
  266. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  267. return c.GetPermissionDeniedError()
  268. }
  269. if c.User.IsVirtualFolder(virtualPath) {
  270. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %#v", virtualPath)
  271. return c.GetPermissionDeniedError()
  272. }
  273. if c.User.HasVirtualFoldersInside(virtualPath) {
  274. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %#v", virtualPath)
  275. return c.GetOpUnsupportedError()
  276. }
  277. if c.User.IsMappedPath(fsPath) {
  278. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %#v", fsPath)
  279. return c.GetPermissionDeniedError()
  280. }
  281. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualPath)) {
  282. return c.GetPermissionDeniedError()
  283. }
  284. return nil
  285. }
  286. // RemoveDir removes a directory at the specified fsPath
  287. func (c *BaseConnection) RemoveDir(virtualPath string) error {
  288. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  289. if err != nil {
  290. return err
  291. }
  292. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  293. return err
  294. }
  295. var fi os.FileInfo
  296. if fi, err = fs.Lstat(fsPath); err != nil {
  297. // see #149
  298. if fs.IsNotExist(err) && fs.HasVirtualFolders() {
  299. return nil
  300. }
  301. c.Log(logger.LevelWarn, "failed to remove a dir %#v: stat error: %+v", fsPath, err)
  302. return c.GetFsError(fs, err)
  303. }
  304. if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
  305. c.Log(logger.LevelDebug, "cannot remove %#v is not a directory", fsPath)
  306. return c.GetGenericError(nil)
  307. }
  308. if err := fs.Remove(fsPath, true); err != nil {
  309. c.Log(logger.LevelWarn, "failed to remove directory %#v: %+v", fsPath, err)
  310. return c.GetFsError(fs, err)
  311. }
  312. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  313. c.localAddr, c.remoteAddr)
  314. ExecuteActionNotification(&c.User, operationRmdir, fsPath, virtualPath, "", "", c.protocol, 0, nil)
  315. return nil
  316. }
  317. // Rename renames (moves) virtualSourcePath to virtualTargetPath
  318. func (c *BaseConnection) Rename(virtualSourcePath, virtualTargetPath string) error {
  319. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  320. if err != nil {
  321. return err
  322. }
  323. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  324. if err != nil {
  325. return err
  326. }
  327. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  328. if err != nil {
  329. return c.GetFsError(fsSrc, err)
  330. }
  331. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  332. return c.GetPermissionDeniedError()
  333. }
  334. initialSize := int64(-1)
  335. if dstInfo, err := fsDst.Lstat(fsTargetPath); err == nil {
  336. if dstInfo.IsDir() {
  337. c.Log(logger.LevelWarn, "attempted to rename %#v overwriting an existing directory %#v",
  338. fsSourcePath, fsTargetPath)
  339. return c.GetOpUnsupportedError()
  340. }
  341. // we are overwriting an existing file/symlink
  342. if dstInfo.Mode().IsRegular() {
  343. initialSize = dstInfo.Size()
  344. }
  345. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  346. c.Log(logger.LevelDebug, "renaming %#v -> %#v is not allowed. Target exists but the user %#v"+
  347. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  348. return c.GetPermissionDeniedError()
  349. }
  350. }
  351. if srcInfo.IsDir() {
  352. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  353. c.Log(logger.LevelDebug, "renaming the folder %#v is not supported: it has virtual folders inside it",
  354. virtualSourcePath)
  355. return c.GetOpUnsupportedError()
  356. }
  357. if err = c.checkRecursiveRenameDirPermissions(fsSrc, fsDst, fsSourcePath, fsTargetPath); err != nil {
  358. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %#v: %+v", fsSourcePath, err)
  359. return err
  360. }
  361. }
  362. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  363. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  364. return c.GetGenericError(ErrQuotaExceeded)
  365. }
  366. if err := fsSrc.Rename(fsSourcePath, fsTargetPath); err != nil {
  367. c.Log(logger.LevelWarn, "failed to rename %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  368. return c.GetFsError(fsSrc, err)
  369. }
  370. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  371. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize) //nolint:errcheck
  372. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  373. "", "", "", -1, c.localAddr, c.remoteAddr)
  374. ExecuteActionNotification(&c.User, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, "", c.protocol, 0, nil)
  375. return nil
  376. }
  377. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  378. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  379. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  380. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  381. return c.GetOpUnsupportedError()
  382. }
  383. // we cannot have a cross folder request here so only one fs is enough
  384. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  385. if err != nil {
  386. return err
  387. }
  388. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  389. if err != nil {
  390. return c.GetFsError(fs, err)
  391. }
  392. if fs.GetRelativePath(fsSourcePath) == "/" {
  393. c.Log(logger.LevelWarn, "symlinking root dir is not allowed")
  394. return c.GetPermissionDeniedError()
  395. }
  396. if fs.GetRelativePath(fsTargetPath) == "/" {
  397. c.Log(logger.LevelWarn, "symlinking to root dir is not allowed")
  398. return c.GetPermissionDeniedError()
  399. }
  400. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  401. return c.GetPermissionDeniedError()
  402. }
  403. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  404. c.Log(logger.LevelWarn, "failed to create symlink %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  405. return c.GetFsError(fs, err)
  406. }
  407. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  408. "", "", -1, c.localAddr, c.remoteAddr)
  409. return nil
  410. }
  411. func (c *BaseConnection) getPathForSetStatPerms(fs vfs.Fs, fsPath, virtualPath string) string {
  412. pathForPerms := virtualPath
  413. if fi, err := fs.Lstat(fsPath); err == nil {
  414. if fi.IsDir() {
  415. pathForPerms = path.Dir(virtualPath)
  416. }
  417. }
  418. return pathForPerms
  419. }
  420. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  421. func (c *BaseConnection) DoStat(virtualPath string, mode int) (os.FileInfo, error) {
  422. // for some vfs we don't create intermediary folders so we cannot simply check
  423. // if virtualPath is a virtual folder
  424. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  425. if _, ok := vfolders[virtualPath]; ok {
  426. return vfs.NewFileInfo(virtualPath, true, 0, time.Now(), false), nil
  427. }
  428. var info os.FileInfo
  429. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  430. if err != nil {
  431. return info, err
  432. }
  433. if mode == 1 {
  434. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  435. } else {
  436. info, err = fs.Stat(c.getRealFsPath(fsPath))
  437. }
  438. if err != nil {
  439. return info, c.GetFsError(fs, err)
  440. }
  441. if vfs.IsCryptOsFs(fs) {
  442. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  443. }
  444. return info, nil
  445. }
  446. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  447. if Config.SetstatMode == 1 {
  448. return true
  449. }
  450. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  451. return true
  452. }
  453. return false
  454. }
  455. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  456. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  457. return c.GetPermissionDeniedError()
  458. }
  459. if c.ignoreSetStat(fs) {
  460. return nil
  461. }
  462. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  463. c.Log(logger.LevelWarn, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  464. return c.GetFsError(fs, err)
  465. }
  466. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  467. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr)
  468. return nil
  469. }
  470. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  471. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  472. return c.GetPermissionDeniedError()
  473. }
  474. if c.ignoreSetStat(fs) {
  475. return nil
  476. }
  477. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  478. c.Log(logger.LevelWarn, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  479. attributes.GID, err)
  480. return c.GetFsError(fs, err)
  481. }
  482. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  483. "", "", "", -1, c.localAddr, c.remoteAddr)
  484. return nil
  485. }
  486. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  487. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  488. return c.GetPermissionDeniedError()
  489. }
  490. if c.ignoreSetStat(fs) {
  491. return nil
  492. }
  493. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime); err != nil {
  494. c.Log(logger.LevelWarn, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  495. fsPath, attributes.Atime, attributes.Mtime, err)
  496. return c.GetFsError(fs, err)
  497. }
  498. accessTimeString := attributes.Atime.Format(chtimesFormat)
  499. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  500. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  501. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr)
  502. return nil
  503. }
  504. // SetStat set StatAttributes for the specified fsPath
  505. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  506. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  507. if err != nil {
  508. return err
  509. }
  510. pathForPerms := c.getPathForSetStatPerms(fs, fsPath, virtualPath)
  511. if attributes.Flags&StatAttrPerms != 0 {
  512. return c.handleChmod(fs, fsPath, pathForPerms, attributes)
  513. }
  514. if attributes.Flags&StatAttrUIDGID != 0 {
  515. return c.handleChown(fs, fsPath, pathForPerms, attributes)
  516. }
  517. if attributes.Flags&StatAttrTimes != 0 {
  518. return c.handleChtimes(fs, fsPath, pathForPerms, attributes)
  519. }
  520. if attributes.Flags&StatAttrSize != 0 {
  521. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  522. return c.GetPermissionDeniedError()
  523. }
  524. if err := c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  525. c.Log(logger.LevelWarn, "failed to truncate path %#v, size: %v, err: %+v", fsPath, attributes.Size, err)
  526. return c.GetFsError(fs, err)
  527. }
  528. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  529. "", attributes.Size, c.localAddr, c.remoteAddr)
  530. }
  531. return nil
  532. }
  533. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  534. // check first if we have an open transfer for the given path and try to truncate the file already opened
  535. // if we found no transfer we truncate by path.
  536. var initialSize int64
  537. var err error
  538. initialSize, err = c.truncateOpenHandle(fsPath, size)
  539. if err == errNoTransfer {
  540. c.Log(logger.LevelDebug, "file path %#v not found in active transfers, execute trucate by path", fsPath)
  541. var info os.FileInfo
  542. info, err = fs.Stat(fsPath)
  543. if err != nil {
  544. return err
  545. }
  546. initialSize = info.Size()
  547. err = fs.Truncate(fsPath, size)
  548. }
  549. if err == nil && vfs.IsLocalOrSFTPFs(fs) {
  550. sizeDiff := initialSize - size
  551. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  552. if err == nil {
  553. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  554. if vfolder.IsIncludedInUserQuota() {
  555. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  556. }
  557. } else {
  558. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  559. }
  560. }
  561. return err
  562. }
  563. func (c *BaseConnection) checkRecursiveRenameDirPermissions(fsSrc, fsDst vfs.Fs, sourcePath, targetPath string) error {
  564. dstPerms := []string{
  565. dataprovider.PermCreateDirs,
  566. dataprovider.PermUpload,
  567. dataprovider.PermCreateSymlinks,
  568. }
  569. err := fsSrc.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  570. if err != nil {
  571. return c.GetFsError(fsSrc, err)
  572. }
  573. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  574. virtualSrcPath := fsSrc.GetRelativePath(walkedPath)
  575. virtualDstPath := fsDst.GetRelativePath(dstPath)
  576. // walk scans the directory tree in order, checking the parent directory permissions we are sure that all contents
  577. // inside the parent path was checked. If the current dir has no subdirs with defined permissions inside it
  578. // and it has all the possible permissions we can stop scanning
  579. if !c.User.HasPermissionsInside(path.Dir(virtualSrcPath)) && !c.User.HasPermissionsInside(path.Dir(virtualDstPath)) {
  580. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSrcPath)) &&
  581. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualDstPath)) {
  582. return ErrSkipPermissionsCheck
  583. }
  584. if c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSrcPath)) &&
  585. c.User.HasPerms(dstPerms, path.Dir(virtualDstPath)) {
  586. return ErrSkipPermissionsCheck
  587. }
  588. }
  589. if !c.isRenamePermitted(fsSrc, fsDst, walkedPath, dstPath, virtualSrcPath, virtualDstPath, info) {
  590. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  591. walkedPath, dstPath, virtualDstPath)
  592. return c.GetPermissionDeniedError()
  593. }
  594. return nil
  595. })
  596. if err == ErrSkipPermissionsCheck {
  597. err = nil
  598. }
  599. return err
  600. }
  601. func (c *BaseConnection) hasRenamePerms(virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  602. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSourcePath)) &&
  603. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualTargetPath)) {
  604. return true
  605. }
  606. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSourcePath)) {
  607. return false
  608. }
  609. if fi != nil {
  610. if fi.IsDir() {
  611. return c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualTargetPath))
  612. } else if fi.Mode()&os.ModeSymlink != 0 {
  613. return c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath))
  614. }
  615. }
  616. return c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualTargetPath))
  617. }
  618. func (c *BaseConnection) isRenamePermitted(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  619. if !c.isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath) {
  620. c.Log(logger.LevelInfo, "rename %#v->%#v is not allowed: the paths must be local or on the same virtual folder",
  621. virtualSourcePath, virtualTargetPath)
  622. return false
  623. }
  624. if c.User.IsMappedPath(fsSourcePath) && vfs.IsLocalOrCryptoFs(fsSrc) {
  625. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  626. return false
  627. }
  628. if c.User.IsMappedPath(fsTargetPath) && vfs.IsLocalOrCryptoFs(fsDst) {
  629. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  630. return false
  631. }
  632. if fsSrc.GetRelativePath(fsSourcePath) == "/" {
  633. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  634. return false
  635. }
  636. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  637. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  638. return false
  639. }
  640. if !c.User.IsFileAllowed(virtualSourcePath) || !c.User.IsFileAllowed(virtualTargetPath) {
  641. if fi != nil && fi.Mode().IsRegular() {
  642. c.Log(logger.LevelDebug, "renaming file is not allowed, source: %#v target: %#v",
  643. virtualSourcePath, virtualTargetPath)
  644. return false
  645. }
  646. }
  647. return c.hasRenamePerms(virtualSourcePath, virtualTargetPath, fi)
  648. }
  649. func (c *BaseConnection) hasSpaceForRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath string, initialSize int64,
  650. fsSourcePath string) bool {
  651. if dataprovider.GetQuotaTracking() == 0 {
  652. return true
  653. }
  654. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  655. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  656. if errSrc != nil && errDst != nil {
  657. // rename inside the user home dir
  658. return true
  659. }
  660. if errSrc == nil && errDst == nil {
  661. // rename between virtual folders
  662. if sourceFolder.Name == dstFolder.Name {
  663. // rename inside the same virtual folder
  664. return true
  665. }
  666. }
  667. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  668. // rename between user root dir and a virtual folder included in user quota
  669. return true
  670. }
  671. quotaResult := c.HasSpace(true, false, virtualTargetPath)
  672. return c.hasSpaceForCrossRename(fs, quotaResult, initialSize, fsSourcePath)
  673. }
  674. // hasSpaceForCrossRename checks the quota after a rename between different folders
  675. func (c *BaseConnection) hasSpaceForCrossRename(fs vfs.Fs, quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  676. if !quotaResult.HasSpace && initialSize == -1 {
  677. // we are over quota and this is not a file replace
  678. return false
  679. }
  680. fi, err := fs.Lstat(sourcePath)
  681. if err != nil {
  682. c.Log(logger.LevelWarn, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  683. return false
  684. }
  685. var sizeDiff int64
  686. var filesDiff int
  687. if fi.Mode().IsRegular() {
  688. sizeDiff = fi.Size()
  689. filesDiff = 1
  690. if initialSize != -1 {
  691. sizeDiff -= initialSize
  692. filesDiff = 0
  693. }
  694. } else if fi.IsDir() {
  695. filesDiff, sizeDiff, err = fs.GetDirSize(sourcePath)
  696. if err != nil {
  697. c.Log(logger.LevelWarn, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  698. return false
  699. }
  700. }
  701. if !quotaResult.HasSpace && initialSize != -1 {
  702. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  703. if quotaResult.QuotaSize == 0 {
  704. return true
  705. }
  706. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  707. sourcePath, quotaResult.UsedSize, sizeDiff)
  708. quotaResult.UsedSize += sizeDiff
  709. return quotaResult.GetRemainingSize() >= 0
  710. }
  711. if quotaResult.QuotaFiles > 0 {
  712. remainingFiles := quotaResult.GetRemainingFiles()
  713. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  714. remainingFiles, filesDiff)
  715. if remainingFiles < filesDiff {
  716. return false
  717. }
  718. }
  719. if quotaResult.QuotaSize > 0 {
  720. remainingSize := quotaResult.GetRemainingSize()
  721. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  722. remainingSize, sizeDiff)
  723. if remainingSize < sizeDiff {
  724. return false
  725. }
  726. }
  727. return true
  728. }
  729. // GetMaxWriteSize returns the allowed size for an upload or an error
  730. // if no enough size is available for a resume/append
  731. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64, isUploadResumeSupported bool) (int64, error) {
  732. maxWriteSize := quotaResult.GetRemainingSize()
  733. if isResume {
  734. if !isUploadResumeSupported {
  735. return 0, c.GetOpUnsupportedError()
  736. }
  737. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  738. return 0, c.GetQuotaExceededError()
  739. }
  740. if c.User.Filters.MaxUploadFileSize > 0 {
  741. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  742. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  743. maxWriteSize = maxUploadSize
  744. }
  745. }
  746. } else {
  747. if maxWriteSize > 0 {
  748. maxWriteSize += fileSize
  749. }
  750. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  751. maxWriteSize = c.User.Filters.MaxUploadFileSize
  752. }
  753. }
  754. return maxWriteSize, nil
  755. }
  756. // HasSpace checks user's quota usage
  757. func (c *BaseConnection) HasSpace(checkFiles, getUsage bool, requestPath string) vfs.QuotaCheckResult {
  758. result := vfs.QuotaCheckResult{
  759. HasSpace: true,
  760. AllowedSize: 0,
  761. AllowedFiles: 0,
  762. UsedSize: 0,
  763. UsedFiles: 0,
  764. QuotaSize: 0,
  765. QuotaFiles: 0,
  766. }
  767. if dataprovider.GetQuotaTracking() == 0 {
  768. return result
  769. }
  770. var err error
  771. var vfolder vfs.VirtualFolder
  772. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  773. if err == nil && !vfolder.IsIncludedInUserQuota() {
  774. if vfolder.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  775. return result
  776. }
  777. result.QuotaSize = vfolder.QuotaSize
  778. result.QuotaFiles = vfolder.QuotaFiles
  779. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.Name)
  780. } else {
  781. if c.User.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  782. return result
  783. }
  784. result.QuotaSize = c.User.QuotaSize
  785. result.QuotaFiles = c.User.QuotaFiles
  786. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedQuota(c.User.Username)
  787. }
  788. if err != nil {
  789. c.Log(logger.LevelWarn, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  790. result.HasSpace = false
  791. return result
  792. }
  793. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  794. result.AllowedSize = result.QuotaSize - result.UsedSize
  795. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  796. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  797. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  798. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  799. result.HasSpace = false
  800. return result
  801. }
  802. return result
  803. }
  804. // returns true if this is a rename on the same fs or local virtual folders
  805. func (c *BaseConnection) isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath string) bool {
  806. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  807. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  808. if errSrc != nil && errDst != nil {
  809. return true
  810. }
  811. if errSrc == nil && errDst == nil {
  812. if sourceFolder.Name == dstFolder.Name {
  813. return true
  814. }
  815. // we have different folders, only local fs is supported
  816. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider &&
  817. dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  818. return true
  819. }
  820. return false
  821. }
  822. if c.User.FsConfig.Provider != sdk.LocalFilesystemProvider {
  823. return false
  824. }
  825. if errSrc == nil {
  826. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  827. return true
  828. }
  829. }
  830. if errDst == nil {
  831. if dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  832. return true
  833. }
  834. }
  835. return false
  836. }
  837. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  838. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  839. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  840. if errSrc != nil && errDst != nil {
  841. return false
  842. }
  843. if errSrc == nil && errDst == nil {
  844. return sourceFolder.Name != dstFolder.Name
  845. }
  846. return true
  847. }
  848. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder *vfs.VirtualFolder, initialSize,
  849. filesSize int64, numFiles int) {
  850. if sourceFolder.Name == dstFolder.Name {
  851. // both files are inside the same virtual folder
  852. if initialSize != -1 {
  853. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  854. if dstFolder.IsIncludedInUserQuota() {
  855. dataprovider.UpdateUserQuota(&c.User, -numFiles, -initialSize, false) //nolint:errcheck
  856. }
  857. }
  858. return
  859. }
  860. // files are inside different virtual folders
  861. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  862. if sourceFolder.IsIncludedInUserQuota() {
  863. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  864. }
  865. if initialSize == -1 {
  866. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  867. if dstFolder.IsIncludedInUserQuota() {
  868. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  869. }
  870. } else {
  871. // we cannot have a directory here, initialSize != -1 only for files
  872. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  873. if dstFolder.IsIncludedInUserQuota() {
  874. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  875. }
  876. }
  877. }
  878. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  879. // move between a virtual folder and the user home dir
  880. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  881. if sourceFolder.IsIncludedInUserQuota() {
  882. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  883. }
  884. if initialSize == -1 {
  885. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  886. } else {
  887. // we cannot have a directory here, initialSize != -1 only for files
  888. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  889. }
  890. }
  891. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  892. // move between the user home dir and a virtual folder
  893. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  894. if initialSize == -1 {
  895. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  896. if dstFolder.IsIncludedInUserQuota() {
  897. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  898. }
  899. } else {
  900. // we cannot have a directory here, initialSize != -1 only for files
  901. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  902. if dstFolder.IsIncludedInUserQuota() {
  903. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  904. }
  905. }
  906. }
  907. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  908. if dataprovider.GetQuotaTracking() == 0 {
  909. return nil
  910. }
  911. // we don't allow to overwrite an existing directory so targetPath can be:
  912. // - a new file, a symlink is as a new file here
  913. // - a file overwriting an existing one
  914. // - a new directory
  915. // initialSize != -1 only when overwriting files
  916. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  917. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  918. if errSrc != nil && errDst != nil {
  919. // both files are contained inside the user home dir
  920. if initialSize != -1 {
  921. // we cannot have a directory here, we are overwriting an existing file
  922. // we need to subtract the size of the overwritten file from the user quota
  923. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  924. }
  925. return nil
  926. }
  927. filesSize := int64(0)
  928. numFiles := 1
  929. if fi, err := fs.Stat(targetPath); err == nil {
  930. if fi.Mode().IsDir() {
  931. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  932. if err != nil {
  933. c.Log(logger.LevelWarn, "failed to update quota after rename, error scanning moved folder %#v: %v",
  934. targetPath, err)
  935. return err
  936. }
  937. } else {
  938. filesSize = fi.Size()
  939. }
  940. } else {
  941. c.Log(logger.LevelWarn, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  942. return err
  943. }
  944. if errSrc == nil && errDst == nil {
  945. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  946. }
  947. if errSrc == nil && errDst != nil {
  948. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  949. }
  950. if errSrc != nil && errDst == nil {
  951. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  952. }
  953. return nil
  954. }
  955. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  956. func (c *BaseConnection) GetPermissionDeniedError() error {
  957. switch c.protocol {
  958. case ProtocolSFTP:
  959. return sftp.ErrSSHFxPermissionDenied
  960. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP:
  961. return os.ErrPermission
  962. default:
  963. return ErrPermissionDenied
  964. }
  965. }
  966. // GetNotExistError returns an appropriate not exist error for the connection protocol
  967. func (c *BaseConnection) GetNotExistError() error {
  968. switch c.protocol {
  969. case ProtocolSFTP:
  970. return sftp.ErrSSHFxNoSuchFile
  971. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP:
  972. return os.ErrNotExist
  973. default:
  974. return ErrNotExist
  975. }
  976. }
  977. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  978. func (c *BaseConnection) GetOpUnsupportedError() error {
  979. switch c.protocol {
  980. case ProtocolSFTP:
  981. return sftp.ErrSSHFxOpUnsupported
  982. default:
  983. return ErrOpUnsupported
  984. }
  985. }
  986. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  987. func (c *BaseConnection) GetQuotaExceededError() error {
  988. switch c.protocol {
  989. case ProtocolSFTP:
  990. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrQuotaExceeded.Error())
  991. case ProtocolFTP:
  992. return ftpserver.ErrStorageExceeded
  993. default:
  994. return ErrQuotaExceeded
  995. }
  996. }
  997. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  998. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  999. switch c.protocol {
  1000. case ProtocolSFTP:
  1001. if err == nil {
  1002. return false
  1003. }
  1004. if errors.Is(err, ErrQuotaExceeded) {
  1005. return true
  1006. }
  1007. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1008. case ProtocolFTP:
  1009. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1010. default:
  1011. return errors.Is(err, ErrQuotaExceeded)
  1012. }
  1013. }
  1014. // GetGenericError returns an appropriate generic error for the connection protocol
  1015. func (c *BaseConnection) GetGenericError(err error) error {
  1016. switch c.protocol {
  1017. case ProtocolSFTP:
  1018. if err == vfs.ErrStorageSizeUnavailable {
  1019. return fmt.Errorf("%w: %v", sftp.ErrSSHFxOpUnsupported, err.Error())
  1020. }
  1021. if err != nil {
  1022. if e, ok := err.(*os.PathError); ok {
  1023. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, e.Op, e.Err.Error())
  1024. }
  1025. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, err.Error())
  1026. }
  1027. return sftp.ErrSSHFxFailure
  1028. default:
  1029. if err == ErrPermissionDenied || err == ErrNotExist || err == ErrOpUnsupported ||
  1030. err == ErrQuotaExceeded || err == vfs.ErrStorageSizeUnavailable {
  1031. return err
  1032. }
  1033. return ErrGenericFailure
  1034. }
  1035. }
  1036. // GetFsError converts a filesystem error to a protocol error
  1037. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1038. if fs.IsNotExist(err) {
  1039. return c.GetNotExistError()
  1040. } else if fs.IsPermission(err) {
  1041. return c.GetPermissionDeniedError()
  1042. } else if fs.IsNotSupported(err) {
  1043. return c.GetOpUnsupportedError()
  1044. } else if err != nil {
  1045. return c.GetGenericError(err)
  1046. }
  1047. return nil
  1048. }
  1049. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1050. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1051. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1052. if err != nil {
  1053. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1054. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1055. // will not be listed
  1056. return nil, "", c.GetPermissionDeniedError()
  1057. }
  1058. return nil, "", err
  1059. }
  1060. fsPath, err := fs.ResolvePath(virtualPath)
  1061. if err != nil {
  1062. return nil, "", c.GetFsError(fs, err)
  1063. }
  1064. return fs, fsPath, nil
  1065. }