connection.go 61 KB

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