connection.go 57 KB

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