connection.go 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  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/sftpgo/sdk"
  14. "github.com/drakkan/sftpgo/v2/dataprovider"
  15. "github.com/drakkan/sftpgo/v2/logger"
  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. if virtualSourcePath == virtualTargetPath {
  365. return fmt.Errorf("the rename source and target cannot be the same: %w", c.GetOpUnsupportedError())
  366. }
  367. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  368. if err != nil {
  369. return err
  370. }
  371. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  372. if err != nil {
  373. return err
  374. }
  375. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  376. if err != nil {
  377. return c.GetFsError(fsSrc, err)
  378. }
  379. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  380. return c.GetPermissionDeniedError()
  381. }
  382. initialSize := int64(-1)
  383. if dstInfo, err := fsDst.Lstat(fsTargetPath); err == nil {
  384. if dstInfo.IsDir() {
  385. c.Log(logger.LevelWarn, "attempted to rename %#v overwriting an existing directory %#v",
  386. fsSourcePath, fsTargetPath)
  387. return c.GetOpUnsupportedError()
  388. }
  389. // we are overwriting an existing file/symlink
  390. if dstInfo.Mode().IsRegular() {
  391. initialSize = dstInfo.Size()
  392. }
  393. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  394. c.Log(logger.LevelDebug, "renaming %#v -> %#v is not allowed. Target exists but the user %#v"+
  395. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  396. return c.GetPermissionDeniedError()
  397. }
  398. }
  399. if srcInfo.IsDir() {
  400. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  401. c.Log(logger.LevelDebug, "renaming the folder %#v is not supported: it has virtual folders inside it",
  402. virtualSourcePath)
  403. return c.GetOpUnsupportedError()
  404. }
  405. if err = c.checkRecursiveRenameDirPermissions(fsSrc, fsDst, fsSourcePath, fsTargetPath); err != nil {
  406. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %#v: %+v", fsSourcePath, err)
  407. return err
  408. }
  409. }
  410. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  411. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  412. return c.GetGenericError(ErrQuotaExceeded)
  413. }
  414. if err := fsSrc.Rename(fsSourcePath, fsTargetPath); err != nil {
  415. c.Log(logger.LevelError, "failed to rename %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  416. return c.GetFsError(fsSrc, err)
  417. }
  418. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  419. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize) //nolint:errcheck
  420. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  421. "", "", "", -1, c.localAddr, c.remoteAddr)
  422. ExecuteActionNotification(c, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, virtualTargetPath,
  423. "", 0, nil)
  424. return nil
  425. }
  426. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  427. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  428. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  429. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  430. return c.GetOpUnsupportedError()
  431. }
  432. // we cannot have a cross folder request here so only one fs is enough
  433. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  434. if err != nil {
  435. return err
  436. }
  437. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  438. if err != nil {
  439. return c.GetFsError(fs, err)
  440. }
  441. if fs.GetRelativePath(fsSourcePath) == "/" {
  442. c.Log(logger.LevelWarn, "symlinking root dir is not allowed")
  443. return c.GetPermissionDeniedError()
  444. }
  445. if fs.GetRelativePath(fsTargetPath) == "/" {
  446. c.Log(logger.LevelWarn, "symlinking to root dir is not allowed")
  447. return c.GetPermissionDeniedError()
  448. }
  449. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  450. return c.GetPermissionDeniedError()
  451. }
  452. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  453. c.Log(logger.LevelError, "failed to create symlink %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  454. return c.GetFsError(fs, err)
  455. }
  456. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  457. "", "", -1, c.localAddr, c.remoteAddr)
  458. return nil
  459. }
  460. func (c *BaseConnection) getPathForSetStatPerms(fs vfs.Fs, fsPath, virtualPath string) string {
  461. pathForPerms := virtualPath
  462. if fi, err := fs.Lstat(fsPath); err == nil {
  463. if fi.IsDir() {
  464. pathForPerms = path.Dir(virtualPath)
  465. }
  466. }
  467. return pathForPerms
  468. }
  469. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  470. func (c *BaseConnection) DoStat(virtualPath string, mode int) (os.FileInfo, error) {
  471. // for some vfs we don't create intermediary folders so we cannot simply check
  472. // if virtualPath is a virtual folder
  473. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  474. if _, ok := vfolders[virtualPath]; ok {
  475. return vfs.NewFileInfo(virtualPath, true, 0, time.Now(), false), nil
  476. }
  477. var info os.FileInfo
  478. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  479. if err != nil {
  480. return info, err
  481. }
  482. if mode == 1 {
  483. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  484. } else {
  485. info, err = fs.Stat(c.getRealFsPath(fsPath))
  486. }
  487. if err != nil {
  488. c.Log(logger.LevelError, "stat error for path %#v: %+v", virtualPath, err)
  489. return info, c.GetFsError(fs, err)
  490. }
  491. if vfs.IsCryptOsFs(fs) {
  492. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  493. }
  494. return info, nil
  495. }
  496. func (c *BaseConnection) createDirIfMissing(name string) error {
  497. _, err := c.DoStat(name, 0)
  498. if c.IsNotExistError(err) {
  499. return c.CreateDir(name)
  500. }
  501. return err
  502. }
  503. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  504. if Config.SetstatMode == 1 {
  505. return true
  506. }
  507. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  508. return true
  509. }
  510. return false
  511. }
  512. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  513. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  514. return c.GetPermissionDeniedError()
  515. }
  516. if c.ignoreSetStat(fs) {
  517. return nil
  518. }
  519. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  520. c.Log(logger.LevelError, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  521. return c.GetFsError(fs, err)
  522. }
  523. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  524. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr)
  525. return nil
  526. }
  527. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  528. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  529. return c.GetPermissionDeniedError()
  530. }
  531. if c.ignoreSetStat(fs) {
  532. return nil
  533. }
  534. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  535. c.Log(logger.LevelError, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  536. attributes.GID, err)
  537. return c.GetFsError(fs, err)
  538. }
  539. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  540. "", "", "", -1, c.localAddr, c.remoteAddr)
  541. return nil
  542. }
  543. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  544. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  545. return c.GetPermissionDeniedError()
  546. }
  547. if Config.SetstatMode == 1 {
  548. return nil
  549. }
  550. isUploading := c.setTimes(fsPath, attributes.Atime, attributes.Mtime)
  551. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime, isUploading); err != nil {
  552. c.setTimes(fsPath, time.Time{}, time.Time{})
  553. if errors.Is(err, vfs.ErrVfsUnsupported) && Config.SetstatMode == 2 {
  554. return nil
  555. }
  556. c.Log(logger.LevelError, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  557. fsPath, attributes.Atime, attributes.Mtime, err)
  558. return c.GetFsError(fs, err)
  559. }
  560. accessTimeString := attributes.Atime.Format(chtimesFormat)
  561. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  562. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  563. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr)
  564. return nil
  565. }
  566. // SetStat set StatAttributes for the specified fsPath
  567. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  568. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  569. if err != nil {
  570. return err
  571. }
  572. pathForPerms := c.getPathForSetStatPerms(fs, fsPath, virtualPath)
  573. if attributes.Flags&StatAttrTimes != 0 {
  574. if err = c.handleChtimes(fs, fsPath, pathForPerms, attributes); err != nil {
  575. return err
  576. }
  577. }
  578. if attributes.Flags&StatAttrPerms != 0 {
  579. if err = c.handleChmod(fs, fsPath, pathForPerms, attributes); err != nil {
  580. return err
  581. }
  582. }
  583. if attributes.Flags&StatAttrUIDGID != 0 {
  584. if err = c.handleChown(fs, fsPath, pathForPerms, attributes); err != nil {
  585. return err
  586. }
  587. }
  588. if attributes.Flags&StatAttrSize != 0 {
  589. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  590. return c.GetPermissionDeniedError()
  591. }
  592. if err = c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  593. c.Log(logger.LevelError, "failed to truncate path %#v, size: %v, err: %+v", fsPath, attributes.Size, err)
  594. return c.GetFsError(fs, err)
  595. }
  596. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  597. "", attributes.Size, c.localAddr, c.remoteAddr)
  598. }
  599. return nil
  600. }
  601. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  602. // check first if we have an open transfer for the given path and try to truncate the file already opened
  603. // if we found no transfer we truncate by path.
  604. var initialSize int64
  605. var err error
  606. initialSize, err = c.truncateOpenHandle(fsPath, size)
  607. if err == errNoTransfer {
  608. c.Log(logger.LevelDebug, "file path %#v not found in active transfers, execute trucate by path", fsPath)
  609. var info os.FileInfo
  610. info, err = fs.Stat(fsPath)
  611. if err != nil {
  612. return err
  613. }
  614. initialSize = info.Size()
  615. err = fs.Truncate(fsPath, size)
  616. }
  617. if err == nil && vfs.IsLocalOrSFTPFs(fs) {
  618. sizeDiff := initialSize - size
  619. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  620. if err == nil {
  621. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  622. if vfolder.IsIncludedInUserQuota() {
  623. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  624. }
  625. } else {
  626. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  627. }
  628. }
  629. return err
  630. }
  631. func (c *BaseConnection) checkRecursiveRenameDirPermissions(fsSrc, fsDst vfs.Fs, sourcePath, targetPath string) error {
  632. dstPerms := []string{
  633. dataprovider.PermCreateDirs,
  634. dataprovider.PermUpload,
  635. dataprovider.PermCreateSymlinks,
  636. }
  637. err := fsSrc.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  638. if err != nil {
  639. return c.GetFsError(fsSrc, err)
  640. }
  641. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  642. virtualSrcPath := fsSrc.GetRelativePath(walkedPath)
  643. virtualDstPath := fsDst.GetRelativePath(dstPath)
  644. // walk scans the directory tree in order, checking the parent directory permissions we are sure that all contents
  645. // inside the parent path was checked. If the current dir has no subdirs with defined permissions inside it
  646. // and it has all the possible permissions we can stop scanning
  647. if !c.User.HasPermissionsInside(path.Dir(virtualSrcPath)) && !c.User.HasPermissionsInside(path.Dir(virtualDstPath)) {
  648. if c.User.HasPermsRenameAll(path.Dir(virtualSrcPath)) &&
  649. c.User.HasPermsRenameAll(path.Dir(virtualDstPath)) {
  650. return ErrSkipPermissionsCheck
  651. }
  652. if c.User.HasPermsDeleteAll(path.Dir(virtualSrcPath)) &&
  653. c.User.HasPerms(dstPerms, path.Dir(virtualDstPath)) {
  654. return ErrSkipPermissionsCheck
  655. }
  656. }
  657. if !c.isRenamePermitted(fsSrc, fsDst, walkedPath, dstPath, virtualSrcPath, virtualDstPath, info) {
  658. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  659. walkedPath, dstPath, virtualDstPath)
  660. return c.GetPermissionDeniedError()
  661. }
  662. return nil
  663. })
  664. if err == ErrSkipPermissionsCheck {
  665. err = nil
  666. }
  667. return err
  668. }
  669. func (c *BaseConnection) hasRenamePerms(virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  670. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) &&
  671. c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  672. return true
  673. }
  674. if fi == nil {
  675. // we don't know if this is a file or a directory we have to check all the required permissions
  676. if !c.User.HasPermsDeleteAll(path.Dir(virtualSourcePath)) {
  677. return false
  678. }
  679. dstPerms := []string{
  680. dataprovider.PermCreateDirs,
  681. dataprovider.PermUpload,
  682. dataprovider.PermCreateSymlinks,
  683. }
  684. return c.User.HasPerms(dstPerms, path.Dir(virtualTargetPath))
  685. }
  686. if fi.IsDir() {
  687. if c.User.HasPerm(dataprovider.PermRenameDirs, path.Dir(virtualSourcePath)) &&
  688. c.User.HasPerm(dataprovider.PermRenameDirs, path.Dir(virtualTargetPath)) {
  689. return true
  690. }
  691. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualSourcePath)) {
  692. return false
  693. }
  694. return c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualTargetPath))
  695. }
  696. // file or symlink
  697. if c.User.HasPerm(dataprovider.PermRenameFiles, path.Dir(virtualSourcePath)) &&
  698. c.User.HasPerm(dataprovider.PermRenameFiles, path.Dir(virtualTargetPath)) {
  699. return true
  700. }
  701. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualSourcePath)) {
  702. return false
  703. }
  704. if fi.Mode()&os.ModeSymlink != 0 {
  705. return c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath))
  706. }
  707. return c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualTargetPath))
  708. }
  709. func (c *BaseConnection) isRenamePermitted(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  710. if !c.isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath) {
  711. c.Log(logger.LevelInfo, "rename %#v->%#v is not allowed: the paths must be local or on the same virtual folder",
  712. virtualSourcePath, virtualTargetPath)
  713. return false
  714. }
  715. if c.User.IsMappedPath(fsSourcePath) && vfs.IsLocalOrCryptoFs(fsSrc) {
  716. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  717. return false
  718. }
  719. if c.User.IsMappedPath(fsTargetPath) && vfs.IsLocalOrCryptoFs(fsDst) {
  720. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  721. return false
  722. }
  723. if fsSrc.GetRelativePath(fsSourcePath) == "/" {
  724. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  725. return false
  726. }
  727. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  728. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  729. return false
  730. }
  731. if !c.User.IsFileAllowed(virtualSourcePath) || !c.User.IsFileAllowed(virtualTargetPath) {
  732. if fi != nil && fi.Mode().IsRegular() {
  733. c.Log(logger.LevelDebug, "renaming file is not allowed, source: %#v target: %#v",
  734. virtualSourcePath, virtualTargetPath)
  735. return false
  736. }
  737. }
  738. return c.hasRenamePerms(virtualSourcePath, virtualTargetPath, fi)
  739. }
  740. func (c *BaseConnection) hasSpaceForRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath string, initialSize int64,
  741. fsSourcePath string) bool {
  742. if dataprovider.GetQuotaTracking() == 0 {
  743. return true
  744. }
  745. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  746. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  747. if errSrc != nil && errDst != nil {
  748. // rename inside the user home dir
  749. return true
  750. }
  751. if errSrc == nil && errDst == nil {
  752. // rename between virtual folders
  753. if sourceFolder.Name == dstFolder.Name {
  754. // rename inside the same virtual folder
  755. return true
  756. }
  757. }
  758. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  759. // rename between user root dir and a virtual folder included in user quota
  760. return true
  761. }
  762. quotaResult := c.HasSpace(true, false, virtualTargetPath)
  763. return c.hasSpaceForCrossRename(fs, quotaResult, initialSize, fsSourcePath)
  764. }
  765. // hasSpaceForCrossRename checks the quota after a rename between different folders
  766. func (c *BaseConnection) hasSpaceForCrossRename(fs vfs.Fs, quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  767. if !quotaResult.HasSpace && initialSize == -1 {
  768. // we are over quota and this is not a file replace
  769. return false
  770. }
  771. fi, err := fs.Lstat(sourcePath)
  772. if err != nil {
  773. c.Log(logger.LevelError, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  774. return false
  775. }
  776. var sizeDiff int64
  777. var filesDiff int
  778. if fi.Mode().IsRegular() {
  779. sizeDiff = fi.Size()
  780. filesDiff = 1
  781. if initialSize != -1 {
  782. sizeDiff -= initialSize
  783. filesDiff = 0
  784. }
  785. } else if fi.IsDir() {
  786. filesDiff, sizeDiff, err = fs.GetDirSize(sourcePath)
  787. if err != nil {
  788. c.Log(logger.LevelError, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  789. return false
  790. }
  791. }
  792. if !quotaResult.HasSpace && initialSize != -1 {
  793. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  794. if quotaResult.QuotaSize == 0 {
  795. return true
  796. }
  797. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  798. sourcePath, quotaResult.UsedSize, sizeDiff)
  799. quotaResult.UsedSize += sizeDiff
  800. return quotaResult.GetRemainingSize() >= 0
  801. }
  802. if quotaResult.QuotaFiles > 0 {
  803. remainingFiles := quotaResult.GetRemainingFiles()
  804. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  805. remainingFiles, filesDiff)
  806. if remainingFiles < filesDiff {
  807. return false
  808. }
  809. }
  810. if quotaResult.QuotaSize > 0 {
  811. remainingSize := quotaResult.GetRemainingSize()
  812. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  813. remainingSize, sizeDiff)
  814. if remainingSize < sizeDiff {
  815. return false
  816. }
  817. }
  818. return true
  819. }
  820. // GetMaxWriteSize returns the allowed size for an upload or an error
  821. // if no enough size is available for a resume/append
  822. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64, isUploadResumeSupported bool) (int64, error) {
  823. maxWriteSize := quotaResult.GetRemainingSize()
  824. if isResume {
  825. if !isUploadResumeSupported {
  826. return 0, c.GetOpUnsupportedError()
  827. }
  828. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  829. return 0, c.GetQuotaExceededError()
  830. }
  831. if c.User.Filters.MaxUploadFileSize > 0 {
  832. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  833. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  834. maxWriteSize = maxUploadSize
  835. }
  836. }
  837. } else {
  838. if maxWriteSize > 0 {
  839. maxWriteSize += fileSize
  840. }
  841. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  842. maxWriteSize = c.User.Filters.MaxUploadFileSize
  843. }
  844. }
  845. return maxWriteSize, nil
  846. }
  847. // HasSpace checks user's quota usage
  848. func (c *BaseConnection) HasSpace(checkFiles, getUsage bool, requestPath string) vfs.QuotaCheckResult {
  849. result := vfs.QuotaCheckResult{
  850. HasSpace: true,
  851. AllowedSize: 0,
  852. AllowedFiles: 0,
  853. UsedSize: 0,
  854. UsedFiles: 0,
  855. QuotaSize: 0,
  856. QuotaFiles: 0,
  857. }
  858. if dataprovider.GetQuotaTracking() == 0 {
  859. return result
  860. }
  861. var err error
  862. var vfolder vfs.VirtualFolder
  863. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  864. if err == nil && !vfolder.IsIncludedInUserQuota() {
  865. if vfolder.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  866. return result
  867. }
  868. result.QuotaSize = vfolder.QuotaSize
  869. result.QuotaFiles = vfolder.QuotaFiles
  870. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.Name)
  871. } else {
  872. if c.User.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  873. return result
  874. }
  875. result.QuotaSize = c.User.QuotaSize
  876. result.QuotaFiles = c.User.QuotaFiles
  877. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedQuota(c.User.Username)
  878. }
  879. if err != nil {
  880. c.Log(logger.LevelError, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  881. result.HasSpace = false
  882. return result
  883. }
  884. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  885. result.AllowedSize = result.QuotaSize - result.UsedSize
  886. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  887. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  888. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  889. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  890. result.HasSpace = false
  891. return result
  892. }
  893. return result
  894. }
  895. // returns true if this is a rename on the same fs or local virtual folders
  896. func (c *BaseConnection) isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath string) bool {
  897. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  898. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  899. if errSrc != nil && errDst != nil {
  900. return true
  901. }
  902. if errSrc == nil && errDst == nil {
  903. if sourceFolder.Name == dstFolder.Name {
  904. return true
  905. }
  906. // we have different folders, only local fs is supported
  907. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider &&
  908. dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  909. return true
  910. }
  911. return false
  912. }
  913. if c.User.FsConfig.Provider != sdk.LocalFilesystemProvider {
  914. return false
  915. }
  916. if errSrc == nil {
  917. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  918. return true
  919. }
  920. }
  921. if errDst == nil {
  922. if dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  923. return true
  924. }
  925. }
  926. return false
  927. }
  928. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  929. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  930. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  931. if errSrc != nil && errDst != nil {
  932. return false
  933. }
  934. if errSrc == nil && errDst == nil {
  935. return sourceFolder.Name != dstFolder.Name
  936. }
  937. return true
  938. }
  939. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder *vfs.VirtualFolder, initialSize,
  940. filesSize int64, numFiles int) {
  941. if sourceFolder.Name == dstFolder.Name {
  942. // both files are inside the same virtual folder
  943. if initialSize != -1 {
  944. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  945. if dstFolder.IsIncludedInUserQuota() {
  946. dataprovider.UpdateUserQuota(&c.User, -numFiles, -initialSize, false) //nolint:errcheck
  947. }
  948. }
  949. return
  950. }
  951. // files are inside different virtual folders
  952. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  953. if sourceFolder.IsIncludedInUserQuota() {
  954. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  955. }
  956. if initialSize == -1 {
  957. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  958. if dstFolder.IsIncludedInUserQuota() {
  959. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  960. }
  961. } else {
  962. // we cannot have a directory here, initialSize != -1 only for files
  963. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  964. if dstFolder.IsIncludedInUserQuota() {
  965. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  966. }
  967. }
  968. }
  969. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  970. // move between a virtual folder and the user home dir
  971. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  972. if sourceFolder.IsIncludedInUserQuota() {
  973. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  974. }
  975. if initialSize == -1 {
  976. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  977. } else {
  978. // we cannot have a directory here, initialSize != -1 only for files
  979. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  980. }
  981. }
  982. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  983. // move between the user home dir and a virtual folder
  984. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  985. if initialSize == -1 {
  986. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  987. if dstFolder.IsIncludedInUserQuota() {
  988. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  989. }
  990. } else {
  991. // we cannot have a directory here, initialSize != -1 only for files
  992. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  993. if dstFolder.IsIncludedInUserQuota() {
  994. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  995. }
  996. }
  997. }
  998. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  999. if dataprovider.GetQuotaTracking() == 0 {
  1000. return nil
  1001. }
  1002. // we don't allow to overwrite an existing directory so targetPath can be:
  1003. // - a new file, a symlink is as a new file here
  1004. // - a file overwriting an existing one
  1005. // - a new directory
  1006. // initialSize != -1 only when overwriting files
  1007. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1008. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1009. if errSrc != nil && errDst != nil {
  1010. // both files are contained inside the user home dir
  1011. if initialSize != -1 {
  1012. // we cannot have a directory here, we are overwriting an existing file
  1013. // we need to subtract the size of the overwritten file from the user quota
  1014. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  1015. }
  1016. return nil
  1017. }
  1018. filesSize := int64(0)
  1019. numFiles := 1
  1020. if fi, err := fs.Stat(targetPath); err == nil {
  1021. if fi.Mode().IsDir() {
  1022. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  1023. if err != nil {
  1024. c.Log(logger.LevelError, "failed to update quota after rename, error scanning moved folder %#v: %v",
  1025. targetPath, err)
  1026. return err
  1027. }
  1028. } else {
  1029. filesSize = fi.Size()
  1030. }
  1031. } else {
  1032. c.Log(logger.LevelError, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  1033. return err
  1034. }
  1035. if errSrc == nil && errDst == nil {
  1036. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  1037. }
  1038. if errSrc == nil && errDst != nil {
  1039. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  1040. }
  1041. if errSrc != nil && errDst == nil {
  1042. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  1043. }
  1044. return nil
  1045. }
  1046. // IsNotExistError returns true if the specified fs error is not exist for the connection protocol
  1047. func (c *BaseConnection) IsNotExistError(err error) bool {
  1048. switch c.protocol {
  1049. case ProtocolSFTP:
  1050. return errors.Is(err, sftp.ErrSSHFxNoSuchFile)
  1051. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolHTTPShare, ProtocolDataRetention:
  1052. return errors.Is(err, os.ErrNotExist)
  1053. default:
  1054. return errors.Is(err, ErrNotExist)
  1055. }
  1056. }
  1057. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  1058. func (c *BaseConnection) GetPermissionDeniedError() error {
  1059. switch c.protocol {
  1060. case ProtocolSFTP:
  1061. return sftp.ErrSSHFxPermissionDenied
  1062. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolHTTPShare, ProtocolDataRetention:
  1063. return os.ErrPermission
  1064. default:
  1065. return ErrPermissionDenied
  1066. }
  1067. }
  1068. // GetNotExistError returns an appropriate not exist error for the connection protocol
  1069. func (c *BaseConnection) GetNotExistError() error {
  1070. switch c.protocol {
  1071. case ProtocolSFTP:
  1072. return sftp.ErrSSHFxNoSuchFile
  1073. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolHTTPShare, ProtocolDataRetention:
  1074. return os.ErrNotExist
  1075. default:
  1076. return ErrNotExist
  1077. }
  1078. }
  1079. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  1080. func (c *BaseConnection) GetOpUnsupportedError() error {
  1081. switch c.protocol {
  1082. case ProtocolSFTP:
  1083. return sftp.ErrSSHFxOpUnsupported
  1084. default:
  1085. return ErrOpUnsupported
  1086. }
  1087. }
  1088. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  1089. func (c *BaseConnection) GetQuotaExceededError() error {
  1090. switch c.protocol {
  1091. case ProtocolSFTP:
  1092. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrQuotaExceeded.Error())
  1093. case ProtocolFTP:
  1094. return ftpserver.ErrStorageExceeded
  1095. default:
  1096. return ErrQuotaExceeded
  1097. }
  1098. }
  1099. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  1100. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  1101. switch c.protocol {
  1102. case ProtocolSFTP:
  1103. if err == nil {
  1104. return false
  1105. }
  1106. if errors.Is(err, ErrQuotaExceeded) {
  1107. return true
  1108. }
  1109. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1110. case ProtocolFTP:
  1111. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1112. default:
  1113. return errors.Is(err, ErrQuotaExceeded)
  1114. }
  1115. }
  1116. // GetGenericError returns an appropriate generic error for the connection protocol
  1117. func (c *BaseConnection) GetGenericError(err error) error {
  1118. switch c.protocol {
  1119. case ProtocolSFTP:
  1120. if err == vfs.ErrStorageSizeUnavailable {
  1121. return fmt.Errorf("%w: %v", sftp.ErrSSHFxOpUnsupported, err.Error())
  1122. }
  1123. if err != nil {
  1124. if e, ok := err.(*os.PathError); ok {
  1125. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, e.Op, e.Err.Error())
  1126. }
  1127. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, err.Error())
  1128. }
  1129. return sftp.ErrSSHFxFailure
  1130. default:
  1131. if err == ErrPermissionDenied || err == ErrNotExist || err == ErrOpUnsupported ||
  1132. err == ErrQuotaExceeded || err == vfs.ErrStorageSizeUnavailable {
  1133. return err
  1134. }
  1135. return ErrGenericFailure
  1136. }
  1137. }
  1138. // GetFsError converts a filesystem error to a protocol error
  1139. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1140. if fs.IsNotExist(err) {
  1141. return c.GetNotExistError()
  1142. } else if fs.IsPermission(err) {
  1143. return c.GetPermissionDeniedError()
  1144. } else if fs.IsNotSupported(err) {
  1145. return c.GetOpUnsupportedError()
  1146. } else if err != nil {
  1147. return c.GetGenericError(err)
  1148. }
  1149. return nil
  1150. }
  1151. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1152. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1153. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1154. if err != nil {
  1155. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1156. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1157. // will not be listed
  1158. return nil, "", c.GetPermissionDeniedError()
  1159. }
  1160. return nil, "", err
  1161. }
  1162. fsPath, err := fs.ResolvePath(virtualPath)
  1163. if err != nil {
  1164. return nil, "", c.GetFsError(fs, err)
  1165. }
  1166. return fs, fsPath, nil
  1167. }