connection.go 57 KB

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