connection.go 52 KB

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