connection.go 38 KB

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