connection.go 41 KB

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