connection.go 65 KB

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