connection.go 60 KB

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