connection.go 53 KB

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