connection.go 64 KB

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