connection.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  1. package common
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path"
  7. "strings"
  8. "sync"
  9. "sync/atomic"
  10. "time"
  11. ftpserver "github.com/fclairamb/ftpserverlib"
  12. "github.com/pkg/sftp"
  13. "github.com/drakkan/sftpgo/v2/dataprovider"
  14. "github.com/drakkan/sftpgo/v2/logger"
  15. "github.com/drakkan/sftpgo/v2/sdk"
  16. "github.com/drakkan/sftpgo/v2/util"
  17. "github.com/drakkan/sftpgo/v2/vfs"
  18. )
  19. // BaseConnection defines common fields for a connection using any supported protocol
  20. type BaseConnection struct {
  21. // last activity for this connection.
  22. // Since this field is accessed atomically we put it as first element of the struct to achieve 64 bit alignment
  23. lastActivity int64
  24. // unique ID for a transfer.
  25. // This field is accessed atomically so we put it at the beginning of the struct to achieve 64 bit alignment
  26. transferID uint64
  27. // Unique identifier for the connection
  28. ID string
  29. // user associated with this connection if any
  30. User dataprovider.User
  31. // start time for this connection
  32. startTime time.Time
  33. protocol string
  34. remoteAddr string
  35. localAddr string
  36. sync.RWMutex
  37. activeTransfers []ActiveTransfer
  38. }
  39. // NewBaseConnection returns a new BaseConnection
  40. func NewBaseConnection(id, protocol, localAddr, remoteAddr string, user dataprovider.User) *BaseConnection {
  41. connID := id
  42. if util.IsStringInSlice(protocol, supportedProtocols) {
  43. connID = fmt.Sprintf("%v_%v", protocol, id)
  44. }
  45. user.UploadBandwidth, user.DownloadBandwidth = user.GetBandwidthForIP(util.GetIPFromRemoteAddress(remoteAddr), connID)
  46. return &BaseConnection{
  47. ID: connID,
  48. User: user,
  49. startTime: time.Now(),
  50. protocol: protocol,
  51. localAddr: localAddr,
  52. remoteAddr: remoteAddr,
  53. lastActivity: time.Now().UnixNano(),
  54. transferID: 0,
  55. }
  56. }
  57. // Log outputs a log entry to the configured logger
  58. func (c *BaseConnection) Log(level logger.LogLevel, format string, v ...interface{}) {
  59. logger.Log(level, c.protocol, c.ID, format, v...)
  60. }
  61. // GetTransferID returns an unique transfer ID for this connection
  62. func (c *BaseConnection) GetTransferID() uint64 {
  63. return atomic.AddUint64(&c.transferID, 1)
  64. }
  65. // GetID returns the connection ID
  66. func (c *BaseConnection) GetID() string {
  67. return c.ID
  68. }
  69. // GetUsername returns the authenticated username associated with this connection if any
  70. func (c *BaseConnection) GetUsername() string {
  71. return c.User.Username
  72. }
  73. // GetProtocol returns the protocol for the connection
  74. func (c *BaseConnection) GetProtocol() string {
  75. return c.protocol
  76. }
  77. // GetRemoteIP returns the remote ip address
  78. func (c *BaseConnection) GetRemoteIP() string {
  79. return util.GetIPFromRemoteAddress(c.remoteAddr)
  80. }
  81. // SetProtocol sets the protocol for this connection
  82. func (c *BaseConnection) SetProtocol(protocol string) {
  83. c.protocol = protocol
  84. if util.IsStringInSlice(c.protocol, supportedProtocols) {
  85. c.ID = fmt.Sprintf("%v_%v", c.protocol, c.ID)
  86. }
  87. }
  88. // GetConnectionTime returns the initial connection time
  89. func (c *BaseConnection) GetConnectionTime() time.Time {
  90. return c.startTime
  91. }
  92. // UpdateLastActivity updates last activity for this connection
  93. func (c *BaseConnection) UpdateLastActivity() {
  94. atomic.StoreInt64(&c.lastActivity, time.Now().UnixNano())
  95. }
  96. // GetLastActivity returns the last connection activity
  97. func (c *BaseConnection) GetLastActivity() time.Time {
  98. return time.Unix(0, atomic.LoadInt64(&c.lastActivity))
  99. }
  100. // CloseFS closes the underlying fs
  101. func (c *BaseConnection) CloseFS() error {
  102. return c.User.CloseFs()
  103. }
  104. // AddTransfer associates a new transfer to this connection
  105. func (c *BaseConnection) AddTransfer(t ActiveTransfer) {
  106. c.Lock()
  107. defer c.Unlock()
  108. c.activeTransfers = append(c.activeTransfers, t)
  109. c.Log(logger.LevelDebug, "transfer added, id: %v, active transfers: %v", t.GetID(), len(c.activeTransfers))
  110. }
  111. // RemoveTransfer removes the specified transfer from the active ones
  112. func (c *BaseConnection) RemoveTransfer(t ActiveTransfer) {
  113. c.Lock()
  114. defer c.Unlock()
  115. indexToRemove := -1
  116. for i, v := range c.activeTransfers {
  117. if v.GetID() == t.GetID() {
  118. indexToRemove = i
  119. break
  120. }
  121. }
  122. if indexToRemove >= 0 {
  123. c.activeTransfers[indexToRemove] = c.activeTransfers[len(c.activeTransfers)-1]
  124. c.activeTransfers[len(c.activeTransfers)-1] = nil
  125. c.activeTransfers = c.activeTransfers[:len(c.activeTransfers)-1]
  126. c.Log(logger.LevelDebug, "transfer removed, id: %v active transfers: %v", t.GetID(), len(c.activeTransfers))
  127. } else {
  128. c.Log(logger.LevelWarn, "transfer to remove not found!")
  129. }
  130. }
  131. // GetTransfers returns the active transfers
  132. func (c *BaseConnection) GetTransfers() []ConnectionTransfer {
  133. c.RLock()
  134. defer c.RUnlock()
  135. transfers := make([]ConnectionTransfer, 0, len(c.activeTransfers))
  136. for _, t := range c.activeTransfers {
  137. var operationType string
  138. switch t.GetType() {
  139. case TransferDownload:
  140. operationType = operationDownload
  141. case TransferUpload:
  142. operationType = operationUpload
  143. }
  144. transfers = append(transfers, ConnectionTransfer{
  145. ID: t.GetID(),
  146. OperationType: operationType,
  147. StartTime: util.GetTimeAsMsSinceEpoch(t.GetStartTime()),
  148. Size: t.GetSize(),
  149. VirtualPath: t.GetVirtualPath(),
  150. })
  151. }
  152. return transfers
  153. }
  154. // SignalTransfersAbort signals to the active transfers to exit as soon as possible
  155. func (c *BaseConnection) SignalTransfersAbort() error {
  156. c.RLock()
  157. defer c.RUnlock()
  158. if len(c.activeTransfers) == 0 {
  159. return errors.New("no active transfer found")
  160. }
  161. for _, t := range c.activeTransfers {
  162. t.SignalClose()
  163. }
  164. return nil
  165. }
  166. func (c *BaseConnection) getRealFsPath(fsPath string) string {
  167. c.RLock()
  168. defer c.RUnlock()
  169. for _, t := range c.activeTransfers {
  170. if p := t.GetRealFsPath(fsPath); len(p) > 0 {
  171. return p
  172. }
  173. }
  174. return fsPath
  175. }
  176. func (c *BaseConnection) setTimes(fsPath string, atime time.Time, mtime time.Time) bool {
  177. c.RLock()
  178. defer c.RUnlock()
  179. for _, t := range c.activeTransfers {
  180. if t.SetTimes(fsPath, atime, mtime) {
  181. return true
  182. }
  183. }
  184. return false
  185. }
  186. func (c *BaseConnection) truncateOpenHandle(fsPath string, size int64) (int64, error) {
  187. c.RLock()
  188. defer c.RUnlock()
  189. for _, t := range c.activeTransfers {
  190. initialSize, err := t.Truncate(fsPath, size)
  191. if err != errTransferMismatch {
  192. return initialSize, err
  193. }
  194. }
  195. return 0, errNoTransfer
  196. }
  197. // ListDir reads the directory matching virtualPath and returns a list of directory entries
  198. func (c *BaseConnection) ListDir(virtualPath string) ([]os.FileInfo, error) {
  199. if !c.User.HasPerm(dataprovider.PermListItems, virtualPath) {
  200. return nil, c.GetPermissionDeniedError()
  201. }
  202. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  203. if err != nil {
  204. return nil, err
  205. }
  206. files, err := fs.ReadDir(fsPath)
  207. if err != nil {
  208. c.Log(logger.LevelDebug, "error listing directory: %+v", err)
  209. return nil, c.GetFsError(fs, err)
  210. }
  211. return c.User.AddVirtualDirs(files, virtualPath), nil
  212. }
  213. // CreateDir creates a new directory at the specified fsPath
  214. func (c *BaseConnection) CreateDir(virtualPath string) error {
  215. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  216. return c.GetPermissionDeniedError()
  217. }
  218. if c.User.IsVirtualFolder(virtualPath) {
  219. c.Log(logger.LevelWarn, "mkdir not allowed %#v is a virtual folder", virtualPath)
  220. return c.GetPermissionDeniedError()
  221. }
  222. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  223. if err != nil {
  224. return err
  225. }
  226. if err := fs.Mkdir(fsPath); err != nil {
  227. c.Log(logger.LevelError, "error creating dir: %#v error: %+v", fsPath, err)
  228. return c.GetFsError(fs, err)
  229. }
  230. vfs.SetPathPermissions(fs, fsPath, c.User.GetUID(), c.User.GetGID())
  231. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  232. c.localAddr, c.remoteAddr)
  233. ExecuteActionNotification(c, operationMkdir, fsPath, virtualPath, "", "", "", 0, nil)
  234. return nil
  235. }
  236. // IsRemoveFileAllowed returns an error if removing this file is not allowed
  237. func (c *BaseConnection) IsRemoveFileAllowed(virtualPath string) error {
  238. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  239. return c.GetPermissionDeniedError()
  240. }
  241. if !c.User.IsFileAllowed(virtualPath) {
  242. c.Log(logger.LevelDebug, "removing file %#v is not allowed", virtualPath)
  243. return c.GetPermissionDeniedError()
  244. }
  245. return nil
  246. }
  247. // RemoveFile removes a file at the specified fsPath
  248. func (c *BaseConnection) RemoveFile(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  249. if err := c.IsRemoveFileAllowed(virtualPath); err != nil {
  250. return err
  251. }
  252. size := info.Size()
  253. actionErr := ExecutePreAction(c, operationPreDelete, fsPath, virtualPath, size, 0)
  254. if actionErr == nil {
  255. c.Log(logger.LevelDebug, "remove for path %#v handled by pre-delete action", fsPath)
  256. } else {
  257. if err := fs.Remove(fsPath, false); err != nil {
  258. c.Log(logger.LevelError, "failed to remove file/symlink %#v: %+v", fsPath, err)
  259. return c.GetFsError(fs, err)
  260. }
  261. }
  262. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  263. c.localAddr, c.remoteAddr)
  264. if info.Mode()&os.ModeSymlink == 0 {
  265. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  266. if err == nil {
  267. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, -1, -size, false) //nolint:errcheck
  268. if vfolder.IsIncludedInUserQuota() {
  269. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  270. }
  271. } else {
  272. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  273. }
  274. }
  275. if actionErr != nil {
  276. ExecuteActionNotification(c, operationDelete, fsPath, virtualPath, "", "", "", size, nil)
  277. }
  278. return nil
  279. }
  280. // IsRemoveDirAllowed returns an error if removing this directory is not allowed
  281. func (c *BaseConnection) IsRemoveDirAllowed(fs vfs.Fs, fsPath, virtualPath string) error {
  282. if fs.GetRelativePath(fsPath) == "/" {
  283. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  284. return c.GetPermissionDeniedError()
  285. }
  286. if c.User.IsVirtualFolder(virtualPath) {
  287. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %#v", virtualPath)
  288. return c.GetPermissionDeniedError()
  289. }
  290. if c.User.HasVirtualFoldersInside(virtualPath) {
  291. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %#v", virtualPath)
  292. return c.GetOpUnsupportedError()
  293. }
  294. if c.User.IsMappedPath(fsPath) {
  295. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %#v", fsPath)
  296. return c.GetPermissionDeniedError()
  297. }
  298. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  299. return c.GetPermissionDeniedError()
  300. }
  301. return nil
  302. }
  303. // RemoveDir removes a directory at the specified fsPath
  304. func (c *BaseConnection) RemoveDir(virtualPath string) error {
  305. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  306. if err != nil {
  307. return err
  308. }
  309. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  310. return err
  311. }
  312. var fi os.FileInfo
  313. if fi, err = fs.Lstat(fsPath); err != nil {
  314. // see #149
  315. if fs.IsNotExist(err) && fs.HasVirtualFolders() {
  316. return nil
  317. }
  318. c.Log(logger.LevelError, "failed to remove a dir %#v: stat error: %+v", fsPath, err)
  319. return c.GetFsError(fs, err)
  320. }
  321. if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
  322. c.Log(logger.LevelError, "cannot remove %#v is not a directory", fsPath)
  323. return c.GetGenericError(nil)
  324. }
  325. if err := fs.Remove(fsPath, true); err != nil {
  326. c.Log(logger.LevelError, "failed to remove directory %#v: %+v", fsPath, err)
  327. return c.GetFsError(fs, err)
  328. }
  329. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  330. c.localAddr, c.remoteAddr)
  331. ExecuteActionNotification(c, operationRmdir, fsPath, virtualPath, "", "", "", 0, nil)
  332. return nil
  333. }
  334. // Rename renames (moves) virtualSourcePath to virtualTargetPath
  335. func (c *BaseConnection) Rename(virtualSourcePath, virtualTargetPath string) error {
  336. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  337. if err != nil {
  338. return err
  339. }
  340. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  341. if err != nil {
  342. return err
  343. }
  344. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  345. if err != nil {
  346. return c.GetFsError(fsSrc, err)
  347. }
  348. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  349. return c.GetPermissionDeniedError()
  350. }
  351. initialSize := int64(-1)
  352. if dstInfo, err := fsDst.Lstat(fsTargetPath); err == nil {
  353. if dstInfo.IsDir() {
  354. c.Log(logger.LevelWarn, "attempted to rename %#v overwriting an existing directory %#v",
  355. fsSourcePath, fsTargetPath)
  356. return c.GetOpUnsupportedError()
  357. }
  358. // we are overwriting an existing file/symlink
  359. if dstInfo.Mode().IsRegular() {
  360. initialSize = dstInfo.Size()
  361. }
  362. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  363. c.Log(logger.LevelDebug, "renaming %#v -> %#v is not allowed. Target exists but the user %#v"+
  364. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  365. return c.GetPermissionDeniedError()
  366. }
  367. }
  368. if srcInfo.IsDir() {
  369. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  370. c.Log(logger.LevelDebug, "renaming the folder %#v is not supported: it has virtual folders inside it",
  371. virtualSourcePath)
  372. return c.GetOpUnsupportedError()
  373. }
  374. if err = c.checkRecursiveRenameDirPermissions(fsSrc, fsDst, fsSourcePath, fsTargetPath); err != nil {
  375. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %#v: %+v", fsSourcePath, err)
  376. return err
  377. }
  378. }
  379. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  380. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  381. return c.GetGenericError(ErrQuotaExceeded)
  382. }
  383. if err := fsSrc.Rename(fsSourcePath, fsTargetPath); err != nil {
  384. c.Log(logger.LevelError, "failed to rename %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  385. return c.GetFsError(fsSrc, err)
  386. }
  387. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  388. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize) //nolint:errcheck
  389. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  390. "", "", "", -1, c.localAddr, c.remoteAddr)
  391. ExecuteActionNotification(c, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, virtualTargetPath,
  392. "", 0, nil)
  393. return nil
  394. }
  395. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  396. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  397. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  398. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  399. return c.GetOpUnsupportedError()
  400. }
  401. // we cannot have a cross folder request here so only one fs is enough
  402. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  403. if err != nil {
  404. return err
  405. }
  406. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  407. if err != nil {
  408. return c.GetFsError(fs, err)
  409. }
  410. if fs.GetRelativePath(fsSourcePath) == "/" {
  411. c.Log(logger.LevelWarn, "symlinking root dir is not allowed")
  412. return c.GetPermissionDeniedError()
  413. }
  414. if fs.GetRelativePath(fsTargetPath) == "/" {
  415. c.Log(logger.LevelWarn, "symlinking to root dir is not allowed")
  416. return c.GetPermissionDeniedError()
  417. }
  418. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  419. return c.GetPermissionDeniedError()
  420. }
  421. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  422. c.Log(logger.LevelError, "failed to create symlink %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  423. return c.GetFsError(fs, err)
  424. }
  425. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  426. "", "", -1, c.localAddr, c.remoteAddr)
  427. return nil
  428. }
  429. func (c *BaseConnection) getPathForSetStatPerms(fs vfs.Fs, fsPath, virtualPath string) string {
  430. pathForPerms := virtualPath
  431. if fi, err := fs.Lstat(fsPath); err == nil {
  432. if fi.IsDir() {
  433. pathForPerms = path.Dir(virtualPath)
  434. }
  435. }
  436. return pathForPerms
  437. }
  438. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  439. func (c *BaseConnection) DoStat(virtualPath string, mode int) (os.FileInfo, error) {
  440. // for some vfs we don't create intermediary folders so we cannot simply check
  441. // if virtualPath is a virtual folder
  442. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  443. if _, ok := vfolders[virtualPath]; ok {
  444. return vfs.NewFileInfo(virtualPath, true, 0, time.Now(), false), nil
  445. }
  446. var info os.FileInfo
  447. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  448. if err != nil {
  449. return info, err
  450. }
  451. if mode == 1 {
  452. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  453. } else {
  454. info, err = fs.Stat(c.getRealFsPath(fsPath))
  455. }
  456. if err != nil {
  457. c.Log(logger.LevelDebug, "stat error for path %#v: %+v", virtualPath, err)
  458. return info, c.GetFsError(fs, err)
  459. }
  460. if vfs.IsCryptOsFs(fs) {
  461. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  462. }
  463. return info, nil
  464. }
  465. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  466. if Config.SetstatMode == 1 {
  467. return true
  468. }
  469. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  470. return true
  471. }
  472. return false
  473. }
  474. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  475. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  476. return c.GetPermissionDeniedError()
  477. }
  478. if c.ignoreSetStat(fs) {
  479. return nil
  480. }
  481. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  482. c.Log(logger.LevelError, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  483. return c.GetFsError(fs, err)
  484. }
  485. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  486. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr)
  487. return nil
  488. }
  489. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  490. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  491. return c.GetPermissionDeniedError()
  492. }
  493. if c.ignoreSetStat(fs) {
  494. return nil
  495. }
  496. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  497. c.Log(logger.LevelError, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  498. attributes.GID, err)
  499. return c.GetFsError(fs, err)
  500. }
  501. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  502. "", "", "", -1, c.localAddr, c.remoteAddr)
  503. return nil
  504. }
  505. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  506. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  507. return c.GetPermissionDeniedError()
  508. }
  509. if Config.SetstatMode == 1 {
  510. return nil
  511. }
  512. isUploading := c.setTimes(fsPath, attributes.Atime, attributes.Mtime)
  513. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime, isUploading); err != nil {
  514. c.setTimes(fsPath, time.Time{}, time.Time{})
  515. if errors.Is(err, vfs.ErrVfsUnsupported) && Config.SetstatMode == 2 {
  516. return nil
  517. }
  518. c.Log(logger.LevelError, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  519. fsPath, attributes.Atime, attributes.Mtime, err)
  520. return c.GetFsError(fs, err)
  521. }
  522. accessTimeString := attributes.Atime.Format(chtimesFormat)
  523. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  524. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  525. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr)
  526. return nil
  527. }
  528. // SetStat set StatAttributes for the specified fsPath
  529. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  530. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  531. if err != nil {
  532. return err
  533. }
  534. pathForPerms := c.getPathForSetStatPerms(fs, fsPath, virtualPath)
  535. if attributes.Flags&StatAttrTimes != 0 {
  536. if err = c.handleChtimes(fs, fsPath, pathForPerms, attributes); err != nil {
  537. return err
  538. }
  539. }
  540. if attributes.Flags&StatAttrPerms != 0 {
  541. if err = c.handleChmod(fs, fsPath, pathForPerms, attributes); err != nil {
  542. return err
  543. }
  544. }
  545. if attributes.Flags&StatAttrUIDGID != 0 {
  546. if err = c.handleChown(fs, fsPath, pathForPerms, attributes); err != nil {
  547. return err
  548. }
  549. }
  550. if attributes.Flags&StatAttrSize != 0 {
  551. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  552. return c.GetPermissionDeniedError()
  553. }
  554. if err = c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  555. c.Log(logger.LevelError, "failed to truncate path %#v, size: %v, err: %+v", fsPath, attributes.Size, err)
  556. return c.GetFsError(fs, err)
  557. }
  558. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  559. "", attributes.Size, c.localAddr, c.remoteAddr)
  560. }
  561. return nil
  562. }
  563. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  564. // check first if we have an open transfer for the given path and try to truncate the file already opened
  565. // if we found no transfer we truncate by path.
  566. var initialSize int64
  567. var err error
  568. initialSize, err = c.truncateOpenHandle(fsPath, size)
  569. if err == errNoTransfer {
  570. c.Log(logger.LevelDebug, "file path %#v not found in active transfers, execute trucate by path", fsPath)
  571. var info os.FileInfo
  572. info, err = fs.Stat(fsPath)
  573. if err != nil {
  574. return err
  575. }
  576. initialSize = info.Size()
  577. err = fs.Truncate(fsPath, size)
  578. }
  579. if err == nil && vfs.IsLocalOrSFTPFs(fs) {
  580. sizeDiff := initialSize - size
  581. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  582. if err == nil {
  583. dataprovider.UpdateVirtualFolderQuota(&vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  584. if vfolder.IsIncludedInUserQuota() {
  585. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  586. }
  587. } else {
  588. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  589. }
  590. }
  591. return err
  592. }
  593. func (c *BaseConnection) checkRecursiveRenameDirPermissions(fsSrc, fsDst vfs.Fs, sourcePath, targetPath string) error {
  594. dstPerms := []string{
  595. dataprovider.PermCreateDirs,
  596. dataprovider.PermUpload,
  597. dataprovider.PermCreateSymlinks,
  598. }
  599. err := fsSrc.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  600. if err != nil {
  601. return c.GetFsError(fsSrc, err)
  602. }
  603. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  604. virtualSrcPath := fsSrc.GetRelativePath(walkedPath)
  605. virtualDstPath := fsDst.GetRelativePath(dstPath)
  606. // walk scans the directory tree in order, checking the parent directory permissions we are sure that all contents
  607. // inside the parent path was checked. If the current dir has no subdirs with defined permissions inside it
  608. // and it has all the possible permissions we can stop scanning
  609. if !c.User.HasPermissionsInside(path.Dir(virtualSrcPath)) && !c.User.HasPermissionsInside(path.Dir(virtualDstPath)) {
  610. if c.User.HasPermsRenameAll(path.Dir(virtualSrcPath)) &&
  611. c.User.HasPermsRenameAll(path.Dir(virtualDstPath)) {
  612. return ErrSkipPermissionsCheck
  613. }
  614. if c.User.HasPermsDeleteAll(path.Dir(virtualSrcPath)) &&
  615. c.User.HasPerms(dstPerms, path.Dir(virtualDstPath)) {
  616. return ErrSkipPermissionsCheck
  617. }
  618. }
  619. if !c.isRenamePermitted(fsSrc, fsDst, walkedPath, dstPath, virtualSrcPath, virtualDstPath, info) {
  620. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  621. walkedPath, dstPath, virtualDstPath)
  622. return c.GetPermissionDeniedError()
  623. }
  624. return nil
  625. })
  626. if err == ErrSkipPermissionsCheck {
  627. err = nil
  628. }
  629. return err
  630. }
  631. func (c *BaseConnection) hasRenamePerms(virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  632. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) &&
  633. c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  634. return true
  635. }
  636. if fi == nil {
  637. // we don't know if this is a file or a directory we have to check all the required permissions
  638. if !c.User.HasPermsDeleteAll(path.Dir(virtualSourcePath)) {
  639. return false
  640. }
  641. dstPerms := []string{
  642. dataprovider.PermCreateDirs,
  643. dataprovider.PermUpload,
  644. dataprovider.PermCreateSymlinks,
  645. }
  646. return c.User.HasPerms(dstPerms, path.Dir(virtualTargetPath))
  647. }
  648. if fi.IsDir() {
  649. if c.User.HasPerm(dataprovider.PermRenameDirs, path.Dir(virtualSourcePath)) &&
  650. c.User.HasPerm(dataprovider.PermRenameDirs, path.Dir(virtualTargetPath)) {
  651. return true
  652. }
  653. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualSourcePath)) {
  654. return false
  655. }
  656. return c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualTargetPath))
  657. }
  658. // file or symlink
  659. if c.User.HasPerm(dataprovider.PermRenameFiles, path.Dir(virtualSourcePath)) &&
  660. c.User.HasPerm(dataprovider.PermRenameFiles, path.Dir(virtualTargetPath)) {
  661. return true
  662. }
  663. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualSourcePath)) {
  664. return false
  665. }
  666. if fi.Mode()&os.ModeSymlink != 0 {
  667. return c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath))
  668. }
  669. return c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualTargetPath))
  670. }
  671. func (c *BaseConnection) isRenamePermitted(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  672. if !c.isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath) {
  673. c.Log(logger.LevelInfo, "rename %#v->%#v is not allowed: the paths must be local or on the same virtual folder",
  674. virtualSourcePath, virtualTargetPath)
  675. return false
  676. }
  677. if c.User.IsMappedPath(fsSourcePath) && vfs.IsLocalOrCryptoFs(fsSrc) {
  678. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  679. return false
  680. }
  681. if c.User.IsMappedPath(fsTargetPath) && vfs.IsLocalOrCryptoFs(fsDst) {
  682. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  683. return false
  684. }
  685. if fsSrc.GetRelativePath(fsSourcePath) == "/" {
  686. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  687. return false
  688. }
  689. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  690. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  691. return false
  692. }
  693. if !c.User.IsFileAllowed(virtualSourcePath) || !c.User.IsFileAllowed(virtualTargetPath) {
  694. if fi != nil && fi.Mode().IsRegular() {
  695. c.Log(logger.LevelDebug, "renaming file is not allowed, source: %#v target: %#v",
  696. virtualSourcePath, virtualTargetPath)
  697. return false
  698. }
  699. }
  700. return c.hasRenamePerms(virtualSourcePath, virtualTargetPath, fi)
  701. }
  702. func (c *BaseConnection) hasSpaceForRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath string, initialSize int64,
  703. fsSourcePath string) bool {
  704. if dataprovider.GetQuotaTracking() == 0 {
  705. return true
  706. }
  707. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  708. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  709. if errSrc != nil && errDst != nil {
  710. // rename inside the user home dir
  711. return true
  712. }
  713. if errSrc == nil && errDst == nil {
  714. // rename between virtual folders
  715. if sourceFolder.Name == dstFolder.Name {
  716. // rename inside the same virtual folder
  717. return true
  718. }
  719. }
  720. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  721. // rename between user root dir and a virtual folder included in user quota
  722. return true
  723. }
  724. quotaResult := c.HasSpace(true, false, virtualTargetPath)
  725. return c.hasSpaceForCrossRename(fs, quotaResult, initialSize, fsSourcePath)
  726. }
  727. // hasSpaceForCrossRename checks the quota after a rename between different folders
  728. func (c *BaseConnection) hasSpaceForCrossRename(fs vfs.Fs, quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  729. if !quotaResult.HasSpace && initialSize == -1 {
  730. // we are over quota and this is not a file replace
  731. return false
  732. }
  733. fi, err := fs.Lstat(sourcePath)
  734. if err != nil {
  735. c.Log(logger.LevelError, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  736. return false
  737. }
  738. var sizeDiff int64
  739. var filesDiff int
  740. if fi.Mode().IsRegular() {
  741. sizeDiff = fi.Size()
  742. filesDiff = 1
  743. if initialSize != -1 {
  744. sizeDiff -= initialSize
  745. filesDiff = 0
  746. }
  747. } else if fi.IsDir() {
  748. filesDiff, sizeDiff, err = fs.GetDirSize(sourcePath)
  749. if err != nil {
  750. c.Log(logger.LevelError, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  751. return false
  752. }
  753. }
  754. if !quotaResult.HasSpace && initialSize != -1 {
  755. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  756. if quotaResult.QuotaSize == 0 {
  757. return true
  758. }
  759. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  760. sourcePath, quotaResult.UsedSize, sizeDiff)
  761. quotaResult.UsedSize += sizeDiff
  762. return quotaResult.GetRemainingSize() >= 0
  763. }
  764. if quotaResult.QuotaFiles > 0 {
  765. remainingFiles := quotaResult.GetRemainingFiles()
  766. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  767. remainingFiles, filesDiff)
  768. if remainingFiles < filesDiff {
  769. return false
  770. }
  771. }
  772. if quotaResult.QuotaSize > 0 {
  773. remainingSize := quotaResult.GetRemainingSize()
  774. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  775. remainingSize, sizeDiff)
  776. if remainingSize < sizeDiff {
  777. return false
  778. }
  779. }
  780. return true
  781. }
  782. // GetMaxWriteSize returns the allowed size for an upload or an error
  783. // if no enough size is available for a resume/append
  784. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64, isUploadResumeSupported bool) (int64, error) {
  785. maxWriteSize := quotaResult.GetRemainingSize()
  786. if isResume {
  787. if !isUploadResumeSupported {
  788. return 0, c.GetOpUnsupportedError()
  789. }
  790. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  791. return 0, c.GetQuotaExceededError()
  792. }
  793. if c.User.Filters.MaxUploadFileSize > 0 {
  794. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  795. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  796. maxWriteSize = maxUploadSize
  797. }
  798. }
  799. } else {
  800. if maxWriteSize > 0 {
  801. maxWriteSize += fileSize
  802. }
  803. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  804. maxWriteSize = c.User.Filters.MaxUploadFileSize
  805. }
  806. }
  807. return maxWriteSize, nil
  808. }
  809. // HasSpace checks user's quota usage
  810. func (c *BaseConnection) HasSpace(checkFiles, getUsage bool, requestPath string) vfs.QuotaCheckResult {
  811. result := vfs.QuotaCheckResult{
  812. HasSpace: true,
  813. AllowedSize: 0,
  814. AllowedFiles: 0,
  815. UsedSize: 0,
  816. UsedFiles: 0,
  817. QuotaSize: 0,
  818. QuotaFiles: 0,
  819. }
  820. if dataprovider.GetQuotaTracking() == 0 {
  821. return result
  822. }
  823. var err error
  824. var vfolder vfs.VirtualFolder
  825. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  826. if err == nil && !vfolder.IsIncludedInUserQuota() {
  827. if vfolder.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  828. return result
  829. }
  830. result.QuotaSize = vfolder.QuotaSize
  831. result.QuotaFiles = vfolder.QuotaFiles
  832. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.Name)
  833. } else {
  834. if c.User.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  835. return result
  836. }
  837. result.QuotaSize = c.User.QuotaSize
  838. result.QuotaFiles = c.User.QuotaFiles
  839. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedQuota(c.User.Username)
  840. }
  841. if err != nil {
  842. c.Log(logger.LevelError, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  843. result.HasSpace = false
  844. return result
  845. }
  846. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  847. result.AllowedSize = result.QuotaSize - result.UsedSize
  848. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  849. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  850. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  851. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  852. result.HasSpace = false
  853. return result
  854. }
  855. return result
  856. }
  857. // returns true if this is a rename on the same fs or local virtual folders
  858. func (c *BaseConnection) isLocalOrSameFolderRename(virtualSourcePath, virtualTargetPath string) bool {
  859. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  860. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  861. if errSrc != nil && errDst != nil {
  862. return true
  863. }
  864. if errSrc == nil && errDst == nil {
  865. if sourceFolder.Name == dstFolder.Name {
  866. return true
  867. }
  868. // we have different folders, only local fs is supported
  869. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider &&
  870. dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  871. return true
  872. }
  873. return false
  874. }
  875. if c.User.FsConfig.Provider != sdk.LocalFilesystemProvider {
  876. return false
  877. }
  878. if errSrc == nil {
  879. if sourceFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  880. return true
  881. }
  882. }
  883. if errDst == nil {
  884. if dstFolder.FsConfig.Provider == sdk.LocalFilesystemProvider {
  885. return true
  886. }
  887. }
  888. return false
  889. }
  890. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  891. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  892. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  893. if errSrc != nil && errDst != nil {
  894. return false
  895. }
  896. if errSrc == nil && errDst == nil {
  897. return sourceFolder.Name != dstFolder.Name
  898. }
  899. return true
  900. }
  901. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder *vfs.VirtualFolder, initialSize,
  902. filesSize int64, numFiles int) {
  903. if sourceFolder.Name == dstFolder.Name {
  904. // both files are inside the same virtual folder
  905. if initialSize != -1 {
  906. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  907. if dstFolder.IsIncludedInUserQuota() {
  908. dataprovider.UpdateUserQuota(&c.User, -numFiles, -initialSize, false) //nolint:errcheck
  909. }
  910. }
  911. return
  912. }
  913. // files are inside different virtual folders
  914. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  915. if sourceFolder.IsIncludedInUserQuota() {
  916. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  917. }
  918. if initialSize == -1 {
  919. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  920. if dstFolder.IsIncludedInUserQuota() {
  921. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  922. }
  923. } else {
  924. // we cannot have a directory here, initialSize != -1 only for files
  925. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  926. if dstFolder.IsIncludedInUserQuota() {
  927. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  928. }
  929. }
  930. }
  931. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  932. // move between a virtual folder and the user home dir
  933. dataprovider.UpdateVirtualFolderQuota(&sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  934. if sourceFolder.IsIncludedInUserQuota() {
  935. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  936. }
  937. if initialSize == -1 {
  938. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  939. } else {
  940. // we cannot have a directory here, initialSize != -1 only for files
  941. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  942. }
  943. }
  944. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  945. // move between the user home dir and a virtual folder
  946. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  947. if initialSize == -1 {
  948. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  949. if dstFolder.IsIncludedInUserQuota() {
  950. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  951. }
  952. } else {
  953. // we cannot have a directory here, initialSize != -1 only for files
  954. dataprovider.UpdateVirtualFolderQuota(&dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  955. if dstFolder.IsIncludedInUserQuota() {
  956. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  957. }
  958. }
  959. }
  960. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  961. if dataprovider.GetQuotaTracking() == 0 {
  962. return nil
  963. }
  964. // we don't allow to overwrite an existing directory so targetPath can be:
  965. // - a new file, a symlink is as a new file here
  966. // - a file overwriting an existing one
  967. // - a new directory
  968. // initialSize != -1 only when overwriting files
  969. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  970. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  971. if errSrc != nil && errDst != nil {
  972. // both files are contained inside the user home dir
  973. if initialSize != -1 {
  974. // we cannot have a directory here, we are overwriting an existing file
  975. // we need to subtract the size of the overwritten file from the user quota
  976. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  977. }
  978. return nil
  979. }
  980. filesSize := int64(0)
  981. numFiles := 1
  982. if fi, err := fs.Stat(targetPath); err == nil {
  983. if fi.Mode().IsDir() {
  984. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  985. if err != nil {
  986. c.Log(logger.LevelError, "failed to update quota after rename, error scanning moved folder %#v: %v",
  987. targetPath, err)
  988. return err
  989. }
  990. } else {
  991. filesSize = fi.Size()
  992. }
  993. } else {
  994. c.Log(logger.LevelError, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  995. return err
  996. }
  997. if errSrc == nil && errDst == nil {
  998. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  999. }
  1000. if errSrc == nil && errDst != nil {
  1001. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  1002. }
  1003. if errSrc != nil && errDst == nil {
  1004. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  1005. }
  1006. return nil
  1007. }
  1008. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  1009. func (c *BaseConnection) GetPermissionDeniedError() error {
  1010. switch c.protocol {
  1011. case ProtocolSFTP:
  1012. return sftp.ErrSSHFxPermissionDenied
  1013. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolHTTPShare, ProtocolDataRetention:
  1014. return os.ErrPermission
  1015. default:
  1016. return ErrPermissionDenied
  1017. }
  1018. }
  1019. // GetNotExistError returns an appropriate not exist error for the connection protocol
  1020. func (c *BaseConnection) GetNotExistError() error {
  1021. switch c.protocol {
  1022. case ProtocolSFTP:
  1023. return sftp.ErrSSHFxNoSuchFile
  1024. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolHTTPShare, ProtocolDataRetention:
  1025. return os.ErrNotExist
  1026. default:
  1027. return ErrNotExist
  1028. }
  1029. }
  1030. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  1031. func (c *BaseConnection) GetOpUnsupportedError() error {
  1032. switch c.protocol {
  1033. case ProtocolSFTP:
  1034. return sftp.ErrSSHFxOpUnsupported
  1035. default:
  1036. return ErrOpUnsupported
  1037. }
  1038. }
  1039. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  1040. func (c *BaseConnection) GetQuotaExceededError() error {
  1041. switch c.protocol {
  1042. case ProtocolSFTP:
  1043. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, ErrQuotaExceeded.Error())
  1044. case ProtocolFTP:
  1045. return ftpserver.ErrStorageExceeded
  1046. default:
  1047. return ErrQuotaExceeded
  1048. }
  1049. }
  1050. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  1051. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  1052. switch c.protocol {
  1053. case ProtocolSFTP:
  1054. if err == nil {
  1055. return false
  1056. }
  1057. if errors.Is(err, ErrQuotaExceeded) {
  1058. return true
  1059. }
  1060. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1061. case ProtocolFTP:
  1062. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1063. default:
  1064. return errors.Is(err, ErrQuotaExceeded)
  1065. }
  1066. }
  1067. // GetGenericError returns an appropriate generic error for the connection protocol
  1068. func (c *BaseConnection) GetGenericError(err error) error {
  1069. switch c.protocol {
  1070. case ProtocolSFTP:
  1071. if err == vfs.ErrStorageSizeUnavailable {
  1072. return fmt.Errorf("%w: %v", sftp.ErrSSHFxOpUnsupported, err.Error())
  1073. }
  1074. if err != nil {
  1075. if e, ok := err.(*os.PathError); ok {
  1076. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, e.Op, e.Err.Error())
  1077. }
  1078. return fmt.Errorf("%w: %v", sftp.ErrSSHFxFailure, err.Error())
  1079. }
  1080. return sftp.ErrSSHFxFailure
  1081. default:
  1082. if err == ErrPermissionDenied || err == ErrNotExist || err == ErrOpUnsupported ||
  1083. err == ErrQuotaExceeded || err == vfs.ErrStorageSizeUnavailable {
  1084. return err
  1085. }
  1086. return ErrGenericFailure
  1087. }
  1088. }
  1089. // GetFsError converts a filesystem error to a protocol error
  1090. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1091. if fs.IsNotExist(err) {
  1092. return c.GetNotExistError()
  1093. } else if fs.IsPermission(err) {
  1094. return c.GetPermissionDeniedError()
  1095. } else if fs.IsNotSupported(err) {
  1096. return c.GetOpUnsupportedError()
  1097. } else if err != nil {
  1098. return c.GetGenericError(err)
  1099. }
  1100. return nil
  1101. }
  1102. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1103. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1104. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1105. if err != nil {
  1106. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1107. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1108. // will not be listed
  1109. return nil, "", c.GetPermissionDeniedError()
  1110. }
  1111. return nil, "", err
  1112. }
  1113. fsPath, err := fs.ResolvePath(virtualPath)
  1114. if err != nil {
  1115. return nil, "", c.GetFsError(fs, err)
  1116. }
  1117. return fs, fsPath, nil
  1118. }