connection.go 64 KB

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