connection.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path"
  21. "strings"
  22. "sync"
  23. "sync/atomic"
  24. "time"
  25. ftpserver "github.com/fclairamb/ftpserverlib"
  26. "github.com/pkg/sftp"
  27. "github.com/sftpgo/sdk"
  28. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  29. "github.com/drakkan/sftpgo/v2/internal/logger"
  30. "github.com/drakkan/sftpgo/v2/internal/util"
  31. "github.com/drakkan/sftpgo/v2/internal/vfs"
  32. )
  33. // BaseConnection defines common fields for a connection using any supported protocol
  34. type BaseConnection struct {
  35. // last activity for this connection.
  36. // Since this field is accessed atomically we put it as first element of the struct to achieve 64 bit alignment
  37. lastActivity atomic.Int64
  38. uploadDone atomic.Bool
  39. downloadDone atomic.Bool
  40. // unique ID for a transfer.
  41. // This field is accessed atomically so we put it at the beginning of the struct to achieve 64 bit alignment
  42. transferID atomic.Int64
  43. // Unique identifier for the connection
  44. ID string
  45. // user associated with this connection if any
  46. User dataprovider.User
  47. // start time for this connection
  48. startTime time.Time
  49. protocol string
  50. remoteAddr string
  51. localAddr string
  52. sync.RWMutex
  53. activeTransfers []ActiveTransfer
  54. }
  55. // NewBaseConnection returns a new BaseConnection
  56. func NewBaseConnection(id, protocol, localAddr, remoteAddr string, user dataprovider.User) *BaseConnection {
  57. connID := id
  58. if util.Contains(supportedProtocols, protocol) {
  59. connID = fmt.Sprintf("%s_%s", protocol, id)
  60. }
  61. user.UploadBandwidth, user.DownloadBandwidth = user.GetBandwidthForIP(util.GetIPFromRemoteAddress(remoteAddr), connID)
  62. c := &BaseConnection{
  63. ID: connID,
  64. User: user,
  65. startTime: time.Now(),
  66. protocol: protocol,
  67. localAddr: localAddr,
  68. remoteAddr: remoteAddr,
  69. }
  70. c.transferID.Store(0)
  71. c.lastActivity.Store(time.Now().UnixNano())
  72. return c
  73. }
  74. // Log outputs a log entry to the configured logger
  75. func (c *BaseConnection) Log(level logger.LogLevel, format string, v ...any) {
  76. logger.Log(level, c.protocol, c.ID, format, v...)
  77. }
  78. // GetTransferID returns an unique transfer ID for this connection
  79. func (c *BaseConnection) GetTransferID() int64 {
  80. return c.transferID.Add(1)
  81. }
  82. // GetID returns the connection ID
  83. func (c *BaseConnection) GetID() string {
  84. return c.ID
  85. }
  86. // GetUsername returns the authenticated username associated with this connection if any
  87. func (c *BaseConnection) GetUsername() string {
  88. return c.User.Username
  89. }
  90. // GetRole returns the role for the user associated with this connection
  91. func (c *BaseConnection) GetRole() string {
  92. return c.User.Role
  93. }
  94. // GetMaxSessions returns the maximum number of concurrent sessions allowed
  95. func (c *BaseConnection) GetMaxSessions() int {
  96. return c.User.MaxSessions
  97. }
  98. // GetProtocol returns the protocol for the connection
  99. func (c *BaseConnection) GetProtocol() string {
  100. return c.protocol
  101. }
  102. // GetRemoteIP returns the remote ip address
  103. func (c *BaseConnection) GetRemoteIP() string {
  104. return util.GetIPFromRemoteAddress(c.remoteAddr)
  105. }
  106. // SetProtocol sets the protocol for this connection
  107. func (c *BaseConnection) SetProtocol(protocol string) {
  108. c.protocol = protocol
  109. if util.Contains(supportedProtocols, c.protocol) {
  110. c.ID = fmt.Sprintf("%v_%v", c.protocol, c.ID)
  111. }
  112. }
  113. // GetConnectionTime returns the initial connection time
  114. func (c *BaseConnection) GetConnectionTime() time.Time {
  115. return c.startTime
  116. }
  117. // UpdateLastActivity updates last activity for this connection
  118. func (c *BaseConnection) UpdateLastActivity() {
  119. c.lastActivity.Store(time.Now().UnixNano())
  120. }
  121. // GetLastActivity returns the last connection activity
  122. func (c *BaseConnection) GetLastActivity() time.Time {
  123. return time.Unix(0, c.lastActivity.Load())
  124. }
  125. // CloseFS closes the underlying fs
  126. func (c *BaseConnection) CloseFS() error {
  127. return c.User.CloseFs()
  128. }
  129. // AddTransfer associates a new transfer to this connection
  130. func (c *BaseConnection) AddTransfer(t ActiveTransfer) {
  131. c.Lock()
  132. defer c.Unlock()
  133. c.activeTransfers = append(c.activeTransfers, t)
  134. c.Log(logger.LevelDebug, "transfer added, id: %v, active transfers: %v", t.GetID(), len(c.activeTransfers))
  135. if t.HasSizeLimit() {
  136. folderName := ""
  137. if t.GetType() == TransferUpload {
  138. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(t.GetVirtualPath()))
  139. if err == nil {
  140. if !vfolder.IsIncludedInUserQuota() {
  141. folderName = vfolder.Name
  142. }
  143. }
  144. }
  145. go transfersChecker.AddTransfer(dataprovider.ActiveTransfer{
  146. ID: t.GetID(),
  147. Type: t.GetType(),
  148. ConnID: c.ID,
  149. Username: c.GetUsername(),
  150. FolderName: folderName,
  151. IP: c.GetRemoteIP(),
  152. TruncatedSize: t.GetTruncatedSize(),
  153. CreatedAt: util.GetTimeAsMsSinceEpoch(time.Now()),
  154. UpdatedAt: util.GetTimeAsMsSinceEpoch(time.Now()),
  155. })
  156. }
  157. }
  158. // RemoveTransfer removes the specified transfer from the active ones
  159. func (c *BaseConnection) RemoveTransfer(t ActiveTransfer) {
  160. c.Lock()
  161. defer c.Unlock()
  162. if t.HasSizeLimit() {
  163. go transfersChecker.RemoveTransfer(t.GetID(), c.ID)
  164. }
  165. for idx, transfer := range c.activeTransfers {
  166. if transfer.GetID() == t.GetID() {
  167. lastIdx := len(c.activeTransfers) - 1
  168. c.activeTransfers[idx] = c.activeTransfers[lastIdx]
  169. c.activeTransfers[lastIdx] = nil
  170. c.activeTransfers = c.activeTransfers[:lastIdx]
  171. c.Log(logger.LevelDebug, "transfer removed, id: %v active transfers: %v", t.GetID(), len(c.activeTransfers))
  172. return
  173. }
  174. }
  175. c.Log(logger.LevelWarn, "transfer to remove with id %v not found!", t.GetID())
  176. }
  177. // SignalTransferClose makes the transfer fail on the next read/write with the
  178. // specified error
  179. func (c *BaseConnection) SignalTransferClose(transferID int64, err error) {
  180. c.RLock()
  181. defer c.RUnlock()
  182. for _, t := range c.activeTransfers {
  183. if t.GetID() == transferID {
  184. c.Log(logger.LevelInfo, "signal transfer close for transfer id %v", transferID)
  185. t.SignalClose(err)
  186. }
  187. }
  188. }
  189. // GetTransfers returns the active transfers
  190. func (c *BaseConnection) GetTransfers() []ConnectionTransfer {
  191. c.RLock()
  192. defer c.RUnlock()
  193. transfers := make([]ConnectionTransfer, 0, len(c.activeTransfers))
  194. for _, t := range c.activeTransfers {
  195. var operationType string
  196. switch t.GetType() {
  197. case TransferDownload:
  198. operationType = operationDownload
  199. case TransferUpload:
  200. operationType = operationUpload
  201. }
  202. transfers = append(transfers, ConnectionTransfer{
  203. ID: t.GetID(),
  204. OperationType: operationType,
  205. StartTime: util.GetTimeAsMsSinceEpoch(t.GetStartTime()),
  206. Size: t.GetSize(),
  207. VirtualPath: t.GetVirtualPath(),
  208. HasSizeLimit: t.HasSizeLimit(),
  209. ULSize: t.GetUploadedSize(),
  210. DLSize: t.GetDownloadedSize(),
  211. })
  212. }
  213. return transfers
  214. }
  215. // SignalTransfersAbort signals to the active transfers to exit as soon as possible
  216. func (c *BaseConnection) SignalTransfersAbort() error {
  217. c.RLock()
  218. defer c.RUnlock()
  219. if len(c.activeTransfers) == 0 {
  220. return errors.New("no active transfer found")
  221. }
  222. for _, t := range c.activeTransfers {
  223. t.SignalClose(ErrTransferAborted)
  224. }
  225. return nil
  226. }
  227. func (c *BaseConnection) getRealFsPath(fsPath string) string {
  228. c.RLock()
  229. defer c.RUnlock()
  230. for _, t := range c.activeTransfers {
  231. if p := t.GetRealFsPath(fsPath); p != "" {
  232. return p
  233. }
  234. }
  235. return fsPath
  236. }
  237. func (c *BaseConnection) setTimes(fsPath string, atime time.Time, mtime time.Time) bool {
  238. c.RLock()
  239. defer c.RUnlock()
  240. for _, t := range c.activeTransfers {
  241. if t.SetTimes(fsPath, atime, mtime) {
  242. return true
  243. }
  244. }
  245. return false
  246. }
  247. func (c *BaseConnection) truncateOpenHandle(fsPath string, size int64) (int64, error) {
  248. c.RLock()
  249. defer c.RUnlock()
  250. for _, t := range c.activeTransfers {
  251. initialSize, err := t.Truncate(fsPath, size)
  252. if err != errTransferMismatch {
  253. return initialSize, err
  254. }
  255. }
  256. return 0, errNoTransfer
  257. }
  258. // ListDir reads the directory matching virtualPath and returns a list of directory entries
  259. func (c *BaseConnection) ListDir(virtualPath string) ([]os.FileInfo, error) {
  260. if !c.User.HasPerm(dataprovider.PermListItems, virtualPath) {
  261. return nil, c.GetPermissionDeniedError()
  262. }
  263. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  264. if err != nil {
  265. return nil, err
  266. }
  267. files, err := fs.ReadDir(fsPath)
  268. if err != nil {
  269. c.Log(logger.LevelDebug, "error listing directory: %+v", err)
  270. return nil, c.GetFsError(fs, err)
  271. }
  272. return c.User.FilterListDir(files, virtualPath), nil
  273. }
  274. // CheckParentDirs tries to create the specified directory and any missing parent dirs
  275. func (c *BaseConnection) CheckParentDirs(virtualPath string) error {
  276. fs, err := c.User.GetFilesystemForPath(virtualPath, c.GetID())
  277. if err != nil {
  278. return err
  279. }
  280. if fs.HasVirtualFolders() {
  281. return nil
  282. }
  283. if _, err := c.DoStat(virtualPath, 0, false); !c.IsNotExistError(err) {
  284. return err
  285. }
  286. dirs := util.GetDirsForVirtualPath(virtualPath)
  287. for idx := len(dirs) - 1; idx >= 0; idx-- {
  288. fs, err = c.User.GetFilesystemForPath(dirs[idx], c.GetID())
  289. if err != nil {
  290. return err
  291. }
  292. if fs.HasVirtualFolders() {
  293. continue
  294. }
  295. if err = c.createDirIfMissing(dirs[idx]); err != nil {
  296. return fmt.Errorf("unable to check/create missing parent dir %q for virtual path %q: %w",
  297. dirs[idx], virtualPath, err)
  298. }
  299. }
  300. return nil
  301. }
  302. // CreateDir creates a new directory at the specified fsPath
  303. func (c *BaseConnection) CreateDir(virtualPath string, checkFilePatterns bool) error {
  304. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  305. return c.GetPermissionDeniedError()
  306. }
  307. if checkFilePatterns {
  308. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  309. return c.GetPermissionDeniedError()
  310. }
  311. }
  312. if c.User.IsVirtualFolder(virtualPath) {
  313. c.Log(logger.LevelWarn, "mkdir not allowed %q is a virtual folder", virtualPath)
  314. return c.GetPermissionDeniedError()
  315. }
  316. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  317. if err != nil {
  318. return err
  319. }
  320. if err := fs.Mkdir(fsPath); err != nil {
  321. c.Log(logger.LevelError, "error creating dir: %#v error: %+v", fsPath, err)
  322. return c.GetFsError(fs, err)
  323. }
  324. vfs.SetPathPermissions(fs, fsPath, c.User.GetUID(), c.User.GetGID())
  325. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  326. c.localAddr, c.remoteAddr)
  327. ExecuteActionNotification(c, operationMkdir, fsPath, virtualPath, "", "", "", 0, nil) //nolint:errcheck
  328. return nil
  329. }
  330. // IsRemoveFileAllowed returns an error if removing this file is not allowed
  331. func (c *BaseConnection) IsRemoveFileAllowed(virtualPath string) error {
  332. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  333. return c.GetPermissionDeniedError()
  334. }
  335. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  336. c.Log(logger.LevelDebug, "removing file %q is not allowed", virtualPath)
  337. return c.GetErrorForDeniedFile(policy)
  338. }
  339. return nil
  340. }
  341. // RemoveFile removes a file at the specified fsPath
  342. func (c *BaseConnection) RemoveFile(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  343. if err := c.IsRemoveFileAllowed(virtualPath); err != nil {
  344. return err
  345. }
  346. size := info.Size()
  347. status, err := ExecutePreAction(c, operationPreDelete, fsPath, virtualPath, size, 0)
  348. if err != nil {
  349. c.Log(logger.LevelDebug, "delete for file %q denied by pre action: %v", virtualPath, err)
  350. return c.GetPermissionDeniedError()
  351. }
  352. updateQuota := true
  353. if err := fs.Remove(fsPath, false); err != nil {
  354. if status > 0 && fs.IsNotExist(err) {
  355. // file removed in the pre-action, if the file was deleted from the EventManager the quota is already updated
  356. c.Log(logger.LevelDebug, "file deleted from the hook, status: %d", status)
  357. updateQuota = (status == 1)
  358. } else {
  359. c.Log(logger.LevelError, "failed to remove file/symlink %q: %+v", fsPath, err)
  360. return c.GetFsError(fs, err)
  361. }
  362. }
  363. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  364. c.localAddr, c.remoteAddr)
  365. if updateQuota && info.Mode()&os.ModeSymlink == 0 {
  366. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  367. if err == nil {
  368. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, -1, -size, false) //nolint:errcheck
  369. if vfolder.IsIncludedInUserQuota() {
  370. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  371. }
  372. } else {
  373. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  374. }
  375. }
  376. ExecuteActionNotification(c, operationDelete, fsPath, virtualPath, "", "", "", size, nil) //nolint:errcheck
  377. return nil
  378. }
  379. // IsRemoveDirAllowed returns an error if removing this directory is not allowed
  380. func (c *BaseConnection) IsRemoveDirAllowed(fs vfs.Fs, fsPath, virtualPath string) error {
  381. if virtualPath == "/" || fs.GetRelativePath(fsPath) == "/" {
  382. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  383. return c.GetPermissionDeniedError()
  384. }
  385. if c.User.IsVirtualFolder(virtualPath) {
  386. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %q", virtualPath)
  387. return fmt.Errorf("removing virtual folders is not allowed: %w", c.GetPermissionDeniedError())
  388. }
  389. if c.User.HasVirtualFoldersInside(virtualPath) {
  390. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %#v", virtualPath)
  391. return fmt.Errorf("cannot remove directory %q with virtual folders inside: %w", virtualPath, c.GetOpUnsupportedError())
  392. }
  393. if c.User.IsMappedPath(fsPath) {
  394. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %q", fsPath)
  395. return fmt.Errorf("removing the directory %q mapped as virtual folder is not allowed: %w",
  396. virtualPath, c.GetPermissionDeniedError())
  397. }
  398. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  399. return c.GetPermissionDeniedError()
  400. }
  401. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  402. c.Log(logger.LevelDebug, "removing directory %q is not allowed", virtualPath)
  403. return c.GetErrorForDeniedFile(policy)
  404. }
  405. return nil
  406. }
  407. // RemoveDir removes a directory at the specified fsPath
  408. func (c *BaseConnection) RemoveDir(virtualPath string) error {
  409. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  410. if err != nil {
  411. return err
  412. }
  413. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  414. return err
  415. }
  416. var fi os.FileInfo
  417. if fi, err = fs.Lstat(fsPath); err != nil {
  418. // see #149
  419. if fs.IsNotExist(err) && fs.HasVirtualFolders() {
  420. return nil
  421. }
  422. c.Log(logger.LevelError, "failed to remove a dir %#v: stat error: %+v", fsPath, err)
  423. return c.GetFsError(fs, err)
  424. }
  425. if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
  426. c.Log(logger.LevelError, "cannot remove %q is not a directory", fsPath)
  427. return c.GetGenericError(nil)
  428. }
  429. if err := fs.Remove(fsPath, true); err != nil {
  430. c.Log(logger.LevelError, "failed to remove directory %#v: %+v", fsPath, err)
  431. return c.GetFsError(fs, err)
  432. }
  433. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  434. c.localAddr, c.remoteAddr)
  435. ExecuteActionNotification(c, operationRmdir, fsPath, virtualPath, "", "", "", 0, nil) //nolint:errcheck
  436. return nil
  437. }
  438. func (c *BaseConnection) doRecursiveRemoveDirEntry(virtualPath string, info os.FileInfo) error {
  439. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  440. if err != nil {
  441. return err
  442. }
  443. return c.doRecursiveRemove(fs, fsPath, virtualPath, info)
  444. }
  445. func (c *BaseConnection) doRecursiveRemove(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  446. if info.IsDir() {
  447. entries, err := c.ListDir(virtualPath)
  448. if err != nil {
  449. return fmt.Errorf("unable to get contents for dir %q: %w", virtualPath, err)
  450. }
  451. for _, fi := range entries {
  452. targetPath := path.Join(virtualPath, fi.Name())
  453. if err := c.doRecursiveRemoveDirEntry(targetPath, fi); err != nil {
  454. return err
  455. }
  456. }
  457. return c.RemoveDir(virtualPath)
  458. }
  459. return c.RemoveFile(fs, fsPath, virtualPath, info)
  460. }
  461. // RemoveAll removes the specified path and any children it contains
  462. func (c *BaseConnection) RemoveAll(virtualPath string) error {
  463. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  464. if err != nil {
  465. return err
  466. }
  467. fi, err := fs.Lstat(fsPath)
  468. if err != nil {
  469. c.Log(logger.LevelDebug, "failed to remove path %q: stat error: %+v", fsPath, err)
  470. return c.GetFsError(fs, err)
  471. }
  472. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  473. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  474. return err
  475. }
  476. return c.doRecursiveRemove(fs, fsPath, virtualPath, fi)
  477. }
  478. return c.RemoveFile(fs, fsPath, virtualPath, fi)
  479. }
  480. func (c *BaseConnection) checkCopy(srcInfo, dstInfo os.FileInfo, virtualSource, virtualTarget string) error {
  481. _, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSource)
  482. if err != nil {
  483. return err
  484. }
  485. _, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTarget)
  486. if err != nil {
  487. return err
  488. }
  489. if srcInfo.IsDir() {
  490. if dstInfo != nil && !dstInfo.IsDir() {
  491. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualTarget, virtualSource, c.GetOpUnsupportedError())
  492. }
  493. if util.IsDirOverlapped(virtualSource, virtualTarget, true, "/") {
  494. return fmt.Errorf("nested copy %q => %q is not supported: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  495. }
  496. if util.IsDirOverlapped(fsSourcePath, fsTargetPath, true, c.User.FsConfig.GetPathSeparator()) {
  497. c.Log(logger.LevelWarn, "nested fs copy %q => %q not allowed", fsSourcePath, fsTargetPath)
  498. return fmt.Errorf("nested fs copy is not supported: %w", c.GetOpUnsupportedError())
  499. }
  500. return nil
  501. }
  502. if dstInfo != nil && dstInfo.IsDir() {
  503. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  504. }
  505. if fsSourcePath == fsTargetPath {
  506. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  507. }
  508. return nil
  509. }
  510. func (c *BaseConnection) copyFile(virtualSourcePath, virtualTargetPath string, srcSize int64) error {
  511. if ok, _ := c.User.IsFileAllowed(virtualTargetPath); !ok {
  512. return fmt.Errorf("file %q is not allowed: %w", virtualTargetPath, c.GetPermissionDeniedError())
  513. }
  514. reader, rCancelFn, err := getFileReader(c, virtualSourcePath)
  515. if err != nil {
  516. return fmt.Errorf("unable to get reader for path %q: %w", virtualSourcePath, err)
  517. }
  518. defer rCancelFn()
  519. defer reader.Close()
  520. writer, numFiles, truncatedSize, wCancelFn, err := getFileWriter(c, virtualTargetPath, srcSize)
  521. if err != nil {
  522. return fmt.Errorf("unable to get writer for path %q: %w", virtualTargetPath, err)
  523. }
  524. defer wCancelFn()
  525. _, err = io.Copy(writer, reader)
  526. return closeWriterAndUpdateQuota(writer, c, virtualSourcePath, virtualTargetPath, numFiles, truncatedSize, err, operationCopy)
  527. }
  528. func (c *BaseConnection) doRecursiveCopy(virtualSourcePath, virtualTargetPath string, srcInfo os.FileInfo,
  529. createTargetDir bool,
  530. ) error {
  531. if srcInfo.IsDir() {
  532. if createTargetDir {
  533. if err := c.CreateDir(virtualTargetPath, false); err != nil {
  534. return fmt.Errorf("unable to create directory %q: %w", virtualTargetPath, err)
  535. }
  536. }
  537. entries, err := c.ListDir(virtualSourcePath)
  538. if err != nil {
  539. return fmt.Errorf("unable to get contents for dir %q: %w", virtualSourcePath, err)
  540. }
  541. for _, info := range entries {
  542. sourcePath := path.Join(virtualSourcePath, info.Name())
  543. targetPath := path.Join(virtualTargetPath, info.Name())
  544. targetInfo, err := c.DoStat(targetPath, 1, false)
  545. if err == nil {
  546. if info.IsDir() && targetInfo.IsDir() {
  547. c.Log(logger.LevelDebug, "target copy dir %q already exists", targetPath)
  548. continue
  549. }
  550. }
  551. if err != nil && !c.IsNotExistError(err) {
  552. return err
  553. }
  554. if err := c.checkCopy(info, targetInfo, sourcePath, targetPath); err != nil {
  555. return err
  556. }
  557. if err := c.doRecursiveCopy(sourcePath, targetPath, info, true); err != nil {
  558. return err
  559. }
  560. }
  561. return nil
  562. }
  563. if !srcInfo.Mode().IsRegular() {
  564. c.Log(logger.LevelInfo, "skipping copy for non regular file %q", virtualSourcePath)
  565. return nil
  566. }
  567. return c.copyFile(virtualSourcePath, virtualTargetPath, srcInfo.Size())
  568. }
  569. // Copy virtualSourcePath to virtualTargetPath
  570. func (c *BaseConnection) Copy(virtualSourcePath, virtualTargetPath string) error {
  571. copyFromSource := strings.HasSuffix(virtualSourcePath, "/")
  572. copyInTarget := strings.HasSuffix(virtualTargetPath, "/")
  573. virtualSourcePath = path.Clean(virtualSourcePath)
  574. virtualTargetPath = path.Clean(virtualTargetPath)
  575. if virtualSourcePath == virtualTargetPath {
  576. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  577. }
  578. srcInfo, err := c.DoStat(virtualSourcePath, 1, false)
  579. if err != nil {
  580. return err
  581. }
  582. if srcInfo.Mode()&os.ModeSymlink != 0 {
  583. return fmt.Errorf("copying symlinks is not supported: %w", c.GetOpUnsupportedError())
  584. }
  585. dstInfo, err := c.DoStat(virtualTargetPath, 1, false)
  586. if err == nil && !copyFromSource {
  587. copyInTarget = dstInfo.IsDir()
  588. }
  589. if err != nil && !c.IsNotExistError(err) {
  590. return err
  591. }
  592. destPath := virtualTargetPath
  593. if copyInTarget {
  594. destPath = path.Join(virtualTargetPath, path.Base(virtualSourcePath))
  595. dstInfo, err = c.DoStat(destPath, 1, false)
  596. if err != nil && !c.IsNotExistError(err) {
  597. return err
  598. }
  599. }
  600. createTargetDir := true
  601. if dstInfo != nil && dstInfo.IsDir() {
  602. createTargetDir = false
  603. }
  604. if err := c.checkCopy(srcInfo, dstInfo, virtualSourcePath, destPath); err != nil {
  605. return err
  606. }
  607. if err := c.CheckParentDirs(path.Dir(destPath)); err != nil {
  608. return err
  609. }
  610. return c.doRecursiveCopy(virtualSourcePath, destPath, srcInfo, createTargetDir)
  611. }
  612. // Rename renames (moves) virtualSourcePath to virtualTargetPath
  613. func (c *BaseConnection) Rename(virtualSourcePath, virtualTargetPath string) error {
  614. if virtualSourcePath == virtualTargetPath {
  615. return fmt.Errorf("the rename source and target cannot be the same: %w", c.GetOpUnsupportedError())
  616. }
  617. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  618. if err != nil {
  619. return err
  620. }
  621. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  622. if err != nil {
  623. return err
  624. }
  625. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  626. if err != nil {
  627. return c.GetFsError(fsSrc, err)
  628. }
  629. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  630. return c.GetPermissionDeniedError()
  631. }
  632. initialSize := int64(-1)
  633. if dstInfo, err := fsDst.Lstat(fsTargetPath); err == nil {
  634. if dstInfo.IsDir() {
  635. c.Log(logger.LevelWarn, "attempted to rename %q overwriting an existing directory %q",
  636. fsSourcePath, fsTargetPath)
  637. return c.GetOpUnsupportedError()
  638. }
  639. // we are overwriting an existing file/symlink
  640. if dstInfo.Mode().IsRegular() {
  641. initialSize = dstInfo.Size()
  642. }
  643. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  644. c.Log(logger.LevelDebug, "renaming %q -> %q is not allowed. Target exists but the user %q"+
  645. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  646. return c.GetPermissionDeniedError()
  647. }
  648. }
  649. if srcInfo.IsDir() {
  650. if err := c.checkFolderRename(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo); err != nil {
  651. return err
  652. }
  653. }
  654. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  655. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  656. return c.GetGenericError(ErrQuotaExceeded)
  657. }
  658. if err := fsDst.Rename(fsSourcePath, fsTargetPath); err != nil {
  659. c.Log(logger.LevelError, "failed to rename %q -> %q: %+v", fsSourcePath, fsTargetPath, err)
  660. return c.GetFsError(fsSrc, err)
  661. }
  662. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  663. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize) //nolint:errcheck
  664. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  665. "", "", "", -1, c.localAddr, c.remoteAddr)
  666. ExecuteActionNotification(c, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, //nolint:errcheck
  667. virtualTargetPath, "", 0, nil)
  668. return nil
  669. }
  670. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  671. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  672. var relativePath string
  673. if !path.IsAbs(virtualSourcePath) {
  674. relativePath = virtualSourcePath
  675. virtualSourcePath = path.Join(path.Dir(virtualTargetPath), relativePath)
  676. c.Log(logger.LevelDebug, "link relative path %q resolved as %q, target path %q",
  677. relativePath, virtualSourcePath, virtualTargetPath)
  678. }
  679. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  680. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  681. return c.GetOpUnsupportedError()
  682. }
  683. // we cannot have a cross folder request here so only one fs is enough
  684. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  685. if err != nil {
  686. return err
  687. }
  688. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  689. if err != nil {
  690. return c.GetFsError(fs, err)
  691. }
  692. if fs.GetRelativePath(fsSourcePath) == "/" {
  693. c.Log(logger.LevelError, "symlinking root dir is not allowed")
  694. return c.GetPermissionDeniedError()
  695. }
  696. if fs.GetRelativePath(fsTargetPath) == "/" {
  697. c.Log(logger.LevelError, "symlinking to root dir is not allowed")
  698. return c.GetPermissionDeniedError()
  699. }
  700. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  701. return c.GetPermissionDeniedError()
  702. }
  703. ok, policy := c.User.IsFileAllowed(virtualSourcePath)
  704. if !ok && policy == sdk.DenyPolicyHide {
  705. c.Log(logger.LevelError, "symlink source path %#v is not allowed", virtualSourcePath)
  706. return c.GetNotExistError()
  707. }
  708. if ok, _ = c.User.IsFileAllowed(virtualTargetPath); !ok {
  709. c.Log(logger.LevelError, "symlink target path %#v is not allowed", virtualTargetPath)
  710. return c.GetPermissionDeniedError()
  711. }
  712. if relativePath != "" {
  713. fsSourcePath = relativePath
  714. }
  715. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  716. c.Log(logger.LevelError, "failed to create symlink %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  717. return c.GetFsError(fs, err)
  718. }
  719. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  720. "", "", -1, c.localAddr, c.remoteAddr)
  721. return nil
  722. }
  723. func (c *BaseConnection) getPathForSetStatPerms(fs vfs.Fs, fsPath, virtualPath string) string {
  724. pathForPerms := virtualPath
  725. if fi, err := fs.Lstat(fsPath); err == nil {
  726. if fi.IsDir() {
  727. pathForPerms = path.Dir(virtualPath)
  728. }
  729. }
  730. return pathForPerms
  731. }
  732. func (c *BaseConnection) doStatInternal(virtualPath string, mode int, checkFilePatterns,
  733. convertResult bool,
  734. ) (os.FileInfo, error) {
  735. // for some vfs we don't create intermediary folders so we cannot simply check
  736. // if virtualPath is a virtual folder
  737. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  738. if _, ok := vfolders[virtualPath]; ok {
  739. return vfs.NewFileInfo(virtualPath, true, 0, time.Unix(0, 0), false), nil
  740. }
  741. if checkFilePatterns && virtualPath != "/" {
  742. ok, policy := c.User.IsFileAllowed(virtualPath)
  743. if !ok && policy == sdk.DenyPolicyHide {
  744. return nil, c.GetNotExistError()
  745. }
  746. }
  747. var info os.FileInfo
  748. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  749. if err != nil {
  750. return info, err
  751. }
  752. if mode == 1 {
  753. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  754. } else {
  755. info, err = fs.Stat(c.getRealFsPath(fsPath))
  756. }
  757. if err != nil {
  758. if !fs.IsNotExist(err) {
  759. c.Log(logger.LevelWarn, "stat error for path %q: %+v", virtualPath, err)
  760. }
  761. return info, c.GetFsError(fs, err)
  762. }
  763. if convertResult && vfs.IsCryptOsFs(fs) {
  764. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  765. }
  766. return info, nil
  767. }
  768. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  769. func (c *BaseConnection) DoStat(virtualPath string, mode int, checkFilePatterns bool) (os.FileInfo, error) {
  770. return c.doStatInternal(virtualPath, mode, checkFilePatterns, true)
  771. }
  772. func (c *BaseConnection) createDirIfMissing(name string) error {
  773. _, err := c.DoStat(name, 0, false)
  774. if c.IsNotExistError(err) {
  775. return c.CreateDir(name, false)
  776. }
  777. return err
  778. }
  779. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  780. if Config.SetstatMode == 1 {
  781. return true
  782. }
  783. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  784. return true
  785. }
  786. return false
  787. }
  788. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  789. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  790. return c.GetPermissionDeniedError()
  791. }
  792. if c.ignoreSetStat(fs) {
  793. return nil
  794. }
  795. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  796. c.Log(logger.LevelError, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  797. return c.GetFsError(fs, err)
  798. }
  799. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  800. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr)
  801. return nil
  802. }
  803. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  804. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  805. return c.GetPermissionDeniedError()
  806. }
  807. if c.ignoreSetStat(fs) {
  808. return nil
  809. }
  810. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  811. c.Log(logger.LevelError, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  812. attributes.GID, err)
  813. return c.GetFsError(fs, err)
  814. }
  815. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  816. "", "", "", -1, c.localAddr, c.remoteAddr)
  817. return nil
  818. }
  819. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  820. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  821. return c.GetPermissionDeniedError()
  822. }
  823. if Config.SetstatMode == 1 {
  824. return nil
  825. }
  826. isUploading := c.setTimes(fsPath, attributes.Atime, attributes.Mtime)
  827. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime, isUploading); err != nil {
  828. c.setTimes(fsPath, time.Time{}, time.Time{})
  829. if errors.Is(err, vfs.ErrVfsUnsupported) && Config.SetstatMode == 2 {
  830. return nil
  831. }
  832. c.Log(logger.LevelError, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  833. fsPath, attributes.Atime, attributes.Mtime, err)
  834. return c.GetFsError(fs, err)
  835. }
  836. accessTimeString := attributes.Atime.Format(chtimesFormat)
  837. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  838. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  839. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr)
  840. return nil
  841. }
  842. // SetStat set StatAttributes for the specified fsPath
  843. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  844. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  845. return c.GetErrorForDeniedFile(policy)
  846. }
  847. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  848. if err != nil {
  849. return err
  850. }
  851. pathForPerms := c.getPathForSetStatPerms(fs, fsPath, virtualPath)
  852. if attributes.Flags&StatAttrTimes != 0 {
  853. if err = c.handleChtimes(fs, fsPath, pathForPerms, attributes); err != nil {
  854. return err
  855. }
  856. }
  857. if attributes.Flags&StatAttrPerms != 0 {
  858. if err = c.handleChmod(fs, fsPath, pathForPerms, attributes); err != nil {
  859. return err
  860. }
  861. }
  862. if attributes.Flags&StatAttrUIDGID != 0 {
  863. if err = c.handleChown(fs, fsPath, pathForPerms, attributes); err != nil {
  864. return err
  865. }
  866. }
  867. if attributes.Flags&StatAttrSize != 0 {
  868. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  869. return c.GetPermissionDeniedError()
  870. }
  871. if err = c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  872. c.Log(logger.LevelError, "failed to truncate path %#v, size: %v, err: %+v", fsPath, attributes.Size, err)
  873. return c.GetFsError(fs, err)
  874. }
  875. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  876. "", attributes.Size, c.localAddr, c.remoteAddr)
  877. }
  878. return nil
  879. }
  880. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  881. // check first if we have an open transfer for the given path and try to truncate the file already opened
  882. // if we found no transfer we truncate by path.
  883. var initialSize int64
  884. var err error
  885. initialSize, err = c.truncateOpenHandle(fsPath, size)
  886. if err == errNoTransfer {
  887. c.Log(logger.LevelDebug, "file path %#v not found in active transfers, execute trucate by path", fsPath)
  888. var info os.FileInfo
  889. info, err = fs.Stat(fsPath)
  890. if err != nil {
  891. return err
  892. }
  893. initialSize = info.Size()
  894. err = fs.Truncate(fsPath, size)
  895. }
  896. if err == nil && vfs.HasTruncateSupport(fs) {
  897. sizeDiff := initialSize - size
  898. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  899. if err == nil {
  900. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  901. if vfolder.IsIncludedInUserQuota() {
  902. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  903. }
  904. } else {
  905. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  906. }
  907. }
  908. return err
  909. }
  910. func (c *BaseConnection) checkRecursiveRenameDirPermissions(fsSrc, fsDst vfs.Fs, sourcePath, targetPath,
  911. virtualSourcePath, virtualTargetPath string, fi os.FileInfo,
  912. ) error {
  913. if !c.User.HasPermissionsInside(virtualSourcePath) &&
  914. !c.User.HasPermissionsInside(virtualTargetPath) {
  915. if !c.isRenamePermitted(fsSrc, fsDst, sourcePath, targetPath, virtualSourcePath, virtualTargetPath, fi) {
  916. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  917. sourcePath, targetPath, virtualTargetPath)
  918. return c.GetPermissionDeniedError()
  919. }
  920. // if all rename permissions are granted we have finished, otherwise we have to walk
  921. // because we could have the rename dir permission but not the rename file and the dir to
  922. // rename could contain files
  923. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) && c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  924. return nil
  925. }
  926. }
  927. return fsSrc.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  928. if err != nil {
  929. return c.GetFsError(fsSrc, err)
  930. }
  931. if walkedPath != sourcePath && vfs.HasImplicitAtomicUploads(fsSrc) {
  932. c.Log(logger.LevelInfo, "cannot rename non empty directory %q on this filesystem", virtualSourcePath)
  933. return c.GetOpUnsupportedError()
  934. }
  935. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  936. virtualSrcPath := fsSrc.GetRelativePath(walkedPath)
  937. virtualDstPath := fsDst.GetRelativePath(dstPath)
  938. if !c.isRenamePermitted(fsSrc, fsDst, walkedPath, dstPath, virtualSrcPath, virtualDstPath, info) {
  939. c.Log(logger.LevelInfo, "rename %q -> %q is not allowed, virtual destination path: %q",
  940. walkedPath, dstPath, virtualDstPath)
  941. return c.GetPermissionDeniedError()
  942. }
  943. return nil
  944. })
  945. }
  946. func (c *BaseConnection) hasRenamePerms(virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  947. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) &&
  948. c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  949. return true
  950. }
  951. if fi == nil {
  952. // we don't know if this is a file or a directory and we don't have all the rename perms, return false
  953. return false
  954. }
  955. if fi.IsDir() {
  956. perms := []string{
  957. dataprovider.PermRenameDirs,
  958. dataprovider.PermRename,
  959. }
  960. return c.User.HasAnyPerm(perms, path.Dir(virtualSourcePath)) &&
  961. c.User.HasAnyPerm(perms, path.Dir(virtualTargetPath))
  962. }
  963. // file or symlink
  964. perms := []string{
  965. dataprovider.PermRenameFiles,
  966. dataprovider.PermRename,
  967. }
  968. return c.User.HasAnyPerm(perms, path.Dir(virtualSourcePath)) &&
  969. c.User.HasAnyPerm(perms, path.Dir(virtualTargetPath))
  970. }
  971. func (c *BaseConnection) checkFolderRename(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath,
  972. virtualTargetPath string, fi os.FileInfo) error {
  973. if util.IsDirOverlapped(virtualSourcePath, virtualTargetPath, true, "/") {
  974. c.Log(logger.LevelDebug, "renaming the folder %q->%q is not supported: nested folders",
  975. virtualSourcePath, virtualTargetPath)
  976. return c.GetOpUnsupportedError()
  977. }
  978. if util.IsDirOverlapped(fsSourcePath, fsTargetPath, true, c.User.FsConfig.GetPathSeparator()) {
  979. c.Log(logger.LevelDebug, "renaming the folder %q->%q is not supported: nested fs folders",
  980. fsSourcePath, fsTargetPath)
  981. return c.GetOpUnsupportedError()
  982. }
  983. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  984. c.Log(logger.LevelDebug, "renaming the folder %q is not supported: it has virtual folders inside it",
  985. virtualSourcePath)
  986. return c.GetOpUnsupportedError()
  987. }
  988. if err := c.checkRecursiveRenameDirPermissions(fsSrc, fsDst, fsSourcePath, fsTargetPath,
  989. virtualSourcePath, virtualTargetPath, fi); err != nil {
  990. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %q: %+v", fsSourcePath, err)
  991. return err
  992. }
  993. return nil
  994. }
  995. func (c *BaseConnection) isRenamePermitted(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath,
  996. virtualTargetPath string, fi os.FileInfo,
  997. ) bool {
  998. if !c.isSameResourceRename(virtualSourcePath, virtualTargetPath) {
  999. c.Log(logger.LevelInfo, "rename %#q->%q is not allowed: the paths must be on the same resource",
  1000. virtualSourcePath, virtualTargetPath)
  1001. return false
  1002. }
  1003. if c.User.IsMappedPath(fsSourcePath) && vfs.IsLocalOrCryptoFs(fsSrc) {
  1004. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  1005. return false
  1006. }
  1007. if c.User.IsMappedPath(fsTargetPath) && vfs.IsLocalOrCryptoFs(fsDst) {
  1008. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  1009. return false
  1010. }
  1011. if virtualSourcePath == "/" || virtualTargetPath == "/" || fsSrc.GetRelativePath(fsSourcePath) == "/" {
  1012. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  1013. return false
  1014. }
  1015. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  1016. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  1017. return false
  1018. }
  1019. isSrcAllowed, _ := c.User.IsFileAllowed(virtualSourcePath)
  1020. isDstAllowed, _ := c.User.IsFileAllowed(virtualTargetPath)
  1021. if !isSrcAllowed || !isDstAllowed {
  1022. c.Log(logger.LevelDebug, "renaming source: %#v to target: %#v not allowed", virtualSourcePath,
  1023. virtualTargetPath)
  1024. return false
  1025. }
  1026. return c.hasRenamePerms(virtualSourcePath, virtualTargetPath, fi)
  1027. }
  1028. func (c *BaseConnection) hasSpaceForRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath string, initialSize int64,
  1029. fsSourcePath string) bool {
  1030. if dataprovider.GetQuotaTracking() == 0 {
  1031. return true
  1032. }
  1033. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1034. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1035. if errSrc != nil && errDst != nil {
  1036. // rename inside the user home dir
  1037. return true
  1038. }
  1039. if errSrc == nil && errDst == nil {
  1040. // rename between virtual folders
  1041. if sourceFolder.Name == dstFolder.Name {
  1042. // rename inside the same virtual folder
  1043. return true
  1044. }
  1045. }
  1046. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  1047. // rename between user root dir and a virtual folder included in user quota
  1048. return true
  1049. }
  1050. quotaResult, _ := c.HasSpace(true, false, virtualTargetPath)
  1051. return c.hasSpaceForCrossRename(fs, quotaResult, initialSize, fsSourcePath)
  1052. }
  1053. // hasSpaceForCrossRename checks the quota after a rename between different folders
  1054. func (c *BaseConnection) hasSpaceForCrossRename(fs vfs.Fs, quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  1055. if !quotaResult.HasSpace && initialSize == -1 {
  1056. // we are over quota and this is not a file replace
  1057. return false
  1058. }
  1059. fi, err := fs.Lstat(sourcePath)
  1060. if err != nil {
  1061. c.Log(logger.LevelError, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  1062. return false
  1063. }
  1064. var sizeDiff int64
  1065. var filesDiff int
  1066. if fi.Mode().IsRegular() {
  1067. sizeDiff = fi.Size()
  1068. filesDiff = 1
  1069. if initialSize != -1 {
  1070. sizeDiff -= initialSize
  1071. filesDiff = 0
  1072. }
  1073. } else if fi.IsDir() {
  1074. filesDiff, sizeDiff, err = fs.GetDirSize(sourcePath)
  1075. if err != nil {
  1076. c.Log(logger.LevelError, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  1077. return false
  1078. }
  1079. }
  1080. if !quotaResult.HasSpace && initialSize != -1 {
  1081. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  1082. if quotaResult.QuotaSize == 0 {
  1083. return true
  1084. }
  1085. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  1086. sourcePath, quotaResult.UsedSize, sizeDiff)
  1087. quotaResult.UsedSize += sizeDiff
  1088. return quotaResult.GetRemainingSize() >= 0
  1089. }
  1090. if quotaResult.QuotaFiles > 0 {
  1091. remainingFiles := quotaResult.GetRemainingFiles()
  1092. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  1093. remainingFiles, filesDiff)
  1094. if remainingFiles < filesDiff {
  1095. return false
  1096. }
  1097. }
  1098. if quotaResult.QuotaSize > 0 {
  1099. remainingSize := quotaResult.GetRemainingSize()
  1100. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  1101. remainingSize, sizeDiff)
  1102. if remainingSize < sizeDiff {
  1103. return false
  1104. }
  1105. }
  1106. return true
  1107. }
  1108. // GetMaxWriteSize returns the allowed size for an upload or an error
  1109. // if no enough size is available for a resume/append
  1110. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64,
  1111. isUploadResumeSupported bool,
  1112. ) (int64, error) {
  1113. maxWriteSize := quotaResult.GetRemainingSize()
  1114. if isResume {
  1115. if !isUploadResumeSupported {
  1116. return 0, c.GetOpUnsupportedError()
  1117. }
  1118. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  1119. return 0, c.GetQuotaExceededError()
  1120. }
  1121. if c.User.Filters.MaxUploadFileSize > 0 {
  1122. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  1123. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  1124. maxWriteSize = maxUploadSize
  1125. }
  1126. }
  1127. } else {
  1128. if maxWriteSize > 0 {
  1129. maxWriteSize += fileSize
  1130. }
  1131. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  1132. maxWriteSize = c.User.Filters.MaxUploadFileSize
  1133. }
  1134. }
  1135. return maxWriteSize, nil
  1136. }
  1137. // GetTransferQuota returns the data transfers quota
  1138. func (c *BaseConnection) GetTransferQuota() dataprovider.TransferQuota {
  1139. result, _, _ := c.checkUserQuota()
  1140. return result
  1141. }
  1142. func (c *BaseConnection) checkUserQuota() (dataprovider.TransferQuota, int, int64) {
  1143. clientIP := c.GetRemoteIP()
  1144. ul, dl, total := c.User.GetDataTransferLimits(clientIP)
  1145. result := dataprovider.TransferQuota{
  1146. ULSize: ul,
  1147. DLSize: dl,
  1148. TotalSize: total,
  1149. AllowedULSize: 0,
  1150. AllowedDLSize: 0,
  1151. AllowedTotalSize: 0,
  1152. }
  1153. if !c.User.HasTransferQuotaRestrictions() {
  1154. return result, -1, -1
  1155. }
  1156. usedFiles, usedSize, usedULSize, usedDLSize, err := dataprovider.GetUsedQuota(c.User.Username)
  1157. if err != nil {
  1158. c.Log(logger.LevelError, "error getting used quota for %#v: %v", c.User.Username, err)
  1159. result.AllowedTotalSize = -1
  1160. return result, -1, -1
  1161. }
  1162. if result.TotalSize > 0 {
  1163. result.AllowedTotalSize = result.TotalSize - (usedULSize + usedDLSize)
  1164. }
  1165. if result.ULSize > 0 {
  1166. result.AllowedULSize = result.ULSize - usedULSize
  1167. }
  1168. if result.DLSize > 0 {
  1169. result.AllowedDLSize = result.DLSize - usedDLSize
  1170. }
  1171. return result, usedFiles, usedSize
  1172. }
  1173. // HasSpace checks user's quota usage
  1174. func (c *BaseConnection) HasSpace(checkFiles, getUsage bool, requestPath string) (vfs.QuotaCheckResult,
  1175. dataprovider.TransferQuota,
  1176. ) {
  1177. result := vfs.QuotaCheckResult{
  1178. HasSpace: true,
  1179. AllowedSize: 0,
  1180. AllowedFiles: 0,
  1181. UsedSize: 0,
  1182. UsedFiles: 0,
  1183. QuotaSize: 0,
  1184. QuotaFiles: 0,
  1185. }
  1186. if dataprovider.GetQuotaTracking() == 0 {
  1187. return result, dataprovider.TransferQuota{}
  1188. }
  1189. transferQuota, usedFiles, usedSize := c.checkUserQuota()
  1190. var err error
  1191. var vfolder vfs.VirtualFolder
  1192. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  1193. if err == nil && !vfolder.IsIncludedInUserQuota() {
  1194. if vfolder.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  1195. return result, transferQuota
  1196. }
  1197. result.QuotaSize = vfolder.QuotaSize
  1198. result.QuotaFiles = vfolder.QuotaFiles
  1199. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.Name)
  1200. } else {
  1201. if c.User.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  1202. return result, transferQuota
  1203. }
  1204. result.QuotaSize = c.User.QuotaSize
  1205. result.QuotaFiles = c.User.QuotaFiles
  1206. if usedSize == -1 {
  1207. result.UsedFiles, result.UsedSize, _, _, err = dataprovider.GetUsedQuota(c.User.Username)
  1208. } else {
  1209. err = nil
  1210. result.UsedFiles = usedFiles
  1211. result.UsedSize = usedSize
  1212. }
  1213. }
  1214. if err != nil {
  1215. c.Log(logger.LevelError, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  1216. result.HasSpace = false
  1217. return result, transferQuota
  1218. }
  1219. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  1220. result.AllowedSize = result.QuotaSize - result.UsedSize
  1221. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  1222. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  1223. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  1224. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  1225. result.HasSpace = false
  1226. return result, transferQuota
  1227. }
  1228. return result, transferQuota
  1229. }
  1230. func (c *BaseConnection) isSameResourceRename(virtualSourcePath, virtualTargetPath string) bool {
  1231. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  1232. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  1233. if errSrc != nil && errDst != nil {
  1234. return true
  1235. }
  1236. if errSrc == nil && errDst == nil {
  1237. if sourceFolder.Name == dstFolder.Name {
  1238. return true
  1239. }
  1240. // we have different folders, check if they point to the same resource
  1241. return sourceFolder.FsConfig.IsSameResource(dstFolder.FsConfig)
  1242. }
  1243. if errSrc == nil {
  1244. return sourceFolder.FsConfig.IsSameResource(c.User.FsConfig)
  1245. }
  1246. return dstFolder.FsConfig.IsSameResource(c.User.FsConfig)
  1247. }
  1248. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  1249. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  1250. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  1251. if errSrc != nil && errDst != nil {
  1252. return false
  1253. }
  1254. if errSrc == nil && errDst == nil {
  1255. return sourceFolder.Name != dstFolder.Name
  1256. }
  1257. return true
  1258. }
  1259. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder *vfs.VirtualFolder, initialSize,
  1260. filesSize int64, numFiles int) {
  1261. if sourceFolder.Name == dstFolder.Name {
  1262. // both files are inside the same virtual folder
  1263. if initialSize != -1 {
  1264. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  1265. if dstFolder.IsIncludedInUserQuota() {
  1266. dataprovider.UpdateUserQuota(&c.User, -numFiles, -initialSize, false) //nolint:errcheck
  1267. }
  1268. }
  1269. return
  1270. }
  1271. // files are inside different virtual folders
  1272. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  1273. if sourceFolder.IsIncludedInUserQuota() {
  1274. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1275. }
  1276. if initialSize == -1 {
  1277. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  1278. if dstFolder.IsIncludedInUserQuota() {
  1279. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1280. }
  1281. } else {
  1282. // we cannot have a directory here, initialSize != -1 only for files
  1283. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  1284. if dstFolder.IsIncludedInUserQuota() {
  1285. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1286. }
  1287. }
  1288. }
  1289. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1290. // move between a virtual folder and the user home dir
  1291. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  1292. if sourceFolder.IsIncludedInUserQuota() {
  1293. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1294. }
  1295. if initialSize == -1 {
  1296. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1297. } else {
  1298. // we cannot have a directory here, initialSize != -1 only for files
  1299. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1300. }
  1301. }
  1302. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1303. // move between the user home dir and a virtual folder
  1304. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1305. if initialSize == -1 {
  1306. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  1307. if dstFolder.IsIncludedInUserQuota() {
  1308. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1309. }
  1310. } else {
  1311. // we cannot have a directory here, initialSize != -1 only for files
  1312. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  1313. if dstFolder.IsIncludedInUserQuota() {
  1314. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1315. }
  1316. }
  1317. }
  1318. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  1319. if dataprovider.GetQuotaTracking() == 0 {
  1320. return nil
  1321. }
  1322. // we don't allow to overwrite an existing directory so targetPath can be:
  1323. // - a new file, a symlink is as a new file here
  1324. // - a file overwriting an existing one
  1325. // - a new directory
  1326. // initialSize != -1 only when overwriting files
  1327. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1328. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1329. if errSrc != nil && errDst != nil {
  1330. // both files are contained inside the user home dir
  1331. if initialSize != -1 {
  1332. // we cannot have a directory here, we are overwriting an existing file
  1333. // we need to subtract the size of the overwritten file from the user quota
  1334. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  1335. }
  1336. return nil
  1337. }
  1338. filesSize := int64(0)
  1339. numFiles := 1
  1340. if fi, err := fs.Stat(targetPath); err == nil {
  1341. if fi.Mode().IsDir() {
  1342. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  1343. if err != nil {
  1344. c.Log(logger.LevelError, "failed to update quota after rename, error scanning moved folder %#v: %v",
  1345. targetPath, err)
  1346. return err
  1347. }
  1348. } else {
  1349. filesSize = fi.Size()
  1350. }
  1351. } else {
  1352. c.Log(logger.LevelError, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  1353. return err
  1354. }
  1355. if errSrc == nil && errDst == nil {
  1356. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  1357. }
  1358. if errSrc == nil && errDst != nil {
  1359. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  1360. }
  1361. if errSrc != nil && errDst == nil {
  1362. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  1363. }
  1364. return nil
  1365. }
  1366. // IsNotExistError returns true if the specified fs error is not exist for the connection protocol
  1367. func (c *BaseConnection) IsNotExistError(err error) bool {
  1368. switch c.protocol {
  1369. case ProtocolSFTP:
  1370. return errors.Is(err, sftp.ErrSSHFxNoSuchFile)
  1371. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1372. return errors.Is(err, os.ErrNotExist)
  1373. default:
  1374. return errors.Is(err, ErrNotExist)
  1375. }
  1376. }
  1377. // GetErrorForDeniedFile return permission denied or not exist error based on the specified policy
  1378. func (c *BaseConnection) GetErrorForDeniedFile(policy int) error {
  1379. switch policy {
  1380. case sdk.DenyPolicyHide:
  1381. return c.GetNotExistError()
  1382. default:
  1383. return c.GetPermissionDeniedError()
  1384. }
  1385. }
  1386. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  1387. func (c *BaseConnection) GetPermissionDeniedError() error {
  1388. switch c.protocol {
  1389. case ProtocolSFTP:
  1390. return sftp.ErrSSHFxPermissionDenied
  1391. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1392. return os.ErrPermission
  1393. default:
  1394. return ErrPermissionDenied
  1395. }
  1396. }
  1397. // GetNotExistError returns an appropriate not exist error for the connection protocol
  1398. func (c *BaseConnection) GetNotExistError() error {
  1399. switch c.protocol {
  1400. case ProtocolSFTP:
  1401. return sftp.ErrSSHFxNoSuchFile
  1402. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1403. return os.ErrNotExist
  1404. default:
  1405. return ErrNotExist
  1406. }
  1407. }
  1408. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  1409. func (c *BaseConnection) GetOpUnsupportedError() error {
  1410. switch c.protocol {
  1411. case ProtocolSFTP:
  1412. return sftp.ErrSSHFxOpUnsupported
  1413. default:
  1414. return ErrOpUnsupported
  1415. }
  1416. }
  1417. func getQuotaExceededError(protocol string) error {
  1418. switch protocol {
  1419. case ProtocolSFTP:
  1420. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrQuotaExceeded.Error())
  1421. case ProtocolFTP:
  1422. return ftpserver.ErrStorageExceeded
  1423. default:
  1424. return ErrQuotaExceeded
  1425. }
  1426. }
  1427. func getReadQuotaExceededError(protocol string) error {
  1428. switch protocol {
  1429. case ProtocolSFTP:
  1430. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrReadQuotaExceeded.Error())
  1431. default:
  1432. return ErrReadQuotaExceeded
  1433. }
  1434. }
  1435. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  1436. func (c *BaseConnection) GetQuotaExceededError() error {
  1437. return getQuotaExceededError(c.protocol)
  1438. }
  1439. // GetReadQuotaExceededError returns an appropriate read quota limit exceeded error for the connection protocol
  1440. func (c *BaseConnection) GetReadQuotaExceededError() error {
  1441. return getReadQuotaExceededError(c.protocol)
  1442. }
  1443. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  1444. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  1445. switch c.protocol {
  1446. case ProtocolSFTP:
  1447. if err == nil {
  1448. return false
  1449. }
  1450. if errors.Is(err, ErrQuotaExceeded) {
  1451. return true
  1452. }
  1453. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1454. case ProtocolFTP:
  1455. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1456. default:
  1457. return errors.Is(err, ErrQuotaExceeded)
  1458. }
  1459. }
  1460. // GetGenericError returns an appropriate generic error for the connection protocol
  1461. func (c *BaseConnection) GetGenericError(err error) error {
  1462. switch c.protocol {
  1463. case ProtocolSFTP:
  1464. if err == vfs.ErrStorageSizeUnavailable {
  1465. return fmt.Errorf("%w: %v", sftp.ErrSSHFxOpUnsupported, err.Error())
  1466. }
  1467. if err == ErrShuttingDown {
  1468. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, err.Error())
  1469. }
  1470. if err != nil {
  1471. if e, ok := err.(*os.PathError); ok {
  1472. c.Log(logger.LevelError, "generic path error: %+v", e)
  1473. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, e.Op, e.Err.Error())
  1474. }
  1475. c.Log(logger.LevelError, "generic error: %+v", err)
  1476. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrGenericFailure.Error())
  1477. }
  1478. return sftp.ErrSSHFxFailure
  1479. default:
  1480. if err == ErrPermissionDenied || err == ErrNotExist || err == ErrOpUnsupported ||
  1481. err == ErrQuotaExceeded || err == vfs.ErrStorageSizeUnavailable || err == ErrShuttingDown {
  1482. return err
  1483. }
  1484. c.Log(logger.LevelError, "generic error: %+v", err)
  1485. return ErrGenericFailure
  1486. }
  1487. }
  1488. // GetFsError converts a filesystem error to a protocol error
  1489. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1490. if fs.IsNotExist(err) {
  1491. return c.GetNotExistError()
  1492. } else if fs.IsPermission(err) {
  1493. return c.GetPermissionDeniedError()
  1494. } else if fs.IsNotSupported(err) {
  1495. return c.GetOpUnsupportedError()
  1496. } else if err != nil {
  1497. return c.GetGenericError(err)
  1498. }
  1499. return nil
  1500. }
  1501. func (c *BaseConnection) getNotificationStatus(err error) int {
  1502. if err == nil {
  1503. return 1
  1504. }
  1505. if c.IsQuotaExceededError(err) {
  1506. return 3
  1507. }
  1508. return 2
  1509. }
  1510. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1511. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1512. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1513. if err != nil {
  1514. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1515. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1516. // will not be listed
  1517. return nil, "", c.GetPermissionDeniedError()
  1518. }
  1519. return nil, "", c.GetGenericError(err)
  1520. }
  1521. if isShuttingDown.Load() {
  1522. return nil, "", c.GetFsError(fs, ErrShuttingDown)
  1523. }
  1524. fsPath, err := fs.ResolvePath(virtualPath)
  1525. if err != nil {
  1526. return nil, "", c.GetFsError(fs, err)
  1527. }
  1528. return fs, fsPath, nil
  1529. }