connection.go 40 KB

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