connection.go 43 KB

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