1
0

connection.go 60 KB

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