connection.go 38 KB

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