connection.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  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. conn: c,
  284. fs: fs,
  285. info: c.User.GetVirtualFoldersInfo(virtualPath),
  286. lister: lister,
  287. }, nil
  288. }
  289. // CheckParentDirs tries to create the specified directory and any missing parent dirs
  290. func (c *BaseConnection) CheckParentDirs(virtualPath string) error {
  291. fs, err := c.User.GetFilesystemForPath(virtualPath, c.GetID())
  292. if err != nil {
  293. return err
  294. }
  295. if fs.HasVirtualFolders() {
  296. return nil
  297. }
  298. if _, err := c.DoStat(virtualPath, 0, false); !c.IsNotExistError(err) {
  299. return err
  300. }
  301. dirs := util.GetDirsForVirtualPath(virtualPath)
  302. for idx := len(dirs) - 1; idx >= 0; idx-- {
  303. fs, err = c.User.GetFilesystemForPath(dirs[idx], c.GetID())
  304. if err != nil {
  305. return err
  306. }
  307. if fs.HasVirtualFolders() {
  308. continue
  309. }
  310. if err = c.createDirIfMissing(dirs[idx]); err != nil {
  311. return fmt.Errorf("unable to check/create missing parent dir %q for virtual path %q: %w",
  312. dirs[idx], virtualPath, err)
  313. }
  314. }
  315. return nil
  316. }
  317. // GetCreateChecks returns the checks for creating new files
  318. func (c *BaseConnection) GetCreateChecks(virtualPath string, isNewFile bool, isResume bool) int {
  319. result := 0
  320. if !isNewFile {
  321. if isResume {
  322. result += vfs.CheckResume
  323. }
  324. return result
  325. }
  326. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  327. result += vfs.CheckParentDir
  328. return result
  329. }
  330. return result
  331. }
  332. // CreateDir creates a new directory at the specified fsPath
  333. func (c *BaseConnection) CreateDir(virtualPath string, checkFilePatterns bool) error {
  334. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  335. return c.GetPermissionDeniedError()
  336. }
  337. if checkFilePatterns {
  338. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  339. return c.GetPermissionDeniedError()
  340. }
  341. }
  342. if c.User.IsVirtualFolder(virtualPath) {
  343. c.Log(logger.LevelWarn, "mkdir not allowed %q is a virtual folder", virtualPath)
  344. return c.GetPermissionDeniedError()
  345. }
  346. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  347. if err != nil {
  348. return err
  349. }
  350. startTime := time.Now()
  351. if err := fs.Mkdir(fsPath); err != nil {
  352. c.Log(logger.LevelError, "error creating dir: %q error: %+v", fsPath, err)
  353. return c.GetFsError(fs, err)
  354. }
  355. vfs.SetPathPermissions(fs, fsPath, c.User.GetUID(), c.User.GetGID())
  356. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  357. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  358. c.localAddr, c.remoteAddr, elapsed)
  359. ExecuteActionNotification(c, operationMkdir, fsPath, virtualPath, "", "", "", 0, nil, elapsed, nil) //nolint:errcheck
  360. return nil
  361. }
  362. // IsRemoveFileAllowed returns an error if removing this file is not allowed
  363. func (c *BaseConnection) IsRemoveFileAllowed(virtualPath string) error {
  364. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  365. return c.GetPermissionDeniedError()
  366. }
  367. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  368. c.Log(logger.LevelDebug, "removing file %q is not allowed", virtualPath)
  369. return c.GetErrorForDeniedFile(policy)
  370. }
  371. return nil
  372. }
  373. // RemoveFile removes a file at the specified fsPath
  374. func (c *BaseConnection) RemoveFile(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  375. if err := c.IsRemoveFileAllowed(virtualPath); err != nil {
  376. return err
  377. }
  378. size := info.Size()
  379. status, err := ExecutePreAction(c, operationPreDelete, fsPath, virtualPath, size, 0)
  380. if err != nil {
  381. c.Log(logger.LevelDebug, "delete for file %q denied by pre action: %v", virtualPath, err)
  382. return c.GetPermissionDeniedError()
  383. }
  384. updateQuota := true
  385. startTime := time.Now()
  386. if err := fs.Remove(fsPath, false); err != nil {
  387. if status > 0 && fs.IsNotExist(err) {
  388. // file removed in the pre-action, if the file was deleted from the EventManager the quota is already updated
  389. c.Log(logger.LevelDebug, "file deleted from the hook, status: %d", status)
  390. updateQuota = (status == 1)
  391. } else {
  392. c.Log(logger.LevelError, "failed to remove file/symlink %q: %+v", fsPath, err)
  393. return c.GetFsError(fs, err)
  394. }
  395. }
  396. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  397. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  398. c.localAddr, c.remoteAddr, elapsed)
  399. if updateQuota && info.Mode()&os.ModeSymlink == 0 {
  400. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  401. if err == nil {
  402. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, -1, -size, false) //nolint:errcheck
  403. if vfolder.IsIncludedInUserQuota() {
  404. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  405. }
  406. } else {
  407. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  408. }
  409. }
  410. ExecuteActionNotification(c, operationDelete, fsPath, virtualPath, "", "", "", size, nil, elapsed, nil) //nolint:errcheck
  411. return nil
  412. }
  413. // IsRemoveDirAllowed returns an error if removing this directory is not allowed
  414. func (c *BaseConnection) IsRemoveDirAllowed(fs vfs.Fs, fsPath, virtualPath string) error {
  415. if virtualPath == "/" || fs.GetRelativePath(fsPath) == "/" {
  416. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  417. return c.GetPermissionDeniedError()
  418. }
  419. if c.User.IsVirtualFolder(virtualPath) {
  420. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %q", virtualPath)
  421. return fmt.Errorf("removing virtual folders is not allowed: %w", c.GetPermissionDeniedError())
  422. }
  423. if c.User.HasVirtualFoldersInside(virtualPath) {
  424. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %q", virtualPath)
  425. return fmt.Errorf("cannot remove directory %q with virtual folders inside: %w", virtualPath, c.GetOpUnsupportedError())
  426. }
  427. if c.User.IsMappedPath(fsPath) {
  428. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %q", fsPath)
  429. return fmt.Errorf("removing the directory %q mapped as virtual folder is not allowed: %w",
  430. virtualPath, c.GetPermissionDeniedError())
  431. }
  432. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  433. return c.GetPermissionDeniedError()
  434. }
  435. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  436. c.Log(logger.LevelDebug, "removing directory %q is not allowed", virtualPath)
  437. return c.GetErrorForDeniedFile(policy)
  438. }
  439. return nil
  440. }
  441. // RemoveDir removes a directory at the specified fsPath
  442. func (c *BaseConnection) RemoveDir(virtualPath string) error {
  443. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  444. if err != nil {
  445. return err
  446. }
  447. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  448. return err
  449. }
  450. var fi os.FileInfo
  451. if fi, err = fs.Lstat(fsPath); err != nil {
  452. // see #149
  453. if fs.IsNotExist(err) && fs.HasVirtualFolders() {
  454. return nil
  455. }
  456. c.Log(logger.LevelError, "failed to remove a dir %q: stat error: %+v", fsPath, err)
  457. return c.GetFsError(fs, err)
  458. }
  459. if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
  460. c.Log(logger.LevelError, "cannot remove %q is not a directory", fsPath)
  461. return c.GetGenericError(nil)
  462. }
  463. startTime := time.Now()
  464. if err := fs.Remove(fsPath, true); err != nil {
  465. c.Log(logger.LevelError, "failed to remove directory %q: %+v", fsPath, err)
  466. return c.GetFsError(fs, err)
  467. }
  468. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  469. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  470. c.localAddr, c.remoteAddr, elapsed)
  471. ExecuteActionNotification(c, operationRmdir, fsPath, virtualPath, "", "", "", 0, nil, elapsed, nil) //nolint:errcheck
  472. return nil
  473. }
  474. func (c *BaseConnection) doRecursiveRemoveDirEntry(virtualPath string, info os.FileInfo, recursion int) error {
  475. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  476. if err != nil {
  477. return err
  478. }
  479. return c.doRecursiveRemove(fs, fsPath, virtualPath, info, recursion)
  480. }
  481. func (c *BaseConnection) doRecursiveRemove(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo, recursion int) error {
  482. if info.IsDir() {
  483. if recursion >= util.MaxRecursion {
  484. c.Log(logger.LevelError, "recursive rename failed, recursion too depth: %d", recursion)
  485. return util.ErrRecursionTooDeep
  486. }
  487. recursion++
  488. lister, err := c.ListDir(virtualPath)
  489. if err != nil {
  490. return fmt.Errorf("unable to get lister for dir %q: %w", virtualPath, err)
  491. }
  492. defer lister.Close()
  493. for {
  494. entries, err := lister.Next(vfs.ListerBatchSize)
  495. finished := errors.Is(err, io.EOF)
  496. if err != nil && !finished {
  497. return fmt.Errorf("unable to get content for dir %q: %w", virtualPath, err)
  498. }
  499. for _, fi := range entries {
  500. targetPath := path.Join(virtualPath, fi.Name())
  501. if err := c.doRecursiveRemoveDirEntry(targetPath, fi, recursion); err != nil {
  502. return err
  503. }
  504. }
  505. if finished {
  506. lister.Close()
  507. break
  508. }
  509. }
  510. return c.RemoveDir(virtualPath)
  511. }
  512. return c.RemoveFile(fs, fsPath, virtualPath, info)
  513. }
  514. // RemoveAll removes the specified path and any children it contains
  515. func (c *BaseConnection) RemoveAll(virtualPath string) error {
  516. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  517. if err != nil {
  518. return err
  519. }
  520. fi, err := fs.Lstat(fsPath)
  521. if err != nil {
  522. c.Log(logger.LevelDebug, "failed to remove path %q: stat error: %+v", fsPath, err)
  523. return c.GetFsError(fs, err)
  524. }
  525. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  526. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  527. return err
  528. }
  529. return c.doRecursiveRemove(fs, fsPath, virtualPath, fi, 0)
  530. }
  531. return c.RemoveFile(fs, fsPath, virtualPath, fi)
  532. }
  533. func (c *BaseConnection) checkCopy(srcInfo, dstInfo os.FileInfo, virtualSource, virtualTarget string) error {
  534. _, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSource)
  535. if err != nil {
  536. return err
  537. }
  538. _, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTarget)
  539. if err != nil {
  540. return err
  541. }
  542. if srcInfo.IsDir() {
  543. if dstInfo != nil && !dstInfo.IsDir() {
  544. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualTarget, virtualSource, c.GetOpUnsupportedError())
  545. }
  546. if util.IsDirOverlapped(virtualSource, virtualTarget, true, "/") {
  547. return fmt.Errorf("nested copy %q => %q is not supported: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  548. }
  549. if util.IsDirOverlapped(fsSourcePath, fsTargetPath, true, c.User.FsConfig.GetPathSeparator()) {
  550. c.Log(logger.LevelWarn, "nested fs copy %q => %q not allowed", fsSourcePath, fsTargetPath)
  551. return fmt.Errorf("nested fs copy is not supported: %w", c.GetOpUnsupportedError())
  552. }
  553. return nil
  554. }
  555. if dstInfo != nil && dstInfo.IsDir() {
  556. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  557. }
  558. if fsSourcePath == fsTargetPath {
  559. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  560. }
  561. return nil
  562. }
  563. func (c *BaseConnection) copyFile(virtualSourcePath, virtualTargetPath string, srcSize int64) error {
  564. if !c.User.HasPerm(dataprovider.PermCopy, virtualSourcePath) || !c.User.HasPerm(dataprovider.PermCopy, virtualTargetPath) {
  565. return c.GetPermissionDeniedError()
  566. }
  567. if ok, _ := c.User.IsFileAllowed(virtualTargetPath); !ok {
  568. return fmt.Errorf("file %q is not allowed: %w", virtualTargetPath, c.GetPermissionDeniedError())
  569. }
  570. if c.IsSameResource(virtualSourcePath, virtualTargetPath) {
  571. fs, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  572. if err != nil {
  573. return err
  574. }
  575. if copier, ok := fs.(vfs.FsFileCopier); ok {
  576. _, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  577. if err != nil {
  578. return err
  579. }
  580. startTime := time.Now()
  581. numFiles, sizeDiff, err := copier.CopyFile(fsSourcePath, fsTargetPath, srcSize)
  582. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  583. updateUserQuotaAfterFileWrite(c, virtualTargetPath, numFiles, sizeDiff)
  584. logger.CommandLog(copyLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  585. "", "", "", srcSize, c.localAddr, c.remoteAddr, elapsed)
  586. ExecuteActionNotification(c, operationCopy, fsSourcePath, virtualSourcePath, fsTargetPath, virtualTargetPath, "", srcSize, err, elapsed, nil) //nolint:errcheck
  587. return err
  588. }
  589. }
  590. reader, rCancelFn, err := getFileReader(c, virtualSourcePath)
  591. if err != nil {
  592. return fmt.Errorf("unable to get reader for path %q: %w", virtualSourcePath, err)
  593. }
  594. defer rCancelFn()
  595. defer reader.Close()
  596. writer, numFiles, truncatedSize, wCancelFn, err := getFileWriter(c, virtualTargetPath, srcSize)
  597. if err != nil {
  598. return fmt.Errorf("unable to get writer for path %q: %w", virtualTargetPath, err)
  599. }
  600. defer wCancelFn()
  601. startTime := time.Now()
  602. _, err = io.Copy(writer, reader)
  603. return closeWriterAndUpdateQuota(writer, c, virtualSourcePath, virtualTargetPath, numFiles, truncatedSize,
  604. err, operationCopy, startTime)
  605. }
  606. func (c *BaseConnection) doRecursiveCopy(virtualSourcePath, virtualTargetPath string, srcInfo os.FileInfo,
  607. createTargetDir bool, recursion int,
  608. ) error {
  609. if srcInfo.IsDir() {
  610. if recursion >= util.MaxRecursion {
  611. c.Log(logger.LevelError, "recursive copy failed, recursion too depth: %d", recursion)
  612. return util.ErrRecursionTooDeep
  613. }
  614. recursion++
  615. if createTargetDir {
  616. if err := c.CreateDir(virtualTargetPath, false); err != nil {
  617. return fmt.Errorf("unable to create directory %q: %w", virtualTargetPath, err)
  618. }
  619. }
  620. lister, err := c.ListDir(virtualSourcePath)
  621. if err != nil {
  622. return fmt.Errorf("unable to get lister for dir %q: %w", virtualSourcePath, err)
  623. }
  624. defer lister.Close()
  625. for {
  626. entries, err := lister.Next(vfs.ListerBatchSize)
  627. finished := errors.Is(err, io.EOF)
  628. if err != nil && !finished {
  629. return fmt.Errorf("unable to get contents for dir %q: %w", virtualSourcePath, err)
  630. }
  631. if err := c.recursiveCopyEntries(virtualSourcePath, virtualTargetPath, entries, recursion); err != nil {
  632. return err
  633. }
  634. if finished {
  635. return nil
  636. }
  637. }
  638. }
  639. if !srcInfo.Mode().IsRegular() {
  640. c.Log(logger.LevelInfo, "skipping copy for non regular file %q", virtualSourcePath)
  641. return nil
  642. }
  643. return c.copyFile(virtualSourcePath, virtualTargetPath, srcInfo.Size())
  644. }
  645. func (c *BaseConnection) recursiveCopyEntries(virtualSourcePath, virtualTargetPath string, entries []os.FileInfo, recursion int) error {
  646. for _, info := range entries {
  647. sourcePath := path.Join(virtualSourcePath, info.Name())
  648. targetPath := path.Join(virtualTargetPath, info.Name())
  649. targetInfo, err := c.DoStat(targetPath, 1, false)
  650. if err == nil {
  651. if info.IsDir() && targetInfo.IsDir() {
  652. c.Log(logger.LevelDebug, "target copy dir %q already exists", targetPath)
  653. continue
  654. }
  655. }
  656. if err != nil && !c.IsNotExistError(err) {
  657. return err
  658. }
  659. if err := c.checkCopy(info, targetInfo, sourcePath, targetPath); err != nil {
  660. return err
  661. }
  662. if err := c.doRecursiveCopy(sourcePath, targetPath, info, true, recursion); err != nil {
  663. if c.IsNotExistError(err) {
  664. c.Log(logger.LevelInfo, "skipping copy for source path %q: %v", sourcePath, err)
  665. continue
  666. }
  667. return err
  668. }
  669. }
  670. return nil
  671. }
  672. // Copy virtualSourcePath to virtualTargetPath
  673. func (c *BaseConnection) Copy(virtualSourcePath, virtualTargetPath string) error {
  674. copyFromSource := strings.HasSuffix(virtualSourcePath, "/")
  675. copyInTarget := strings.HasSuffix(virtualTargetPath, "/")
  676. virtualSourcePath = path.Clean(virtualSourcePath)
  677. virtualTargetPath = path.Clean(virtualTargetPath)
  678. if virtualSourcePath == virtualTargetPath {
  679. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  680. }
  681. srcInfo, err := c.DoStat(virtualSourcePath, 1, false)
  682. if err != nil {
  683. return err
  684. }
  685. if srcInfo.Mode()&os.ModeSymlink != 0 {
  686. return fmt.Errorf("copying symlinks is not supported: %w", c.GetOpUnsupportedError())
  687. }
  688. dstInfo, err := c.DoStat(virtualTargetPath, 1, false)
  689. if err == nil && !copyFromSource {
  690. copyInTarget = dstInfo.IsDir()
  691. }
  692. if err != nil && !c.IsNotExistError(err) {
  693. return err
  694. }
  695. destPath := virtualTargetPath
  696. if copyInTarget {
  697. destPath = path.Join(virtualTargetPath, path.Base(virtualSourcePath))
  698. dstInfo, err = c.DoStat(destPath, 1, false)
  699. if err != nil && !c.IsNotExistError(err) {
  700. return err
  701. }
  702. }
  703. createTargetDir := true
  704. if dstInfo != nil && dstInfo.IsDir() {
  705. createTargetDir = false
  706. }
  707. if err := c.checkCopy(srcInfo, dstInfo, virtualSourcePath, destPath); err != nil {
  708. return err
  709. }
  710. if err := c.CheckParentDirs(path.Dir(destPath)); err != nil {
  711. return err
  712. }
  713. done := make(chan bool)
  714. defer close(done)
  715. go keepConnectionAlive(c, done, 2*time.Minute)
  716. return c.doRecursiveCopy(virtualSourcePath, destPath, srcInfo, createTargetDir, 0)
  717. }
  718. // Rename renames (moves) virtualSourcePath to virtualTargetPath
  719. func (c *BaseConnection) Rename(virtualSourcePath, virtualTargetPath string) error {
  720. return c.renameInternal(virtualSourcePath, virtualTargetPath, false)
  721. }
  722. func (c *BaseConnection) renameInternal(virtualSourcePath, virtualTargetPath string, checkParentDestination bool) error { //nolint:gocyclo
  723. if virtualSourcePath == virtualTargetPath {
  724. return fmt.Errorf("the rename source and target cannot be the same: %w", c.GetOpUnsupportedError())
  725. }
  726. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  727. if err != nil {
  728. return err
  729. }
  730. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  731. if err != nil {
  732. return err
  733. }
  734. startTime := time.Now()
  735. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  736. if err != nil {
  737. return c.GetFsError(fsSrc, err)
  738. }
  739. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  740. return c.GetPermissionDeniedError()
  741. }
  742. initialSize := int64(-1)
  743. dstInfo, err := fsDst.Lstat(fsTargetPath)
  744. if err != nil && !fsDst.IsNotExist(err) {
  745. return err
  746. }
  747. if err == nil {
  748. checkParentDestination = false
  749. if dstInfo.IsDir() {
  750. c.Log(logger.LevelWarn, "attempted to rename %q overwriting an existing directory %q",
  751. fsSourcePath, fsTargetPath)
  752. return c.GetOpUnsupportedError()
  753. }
  754. // we are overwriting an existing file/symlink
  755. if dstInfo.Mode().IsRegular() {
  756. initialSize = dstInfo.Size()
  757. }
  758. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  759. c.Log(logger.LevelDebug, "renaming %q -> %q is not allowed. Target exists but the user %q"+
  760. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  761. return c.GetPermissionDeniedError()
  762. }
  763. }
  764. if srcInfo.IsDir() {
  765. if err := c.checkFolderRename(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo); err != nil {
  766. return err
  767. }
  768. }
  769. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  770. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  771. return c.GetGenericError(ErrQuotaExceeded)
  772. }
  773. if checkParentDestination {
  774. c.CheckParentDirs(path.Dir(virtualTargetPath)) //nolint:errcheck
  775. }
  776. done := make(chan bool)
  777. defer close(done)
  778. go keepConnectionAlive(c, done, 2*time.Minute)
  779. files, size, err := fsDst.Rename(fsSourcePath, fsTargetPath)
  780. if err != nil {
  781. c.Log(logger.LevelError, "failed to rename %q -> %q: %+v", fsSourcePath, fsTargetPath, err)
  782. return c.GetFsError(fsSrc, err)
  783. }
  784. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  785. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  786. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize, files, size) //nolint:errcheck
  787. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  788. "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  789. ExecuteActionNotification(c, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, //nolint:errcheck
  790. virtualTargetPath, "", 0, nil, elapsed, nil)
  791. return nil
  792. }
  793. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  794. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  795. var relativePath string
  796. if !path.IsAbs(virtualSourcePath) {
  797. relativePath = virtualSourcePath
  798. virtualSourcePath = path.Join(path.Dir(virtualTargetPath), relativePath)
  799. c.Log(logger.LevelDebug, "link relative path %q resolved as %q, target path %q",
  800. relativePath, virtualSourcePath, virtualTargetPath)
  801. }
  802. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  803. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  804. return c.GetOpUnsupportedError()
  805. }
  806. // we cannot have a cross folder request here so only one fs is enough
  807. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  808. if err != nil {
  809. return err
  810. }
  811. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  812. if err != nil {
  813. return c.GetFsError(fs, err)
  814. }
  815. if fs.GetRelativePath(fsSourcePath) == "/" {
  816. c.Log(logger.LevelError, "symlinking root dir is not allowed")
  817. return c.GetPermissionDeniedError()
  818. }
  819. if fs.GetRelativePath(fsTargetPath) == "/" {
  820. c.Log(logger.LevelError, "symlinking to root dir is not allowed")
  821. return c.GetPermissionDeniedError()
  822. }
  823. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  824. return c.GetPermissionDeniedError()
  825. }
  826. ok, policy := c.User.IsFileAllowed(virtualSourcePath)
  827. if !ok && policy == sdk.DenyPolicyHide {
  828. c.Log(logger.LevelError, "symlink source path %q is not allowed", virtualSourcePath)
  829. return c.GetNotExistError()
  830. }
  831. if ok, _ = c.User.IsFileAllowed(virtualTargetPath); !ok {
  832. c.Log(logger.LevelError, "symlink target path %q is not allowed", virtualTargetPath)
  833. return c.GetPermissionDeniedError()
  834. }
  835. if relativePath != "" {
  836. fsSourcePath = relativePath
  837. }
  838. startTime := time.Now()
  839. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  840. c.Log(logger.LevelError, "failed to create symlink %q -> %q: %+v", fsSourcePath, fsTargetPath, err)
  841. return c.GetFsError(fs, err)
  842. }
  843. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  844. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  845. "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  846. return nil
  847. }
  848. func (c *BaseConnection) doStatInternal(virtualPath string, mode int, checkFilePatterns,
  849. convertResult bool,
  850. ) (os.FileInfo, error) {
  851. // for some vfs we don't create intermediary folders so we cannot simply check
  852. // if virtualPath is a virtual folder. Allowing stat for hidden virtual folders
  853. // is by purpose.
  854. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  855. if _, ok := vfolders[virtualPath]; ok {
  856. return vfs.NewFileInfo(virtualPath, true, 0, time.Unix(0, 0), false), nil
  857. }
  858. if checkFilePatterns && virtualPath != "/" {
  859. ok, policy := c.User.IsFileAllowed(virtualPath)
  860. if !ok && policy == sdk.DenyPolicyHide {
  861. return nil, c.GetNotExistError()
  862. }
  863. }
  864. var info os.FileInfo
  865. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  866. if err != nil {
  867. return nil, err
  868. }
  869. if mode == 1 {
  870. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  871. } else {
  872. info, err = fs.Stat(c.getRealFsPath(fsPath))
  873. }
  874. if err != nil {
  875. if !fs.IsNotExist(err) {
  876. c.Log(logger.LevelWarn, "stat error for path %q: %+v", virtualPath, err)
  877. }
  878. return nil, c.GetFsError(fs, err)
  879. }
  880. if convertResult && vfs.IsCryptOsFs(fs) {
  881. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  882. }
  883. return info, nil
  884. }
  885. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  886. func (c *BaseConnection) DoStat(virtualPath string, mode int, checkFilePatterns bool) (os.FileInfo, error) {
  887. return c.doStatInternal(virtualPath, mode, checkFilePatterns, true)
  888. }
  889. func (c *BaseConnection) createDirIfMissing(name string) error {
  890. _, err := c.DoStat(name, 0, false)
  891. if c.IsNotExistError(err) {
  892. return c.CreateDir(name, false)
  893. }
  894. return err
  895. }
  896. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  897. if Config.SetstatMode == 1 {
  898. return true
  899. }
  900. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  901. return true
  902. }
  903. return false
  904. }
  905. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  906. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  907. return c.GetPermissionDeniedError()
  908. }
  909. if c.ignoreSetStat(fs) {
  910. return nil
  911. }
  912. startTime := time.Now()
  913. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  914. c.Log(logger.LevelError, "failed to chmod path %q, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  915. return c.GetFsError(fs, err)
  916. }
  917. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  918. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  919. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  920. return nil
  921. }
  922. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  923. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  924. return c.GetPermissionDeniedError()
  925. }
  926. if c.ignoreSetStat(fs) {
  927. return nil
  928. }
  929. startTime := time.Now()
  930. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  931. c.Log(logger.LevelError, "failed to chown path %q, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  932. attributes.GID, err)
  933. return c.GetFsError(fs, err)
  934. }
  935. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  936. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  937. "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  938. return nil
  939. }
  940. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  941. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  942. return c.GetPermissionDeniedError()
  943. }
  944. if Config.SetstatMode == 1 {
  945. return nil
  946. }
  947. startTime := time.Now()
  948. isUploading := c.setTimes(fsPath, attributes.Atime, attributes.Mtime)
  949. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime, isUploading); err != nil {
  950. c.setTimes(fsPath, time.Time{}, time.Time{})
  951. if errors.Is(err, vfs.ErrVfsUnsupported) && Config.SetstatMode == 2 {
  952. return nil
  953. }
  954. c.Log(logger.LevelError, "failed to chtimes for path %q, access time: %v, modification time: %v, err: %+v",
  955. fsPath, attributes.Atime, attributes.Mtime, err)
  956. return c.GetFsError(fs, err)
  957. }
  958. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  959. accessTimeString := attributes.Atime.Format(chtimesFormat)
  960. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  961. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  962. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr, elapsed)
  963. return nil
  964. }
  965. // SetStat set StatAttributes for the specified fsPath
  966. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  967. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  968. return c.GetErrorForDeniedFile(policy)
  969. }
  970. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  971. if err != nil {
  972. return err
  973. }
  974. pathForPerms := path.Dir(virtualPath)
  975. if attributes.Flags&StatAttrTimes != 0 {
  976. if err = c.handleChtimes(fs, fsPath, pathForPerms, attributes); err != nil {
  977. return err
  978. }
  979. }
  980. if attributes.Flags&StatAttrPerms != 0 {
  981. if err = c.handleChmod(fs, fsPath, pathForPerms, attributes); err != nil {
  982. return err
  983. }
  984. }
  985. if attributes.Flags&StatAttrUIDGID != 0 {
  986. if err = c.handleChown(fs, fsPath, pathForPerms, attributes); err != nil {
  987. return err
  988. }
  989. }
  990. if attributes.Flags&StatAttrSize != 0 {
  991. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  992. return c.GetPermissionDeniedError()
  993. }
  994. startTime := time.Now()
  995. if err = c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  996. c.Log(logger.LevelError, "failed to truncate path %q, size: %v, err: %+v", fsPath, attributes.Size, err)
  997. return c.GetFsError(fs, err)
  998. }
  999. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  1000. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  1001. "", attributes.Size, c.localAddr, c.remoteAddr, elapsed)
  1002. }
  1003. return nil
  1004. }
  1005. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  1006. // check first if we have an open transfer for the given path and try to truncate the file already opened
  1007. // if we found no transfer we truncate by path.
  1008. var initialSize int64
  1009. var err error
  1010. initialSize, err = c.truncateOpenHandle(fsPath, size)
  1011. if err == errNoTransfer {
  1012. c.Log(logger.LevelDebug, "file path %q not found in active transfers, execute trucate by path", fsPath)
  1013. var info os.FileInfo
  1014. info, err = fs.Stat(fsPath)
  1015. if err != nil {
  1016. return err
  1017. }
  1018. initialSize = info.Size()
  1019. err = fs.Truncate(fsPath, size)
  1020. }
  1021. if err == nil && vfs.HasTruncateSupport(fs) {
  1022. sizeDiff := initialSize - size
  1023. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  1024. if err == nil {
  1025. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  1026. if vfolder.IsIncludedInUserQuota() {
  1027. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  1028. }
  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.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  1405. if dstFolder.IsIncludedInUserQuota() {
  1406. dataprovider.UpdateUserQuota(&c.User, -numFiles, -initialSize, false) //nolint:errcheck
  1407. }
  1408. }
  1409. return
  1410. }
  1411. // files are inside different virtual folders
  1412. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  1413. if sourceFolder.IsIncludedInUserQuota() {
  1414. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1415. }
  1416. if initialSize == -1 {
  1417. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  1418. if dstFolder.IsIncludedInUserQuota() {
  1419. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1420. }
  1421. } else {
  1422. // we cannot have a directory here, initialSize != -1 only for files
  1423. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  1424. if dstFolder.IsIncludedInUserQuota() {
  1425. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1426. }
  1427. }
  1428. }
  1429. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1430. // move between a virtual folder and the user home dir
  1431. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  1432. if sourceFolder.IsIncludedInUserQuota() {
  1433. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1434. }
  1435. if initialSize == -1 {
  1436. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1437. } else {
  1438. // we cannot have a directory here, initialSize != -1 only for files
  1439. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1440. }
  1441. }
  1442. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1443. // move between the user home dir and a virtual folder
  1444. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1445. if initialSize == -1 {
  1446. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  1447. if dstFolder.IsIncludedInUserQuota() {
  1448. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1449. }
  1450. } else {
  1451. // we cannot have a directory here, initialSize != -1 only for files
  1452. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  1453. if dstFolder.IsIncludedInUserQuota() {
  1454. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1455. }
  1456. }
  1457. }
  1458. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string,
  1459. initialSize int64, numFiles int, filesSize int64,
  1460. ) error {
  1461. if dataprovider.GetQuotaTracking() == 0 {
  1462. return nil
  1463. }
  1464. // we don't allow to overwrite an existing directory so targetPath can be:
  1465. // - a new file, a symlink is as a new file here
  1466. // - a file overwriting an existing one
  1467. // - a new directory
  1468. // initialSize != -1 only when overwriting files
  1469. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1470. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1471. if errSrc != nil && errDst != nil {
  1472. // both files are contained inside the user home dir
  1473. if initialSize != -1 {
  1474. // we cannot have a directory here, we are overwriting an existing file
  1475. // we need to subtract the size of the overwritten file from the user quota
  1476. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  1477. }
  1478. return nil
  1479. }
  1480. if filesSize == -1 {
  1481. // fs.Rename didn't return the affected files/sizes, we need to calculate them
  1482. numFiles = 1
  1483. if fi, err := fs.Stat(targetPath); err == nil {
  1484. if fi.Mode().IsDir() {
  1485. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  1486. if err != nil {
  1487. c.Log(logger.LevelError, "failed to update quota after rename, error scanning moved folder %q: %+v",
  1488. targetPath, err)
  1489. return err
  1490. }
  1491. } else {
  1492. filesSize = fi.Size()
  1493. }
  1494. } else {
  1495. c.Log(logger.LevelError, "failed to update quota after renaming, file %q stat error: %+v", targetPath, err)
  1496. return err
  1497. }
  1498. c.Log(logger.LevelDebug, "calculated renamed files: %d, size: %d bytes", numFiles, filesSize)
  1499. } else {
  1500. c.Log(logger.LevelDebug, "returned renamed files: %d, size: %d bytes", numFiles, filesSize)
  1501. }
  1502. if errSrc == nil && errDst == nil {
  1503. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  1504. }
  1505. if errSrc == nil && errDst != nil {
  1506. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  1507. }
  1508. if errSrc != nil && errDst == nil {
  1509. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  1510. }
  1511. return nil
  1512. }
  1513. // IsNotExistError returns true if the specified fs error is not exist for the connection protocol
  1514. func (c *BaseConnection) IsNotExistError(err error) bool {
  1515. switch c.protocol {
  1516. case ProtocolSFTP:
  1517. return errors.Is(err, sftp.ErrSSHFxNoSuchFile)
  1518. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1519. return errors.Is(err, os.ErrNotExist)
  1520. default:
  1521. return errors.Is(err, ErrNotExist)
  1522. }
  1523. }
  1524. // GetErrorForDeniedFile return permission denied or not exist error based on the specified policy
  1525. func (c *BaseConnection) GetErrorForDeniedFile(policy int) error {
  1526. switch policy {
  1527. case sdk.DenyPolicyHide:
  1528. return c.GetNotExistError()
  1529. default:
  1530. return c.GetPermissionDeniedError()
  1531. }
  1532. }
  1533. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  1534. func (c *BaseConnection) GetPermissionDeniedError() error {
  1535. return getPermissionDeniedError(c.protocol)
  1536. }
  1537. // GetNotExistError returns an appropriate not exist error for the connection protocol
  1538. func (c *BaseConnection) GetNotExistError() error {
  1539. switch c.protocol {
  1540. case ProtocolSFTP:
  1541. return sftp.ErrSSHFxNoSuchFile
  1542. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1543. return os.ErrNotExist
  1544. default:
  1545. return ErrNotExist
  1546. }
  1547. }
  1548. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  1549. func (c *BaseConnection) GetOpUnsupportedError() error {
  1550. switch c.protocol {
  1551. case ProtocolSFTP:
  1552. return sftp.ErrSSHFxOpUnsupported
  1553. default:
  1554. return ErrOpUnsupported
  1555. }
  1556. }
  1557. func getQuotaExceededError(protocol string) error {
  1558. switch protocol {
  1559. case ProtocolSFTP:
  1560. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, ErrQuotaExceeded)
  1561. case ProtocolFTP:
  1562. return ftpserver.ErrStorageExceeded
  1563. default:
  1564. return ErrQuotaExceeded
  1565. }
  1566. }
  1567. func getReadQuotaExceededError(protocol string) error {
  1568. switch protocol {
  1569. case ProtocolSFTP:
  1570. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, ErrReadQuotaExceeded)
  1571. default:
  1572. return ErrReadQuotaExceeded
  1573. }
  1574. }
  1575. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  1576. func (c *BaseConnection) GetQuotaExceededError() error {
  1577. return getQuotaExceededError(c.protocol)
  1578. }
  1579. // GetReadQuotaExceededError returns an appropriate read quota limit exceeded error for the connection protocol
  1580. func (c *BaseConnection) GetReadQuotaExceededError() error {
  1581. return getReadQuotaExceededError(c.protocol)
  1582. }
  1583. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  1584. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  1585. switch c.protocol {
  1586. case ProtocolSFTP:
  1587. if err == nil {
  1588. return false
  1589. }
  1590. if errors.Is(err, ErrQuotaExceeded) {
  1591. return true
  1592. }
  1593. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1594. case ProtocolFTP:
  1595. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1596. default:
  1597. return errors.Is(err, ErrQuotaExceeded)
  1598. }
  1599. }
  1600. func isSFTPGoError(err error) bool {
  1601. return errors.Is(err, ErrPermissionDenied) || errors.Is(err, ErrNotExist) || errors.Is(err, ErrOpUnsupported) ||
  1602. errors.Is(err, ErrQuotaExceeded) || errors.Is(err, ErrReadQuotaExceeded) ||
  1603. errors.Is(err, vfs.ErrStorageSizeUnavailable) || errors.Is(err, ErrShuttingDown)
  1604. }
  1605. // GetGenericError returns an appropriate generic error for the connection protocol
  1606. func (c *BaseConnection) GetGenericError(err error) error {
  1607. switch c.protocol {
  1608. case ProtocolSFTP:
  1609. if errors.Is(err, vfs.ErrStorageSizeUnavailable) || errors.Is(err, ErrOpUnsupported) || errors.Is(err, sftp.ErrSSHFxOpUnsupported) {
  1610. return fmt.Errorf("%w: %w", sftp.ErrSSHFxOpUnsupported, err)
  1611. }
  1612. if isSFTPGoError(err) {
  1613. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, err)
  1614. }
  1615. if err != nil {
  1616. var pathError *fs.PathError
  1617. if errors.As(err, &pathError) {
  1618. c.Log(logger.LevelError, "generic path error: %+v", pathError)
  1619. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, pathError.Op, pathError.Err.Error())
  1620. }
  1621. c.Log(logger.LevelError, "generic error: %+v", err)
  1622. }
  1623. return sftp.ErrSSHFxFailure
  1624. default:
  1625. if isSFTPGoError(err) {
  1626. return err
  1627. }
  1628. c.Log(logger.LevelError, "generic error: %+v", err)
  1629. return ErrGenericFailure
  1630. }
  1631. }
  1632. // GetFsError converts a filesystem error to a protocol error
  1633. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1634. if fs.IsNotExist(err) {
  1635. return c.GetNotExistError()
  1636. } else if fs.IsPermission(err) {
  1637. return c.GetPermissionDeniedError()
  1638. } else if fs.IsNotSupported(err) {
  1639. return c.GetOpUnsupportedError()
  1640. } else if err != nil {
  1641. return c.GetGenericError(err)
  1642. }
  1643. return nil
  1644. }
  1645. func (c *BaseConnection) getNotificationStatus(err error) int {
  1646. if err == nil {
  1647. return 1
  1648. }
  1649. if c.IsQuotaExceededError(err) {
  1650. return 3
  1651. }
  1652. return 2
  1653. }
  1654. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1655. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1656. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1657. if err != nil {
  1658. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1659. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1660. // will not be listed
  1661. return nil, "", util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  1662. }
  1663. return nil, "", c.GetGenericError(err)
  1664. }
  1665. if isShuttingDown.Load() {
  1666. return nil, "", c.GetFsError(fs, ErrShuttingDown)
  1667. }
  1668. fsPath, err := fs.ResolvePath(virtualPath)
  1669. if err != nil {
  1670. return nil, "", c.GetFsError(fs, err)
  1671. }
  1672. return fs, fsPath, nil
  1673. }
  1674. // DirListerAt defines a directory lister implementing the ListAt method.
  1675. type DirListerAt struct {
  1676. virtualPath string
  1677. conn *BaseConnection
  1678. fs vfs.Fs
  1679. info []os.FileInfo
  1680. mu sync.Mutex
  1681. lister vfs.DirLister
  1682. }
  1683. // Add adds the given os.FileInfo to the internal cache
  1684. func (l *DirListerAt) Add(fi os.FileInfo) {
  1685. l.mu.Lock()
  1686. defer l.mu.Unlock()
  1687. l.info = slices.Insert(l.info, 0, fi)
  1688. }
  1689. // ListAt implements sftp.ListerAt
  1690. func (l *DirListerAt) ListAt(f []os.FileInfo, _ int64) (int, error) {
  1691. l.mu.Lock()
  1692. defer l.mu.Unlock()
  1693. if len(f) == 0 {
  1694. return 0, errors.New("invalid ListAt destination, zero size")
  1695. }
  1696. if len(f) <= len(l.info) {
  1697. files := make([]os.FileInfo, 0, len(f))
  1698. for idx := range l.info {
  1699. files = append(files, l.info[idx])
  1700. if len(files) == len(f) {
  1701. l.info = l.info[idx+1:]
  1702. n := copy(f, files)
  1703. return n, nil
  1704. }
  1705. }
  1706. }
  1707. limit := len(f) - len(l.info)
  1708. files, err := l.Next(limit)
  1709. n := copy(f, files)
  1710. return n, err
  1711. }
  1712. // Next reads the directory and returns a slice of up to n FileInfo values.
  1713. func (l *DirListerAt) Next(limit int) ([]os.FileInfo, error) {
  1714. for {
  1715. files, err := l.lister.Next(limit)
  1716. if err != nil && !errors.Is(err, io.EOF) {
  1717. l.conn.Log(logger.LevelDebug, "error retrieving directory entries: %+v", err)
  1718. return files, l.conn.GetFsError(l.fs, err)
  1719. }
  1720. files = l.conn.User.FilterListDir(files, l.virtualPath)
  1721. if len(l.info) > 0 {
  1722. files = slices.Concat(l.info, files)
  1723. l.info = nil
  1724. }
  1725. if err != nil || len(files) > 0 {
  1726. return files, err
  1727. }
  1728. }
  1729. }
  1730. // Close closes the DirListerAt
  1731. func (l *DirListerAt) Close() error {
  1732. l.mu.Lock()
  1733. defer l.mu.Unlock()
  1734. return l.lister.Close()
  1735. }
  1736. func (l *DirListerAt) convertError(err error) error {
  1737. if errors.Is(err, io.EOF) {
  1738. return nil
  1739. }
  1740. return err
  1741. }
  1742. func getPermissionDeniedError(protocol string) error {
  1743. switch protocol {
  1744. case ProtocolSFTP:
  1745. return sftp.ErrSSHFxPermissionDenied
  1746. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1747. return os.ErrPermission
  1748. default:
  1749. return ErrPermissionDenied
  1750. }
  1751. }
  1752. func keepConnectionAlive(c *BaseConnection, done chan bool, interval time.Duration) {
  1753. ticker := time.NewTicker(interval)
  1754. defer func() {
  1755. ticker.Stop()
  1756. }()
  1757. for {
  1758. select {
  1759. case <-done:
  1760. return
  1761. case <-ticker.C:
  1762. c.UpdateLastActivity()
  1763. }
  1764. }
  1765. }