connection.go 52 KB

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