connection.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. package common
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "strings"
  7. "sync"
  8. "sync/atomic"
  9. "time"
  10. "github.com/pkg/sftp"
  11. "github.com/drakkan/sftpgo/dataprovider"
  12. "github.com/drakkan/sftpgo/logger"
  13. "github.com/drakkan/sftpgo/utils"
  14. "github.com/drakkan/sftpgo/vfs"
  15. )
  16. // BaseConnection defines common fields for a connection using any supported protocol
  17. type BaseConnection struct {
  18. // Unique identifier for the connection
  19. ID string
  20. // user associated with this connection if any
  21. User dataprovider.User
  22. // start time for this connection
  23. startTime time.Time
  24. protocol string
  25. Fs vfs.Fs
  26. sync.RWMutex
  27. // last activity for this connection
  28. lastActivity int64
  29. transferID uint64
  30. activeTransfers []ActiveTransfer
  31. }
  32. // NewBaseConnection returns a new BaseConnection
  33. func NewBaseConnection(ID, protocol string, user dataprovider.User, fs vfs.Fs) *BaseConnection {
  34. connID := ID
  35. if utils.IsStringInSlice(protocol, supportedProcols) {
  36. connID = fmt.Sprintf("%v_%v", protocol, ID)
  37. }
  38. return &BaseConnection{
  39. ID: connID,
  40. User: user,
  41. startTime: time.Now(),
  42. protocol: protocol,
  43. Fs: fs,
  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, supportedProcols) {
  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. // AddTransfer associates a new transfer to this connection
  88. func (c *BaseConnection) AddTransfer(t ActiveTransfer) {
  89. c.Lock()
  90. defer c.Unlock()
  91. c.activeTransfers = append(c.activeTransfers, t)
  92. c.Log(logger.LevelDebug, "transfer added, id: %v, active transfers: %v", t.GetID(), len(c.activeTransfers))
  93. }
  94. // RemoveTransfer removes the specified transfer from the active ones
  95. func (c *BaseConnection) RemoveTransfer(t ActiveTransfer) {
  96. c.Lock()
  97. defer c.Unlock()
  98. indexToRemove := -1
  99. for i, v := range c.activeTransfers {
  100. if v.GetID() == t.GetID() {
  101. indexToRemove = i
  102. break
  103. }
  104. }
  105. if indexToRemove >= 0 {
  106. c.activeTransfers[indexToRemove] = c.activeTransfers[len(c.activeTransfers)-1]
  107. c.activeTransfers[len(c.activeTransfers)-1] = nil
  108. c.activeTransfers = c.activeTransfers[:len(c.activeTransfers)-1]
  109. c.Log(logger.LevelDebug, "transfer removed, id: %v active transfers: %v", t.GetID(), len(c.activeTransfers))
  110. } else {
  111. c.Log(logger.LevelWarn, "transfer to remove not found!")
  112. }
  113. }
  114. // GetTransfers returns the active transfers
  115. func (c *BaseConnection) GetTransfers() []ConnectionTransfer {
  116. c.RLock()
  117. defer c.RUnlock()
  118. transfers := make([]ConnectionTransfer, 0, len(c.activeTransfers))
  119. for _, t := range c.activeTransfers {
  120. var operationType string
  121. if t.GetType() == TransferUpload {
  122. operationType = operationUpload
  123. } else {
  124. operationType = operationDownload
  125. }
  126. transfers = append(transfers, ConnectionTransfer{
  127. ID: t.GetID(),
  128. OperationType: operationType,
  129. StartTime: utils.GetTimeAsMsSinceEpoch(t.GetStartTime()),
  130. Size: t.GetSize(),
  131. VirtualPath: t.GetVirtualPath(),
  132. })
  133. }
  134. return transfers
  135. }
  136. // ListDir reads the directory named by fsPath and returns a list of directory entries
  137. func (c *BaseConnection) ListDir(fsPath, virtualPath string) ([]os.FileInfo, error) {
  138. if !c.User.HasPerm(dataprovider.PermListItems, virtualPath) {
  139. return nil, c.GetPermissionDeniedError()
  140. }
  141. files, err := c.Fs.ReadDir(fsPath)
  142. if err != nil {
  143. c.Log(logger.LevelWarn, "error listing directory: %+v", err)
  144. return nil, c.GetFsError(err)
  145. }
  146. return c.User.AddVirtualDirs(files, virtualPath), nil
  147. }
  148. // CreateDir creates a new directory at the specified fsPath
  149. func (c *BaseConnection) CreateDir(fsPath, virtualPath string) error {
  150. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  151. return c.GetPermissionDeniedError()
  152. }
  153. if c.User.IsVirtualFolder(virtualPath) {
  154. c.Log(logger.LevelWarn, "mkdir not allowed %#v is a virtual folder", virtualPath)
  155. return c.GetPermissionDeniedError()
  156. }
  157. if err := c.Fs.Mkdir(fsPath); err != nil {
  158. c.Log(logger.LevelWarn, "error creating dir: %#v error: %+v", fsPath, err)
  159. return c.GetFsError(err)
  160. }
  161. vfs.SetPathPermissions(c.Fs, fsPath, c.User.GetUID(), c.User.GetGID())
  162. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "")
  163. return nil
  164. }
  165. // RemoveFile removes a file at the specified fsPath
  166. func (c *BaseConnection) RemoveFile(fsPath, virtualPath string, info os.FileInfo) error {
  167. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualPath)) {
  168. return c.GetPermissionDeniedError()
  169. }
  170. if !c.User.IsFileAllowed(virtualPath) {
  171. c.Log(logger.LevelDebug, "removing file %#v is not allowed", fsPath)
  172. return c.GetPermissionDeniedError()
  173. }
  174. size := info.Size()
  175. action := newActionNotification(&c.User, operationPreDelete, fsPath, "", "", c.protocol, size, nil)
  176. actionErr := action.execute()
  177. if actionErr == nil {
  178. c.Log(logger.LevelDebug, "remove for path %#v handled by pre-delete action", fsPath)
  179. } else {
  180. if err := c.Fs.Remove(fsPath, false); err != nil {
  181. c.Log(logger.LevelWarn, "failed to remove a file/symlink %#v: %+v", fsPath, err)
  182. return c.GetFsError(err)
  183. }
  184. }
  185. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "")
  186. if info.Mode()&os.ModeSymlink != os.ModeSymlink {
  187. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  188. if err == nil {
  189. dataprovider.UpdateVirtualFolderQuota(vfolder.BaseVirtualFolder, -1, -size, false) //nolint:errcheck
  190. if vfolder.IsIncludedInUserQuota() {
  191. dataprovider.UpdateUserQuota(c.User, -1, -size, false) //nolint:errcheck
  192. }
  193. } else {
  194. dataprovider.UpdateUserQuota(c.User, -1, -size, false) //nolint:errcheck
  195. }
  196. }
  197. if actionErr != nil {
  198. action := newActionNotification(&c.User, operationDelete, fsPath, "", "", c.protocol, size, nil)
  199. go action.execute() //nolint:errcheck
  200. }
  201. return nil
  202. }
  203. // RemoveDir removes a directory at the specified fsPath
  204. func (c *BaseConnection) RemoveDir(fsPath, virtualPath string) error {
  205. if c.Fs.GetRelativePath(fsPath) == "/" {
  206. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  207. return c.GetPermissionDeniedError()
  208. }
  209. if c.User.IsVirtualFolder(virtualPath) {
  210. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %#v", virtualPath)
  211. return c.GetPermissionDeniedError()
  212. }
  213. if c.User.HasVirtualFoldersInside(virtualPath) {
  214. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %#v", virtualPath)
  215. return c.GetOpUnsupportedError()
  216. }
  217. if c.User.IsMappedPath(fsPath) {
  218. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %#v", fsPath)
  219. return c.GetPermissionDeniedError()
  220. }
  221. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualPath)) {
  222. return c.GetPermissionDeniedError()
  223. }
  224. var fi os.FileInfo
  225. var err error
  226. if fi, err = c.Fs.Lstat(fsPath); err != nil {
  227. c.Log(logger.LevelWarn, "failed to remove a dir %#v: stat error: %+v", fsPath, err)
  228. return c.GetFsError(err)
  229. }
  230. if !fi.IsDir() || fi.Mode()&os.ModeSymlink == os.ModeSymlink {
  231. c.Log(logger.LevelDebug, "cannot remove %#v is not a directory", fsPath)
  232. return c.GetGenericError()
  233. }
  234. if err := c.Fs.Remove(fsPath, true); err != nil {
  235. c.Log(logger.LevelWarn, "failed to remove directory %#v: %+v", fsPath, err)
  236. return c.GetFsError(err)
  237. }
  238. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "")
  239. return nil
  240. }
  241. // Rename renames (moves) fsSourcePath to fsTargetPath
  242. func (c *BaseConnection) Rename(fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath string) error {
  243. if c.User.IsMappedPath(fsSourcePath) {
  244. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  245. return c.GetPermissionDeniedError()
  246. }
  247. if c.User.IsMappedPath(fsTargetPath) {
  248. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  249. return c.GetPermissionDeniedError()
  250. }
  251. srcInfo, err := c.Fs.Lstat(fsSourcePath)
  252. if err != nil {
  253. return c.GetFsError(err)
  254. }
  255. if !c.isRenamePermitted(fsSourcePath, virtualSourcePath, virtualTargetPath, srcInfo) {
  256. return c.GetPermissionDeniedError()
  257. }
  258. initialSize := int64(-1)
  259. if dstInfo, err := c.Fs.Lstat(fsTargetPath); err == nil {
  260. if dstInfo.IsDir() {
  261. c.Log(logger.LevelWarn, "attempted to rename %#v overwriting an existing directory %#v",
  262. fsSourcePath, fsTargetPath)
  263. return c.GetOpUnsupportedError()
  264. }
  265. // we are overwriting an existing file/symlink
  266. if dstInfo.Mode().IsRegular() {
  267. initialSize = dstInfo.Size()
  268. }
  269. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  270. c.Log(logger.LevelDebug, "renaming is not allowed, %#v -> %#v. Target exists but the user "+
  271. "has no overwrite permission", virtualSourcePath, virtualTargetPath)
  272. return c.GetPermissionDeniedError()
  273. }
  274. }
  275. if srcInfo.IsDir() {
  276. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  277. c.Log(logger.LevelDebug, "renaming the folder %#v is not supported: it has virtual folders inside it",
  278. virtualSourcePath)
  279. return c.GetOpUnsupportedError()
  280. }
  281. if err = c.checkRecursiveRenameDirPermissions(fsSourcePath, fsTargetPath); err != nil {
  282. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %#v: %+v", fsSourcePath, err)
  283. return c.GetFsError(err)
  284. }
  285. }
  286. if !c.hasSpaceForRename(virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  287. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  288. return c.GetGenericError()
  289. }
  290. if err := c.Fs.Rename(fsSourcePath, fsTargetPath); err != nil {
  291. c.Log(logger.LevelWarn, "failed to rename %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  292. return c.GetFsError(err)
  293. }
  294. if dataprovider.GetQuotaTracking() > 0 {
  295. c.updateQuotaAfterRename(virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize) //nolint:errcheck
  296. }
  297. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  298. "", "", "")
  299. action := newActionNotification(&c.User, operationRename, fsSourcePath, fsTargetPath, "", c.protocol, 0, nil)
  300. // the returned error is used in test cases only, we already log the error inside action.execute
  301. go action.execute() //nolint:errcheck
  302. return nil
  303. }
  304. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  305. func (c *BaseConnection) CreateSymlink(fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath string) error {
  306. if c.Fs.GetRelativePath(fsSourcePath) == "/" {
  307. c.Log(logger.LevelWarn, "symlinking root dir is not allowed")
  308. return c.GetPermissionDeniedError()
  309. }
  310. if c.User.IsVirtualFolder(virtualTargetPath) {
  311. c.Log(logger.LevelWarn, "symlinking a virtual folder is not allowed")
  312. return c.GetPermissionDeniedError()
  313. }
  314. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  315. return c.GetPermissionDeniedError()
  316. }
  317. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  318. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  319. return c.GetGenericError()
  320. }
  321. if c.User.IsMappedPath(fsSourcePath) {
  322. c.Log(logger.LevelWarn, "symlinking a directory mapped as virtual folder is not allowed: %#v", fsSourcePath)
  323. return c.GetPermissionDeniedError()
  324. }
  325. if c.User.IsMappedPath(fsTargetPath) {
  326. c.Log(logger.LevelWarn, "symlinking to a directory mapped as virtual folder is not allowed: %#v", fsTargetPath)
  327. return c.GetPermissionDeniedError()
  328. }
  329. if err := c.Fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  330. c.Log(logger.LevelWarn, "failed to create symlink %#v -> %#v: %+v", fsSourcePath, fsTargetPath, err)
  331. return c.GetFsError(err)
  332. }
  333. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "")
  334. return nil
  335. }
  336. // SetStat set StatAttributes for the specified fsPath
  337. func (c *BaseConnection) SetStat(fsPath, virtualPath string, attributes *StatAttributes) error {
  338. if Config.SetstatMode == 1 {
  339. return nil
  340. }
  341. pathForPerms := virtualPath
  342. if fi, err := c.Fs.Lstat(fsPath); err == nil {
  343. if fi.IsDir() {
  344. pathForPerms = path.Dir(virtualPath)
  345. }
  346. }
  347. if attributes.Flags&StatAttrPerms != 0 {
  348. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  349. return c.GetPermissionDeniedError()
  350. }
  351. if err := c.Fs.Chmod(fsPath, attributes.Mode); err != nil {
  352. c.Log(logger.LevelWarn, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  353. return c.GetFsError(err)
  354. }
  355. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  356. -1, -1, "", "", "")
  357. }
  358. if attributes.Flags&StatAttrUIDGID != 0 {
  359. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  360. return c.GetPermissionDeniedError()
  361. }
  362. if err := c.Fs.Chown(fsPath, attributes.UID, attributes.GID); err != nil {
  363. c.Log(logger.LevelWarn, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  364. attributes.GID, err)
  365. return c.GetFsError(err)
  366. }
  367. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  368. "", "", "")
  369. }
  370. if attributes.Flags&StatAttrTimes != 0 {
  371. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  372. return sftp.ErrSSHFxPermissionDenied
  373. }
  374. if err := c.Fs.Chtimes(fsPath, attributes.Atime, attributes.Mtime); err != nil {
  375. c.Log(logger.LevelWarn, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  376. fsPath, attributes.Atime, attributes.Mtime, err)
  377. return c.GetFsError(err)
  378. }
  379. accessTimeString := attributes.Atime.Format(chtimesFormat)
  380. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  381. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  382. accessTimeString, modificationTimeString, "")
  383. }
  384. return nil
  385. }
  386. func (c *BaseConnection) checkRecursiveRenameDirPermissions(sourcePath, targetPath string) error {
  387. dstPerms := []string{
  388. dataprovider.PermCreateDirs,
  389. dataprovider.PermUpload,
  390. dataprovider.PermCreateSymlinks,
  391. }
  392. err := c.Fs.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  393. if err != nil {
  394. return err
  395. }
  396. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  397. virtualSrcPath := c.Fs.GetRelativePath(walkedPath)
  398. virtualDstPath := c.Fs.GetRelativePath(dstPath)
  399. // walk scans the directory tree in order, checking the parent dirctory permissions we are sure that all contents
  400. // inside the parent path was checked. If the current dir has no subdirs with defined permissions inside it
  401. // and it has all the possible permissions we can stop scanning
  402. if !c.User.HasPermissionsInside(path.Dir(virtualSrcPath)) && !c.User.HasPermissionsInside(path.Dir(virtualDstPath)) {
  403. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSrcPath)) &&
  404. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualDstPath)) {
  405. return ErrSkipPermissionsCheck
  406. }
  407. if c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSrcPath)) &&
  408. c.User.HasPerms(dstPerms, path.Dir(virtualDstPath)) {
  409. return ErrSkipPermissionsCheck
  410. }
  411. }
  412. if !c.isRenamePermitted(walkedPath, virtualSrcPath, virtualDstPath, info) {
  413. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  414. walkedPath, dstPath, virtualDstPath)
  415. return os.ErrPermission
  416. }
  417. return nil
  418. })
  419. if err == ErrSkipPermissionsCheck {
  420. err = nil
  421. }
  422. return err
  423. }
  424. func (c *BaseConnection) isRenamePermitted(fsSourcePath, virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  425. if c.Fs.GetRelativePath(fsSourcePath) == "/" {
  426. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  427. return false
  428. }
  429. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  430. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  431. return false
  432. }
  433. if !c.User.IsFileAllowed(virtualSourcePath) || !c.User.IsFileAllowed(virtualTargetPath) {
  434. if fi != nil && fi.Mode().IsRegular() {
  435. c.Log(logger.LevelDebug, "renaming file is not allowed, source: %#v target: %#v",
  436. virtualSourcePath, virtualTargetPath)
  437. return false
  438. }
  439. }
  440. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSourcePath)) &&
  441. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualTargetPath)) {
  442. return true
  443. }
  444. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSourcePath)) {
  445. return false
  446. }
  447. if fi != nil {
  448. if fi.IsDir() {
  449. return c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualTargetPath))
  450. } else if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
  451. return c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath))
  452. }
  453. }
  454. return c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualTargetPath))
  455. }
  456. func (c *BaseConnection) hasSpaceForRename(virtualSourcePath, virtualTargetPath string, initialSize int64,
  457. fsSourcePath string) bool {
  458. if dataprovider.GetQuotaTracking() == 0 {
  459. return true
  460. }
  461. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  462. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  463. if errSrc != nil && errDst != nil {
  464. // rename inside the user home dir
  465. return true
  466. }
  467. if errSrc == nil && errDst == nil {
  468. // rename between virtual folders
  469. if sourceFolder.MappedPath == dstFolder.MappedPath {
  470. // rename inside the same virtual folder
  471. return true
  472. }
  473. }
  474. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  475. // rename between user root dir and a virtual folder included in user quota
  476. return true
  477. }
  478. quotaResult := c.HasSpace(true, virtualTargetPath)
  479. return c.hasSpaceForCrossRename(quotaResult, initialSize, fsSourcePath)
  480. }
  481. // hasSpaceForCrossRename checks the quota after a rename between different folders
  482. func (c *BaseConnection) hasSpaceForCrossRename(quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  483. if !quotaResult.HasSpace && initialSize == -1 {
  484. // we are over quota and this is not a file replace
  485. return false
  486. }
  487. fi, err := c.Fs.Lstat(sourcePath)
  488. if err != nil {
  489. c.Log(logger.LevelWarn, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  490. return false
  491. }
  492. var sizeDiff int64
  493. var filesDiff int
  494. if fi.Mode().IsRegular() {
  495. sizeDiff = fi.Size()
  496. filesDiff = 1
  497. if initialSize != -1 {
  498. sizeDiff -= initialSize
  499. filesDiff = 0
  500. }
  501. } else if fi.IsDir() {
  502. filesDiff, sizeDiff, err = c.Fs.GetDirSize(sourcePath)
  503. if err != nil {
  504. c.Log(logger.LevelWarn, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  505. return false
  506. }
  507. }
  508. if !quotaResult.HasSpace && initialSize != -1 {
  509. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  510. if quotaResult.QuotaSize == 0 {
  511. return true
  512. }
  513. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  514. sourcePath, quotaResult.UsedSize, sizeDiff)
  515. quotaResult.UsedSize += sizeDiff
  516. return quotaResult.GetRemainingSize() >= 0
  517. }
  518. if quotaResult.QuotaFiles > 0 {
  519. remainingFiles := quotaResult.GetRemainingFiles()
  520. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  521. remainingFiles, filesDiff)
  522. if remainingFiles < filesDiff {
  523. return false
  524. }
  525. }
  526. if quotaResult.QuotaSize > 0 {
  527. remainingSize := quotaResult.GetRemainingSize()
  528. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  529. remainingSize, sizeDiff)
  530. if remainingSize < sizeDiff {
  531. return false
  532. }
  533. }
  534. return true
  535. }
  536. // HasSpace checks user's quota usage
  537. func (c *BaseConnection) HasSpace(checkFiles bool, requestPath string) vfs.QuotaCheckResult {
  538. result := vfs.QuotaCheckResult{
  539. HasSpace: true,
  540. AllowedSize: 0,
  541. AllowedFiles: 0,
  542. UsedSize: 0,
  543. UsedFiles: 0,
  544. QuotaSize: 0,
  545. QuotaFiles: 0,
  546. }
  547. if dataprovider.GetQuotaTracking() == 0 {
  548. return result
  549. }
  550. var err error
  551. var vfolder vfs.VirtualFolder
  552. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  553. if err == nil && !vfolder.IsIncludedInUserQuota() {
  554. if vfolder.HasNoQuotaRestrictions(checkFiles) {
  555. return result
  556. }
  557. result.QuotaSize = vfolder.QuotaSize
  558. result.QuotaFiles = vfolder.QuotaFiles
  559. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.MappedPath)
  560. } else {
  561. if c.User.HasNoQuotaRestrictions(checkFiles) {
  562. return result
  563. }
  564. result.QuotaSize = c.User.QuotaSize
  565. result.QuotaFiles = c.User.QuotaFiles
  566. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedQuota(c.User.Username)
  567. }
  568. if err != nil {
  569. c.Log(logger.LevelWarn, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  570. result.HasSpace = false
  571. return result
  572. }
  573. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  574. result.AllowedSize = result.QuotaSize - result.UsedSize
  575. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  576. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  577. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  578. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  579. result.HasSpace = false
  580. return result
  581. }
  582. return result
  583. }
  584. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  585. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  586. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  587. if errSrc != nil && errDst != nil {
  588. return false
  589. }
  590. if errSrc == nil && errDst == nil {
  591. return sourceFolder.MappedPath != dstFolder.MappedPath
  592. }
  593. return true
  594. }
  595. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder vfs.VirtualFolder, initialSize,
  596. filesSize int64, numFiles int) {
  597. if sourceFolder.MappedPath == dstFolder.MappedPath {
  598. // both files are inside the same virtual folder
  599. if initialSize != -1 {
  600. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  601. if dstFolder.IsIncludedInUserQuota() {
  602. dataprovider.UpdateUserQuota(c.User, -numFiles, -initialSize, false) //nolint:errcheck
  603. }
  604. }
  605. return
  606. }
  607. // files are inside different virtual folders
  608. dataprovider.UpdateVirtualFolderQuota(sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  609. if sourceFolder.IsIncludedInUserQuota() {
  610. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  611. }
  612. if initialSize == -1 {
  613. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  614. if dstFolder.IsIncludedInUserQuota() {
  615. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  616. }
  617. } else {
  618. // we cannot have a directory here, initialSize != -1 only for files
  619. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  620. if dstFolder.IsIncludedInUserQuota() {
  621. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  622. }
  623. }
  624. }
  625. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  626. // move between a virtual folder and the user home dir
  627. dataprovider.UpdateVirtualFolderQuota(sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  628. if sourceFolder.IsIncludedInUserQuota() {
  629. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  630. }
  631. if initialSize == -1 {
  632. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  633. } else {
  634. // we cannot have a directory here, initialSize != -1 only for files
  635. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  636. }
  637. }
  638. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  639. // move between the user home dir and a virtual folder
  640. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  641. if initialSize == -1 {
  642. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  643. if dstFolder.IsIncludedInUserQuota() {
  644. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  645. }
  646. } else {
  647. // we cannot have a directory here, initialSize != -1 only for files
  648. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  649. if dstFolder.IsIncludedInUserQuota() {
  650. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  651. }
  652. }
  653. }
  654. func (c *BaseConnection) updateQuotaAfterRename(virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  655. // we don't allow to overwrite an existing directory so targetPath can be:
  656. // - a new file, a symlink is as a new file here
  657. // - a file overwriting an existing one
  658. // - a new directory
  659. // initialSize != -1 only when overwriting files
  660. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  661. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  662. if errSrc != nil && errDst != nil {
  663. // both files are contained inside the user home dir
  664. if initialSize != -1 {
  665. // we cannot have a directory here
  666. dataprovider.UpdateUserQuota(c.User, -1, -initialSize, false) //nolint:errcheck
  667. }
  668. return nil
  669. }
  670. filesSize := int64(0)
  671. numFiles := 1
  672. if fi, err := c.Fs.Stat(targetPath); err == nil {
  673. if fi.Mode().IsDir() {
  674. numFiles, filesSize, err = c.Fs.GetDirSize(targetPath)
  675. if err != nil {
  676. c.Log(logger.LevelWarn, "failed to update quota after rename, error scanning moved folder %#v: %v",
  677. targetPath, err)
  678. return err
  679. }
  680. } else {
  681. filesSize = fi.Size()
  682. }
  683. } else {
  684. c.Log(logger.LevelWarn, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  685. return err
  686. }
  687. if errSrc == nil && errDst == nil {
  688. c.updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder, initialSize, filesSize, numFiles)
  689. }
  690. if errSrc == nil && errDst != nil {
  691. c.updateQuotaMoveFromVFolder(sourceFolder, initialSize, filesSize, numFiles)
  692. }
  693. if errSrc != nil && errDst == nil {
  694. c.updateQuotaMoveToVFolder(dstFolder, initialSize, filesSize, numFiles)
  695. }
  696. return nil
  697. }
  698. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  699. func (c *BaseConnection) GetPermissionDeniedError() error {
  700. switch c.protocol {
  701. case ProtocolSFTP:
  702. return sftp.ErrSSHFxPermissionDenied
  703. default:
  704. return ErrPermissionDenied
  705. }
  706. }
  707. // GetNotExistError returns an appropriate not exist error for the connection protocol
  708. func (c *BaseConnection) GetNotExistError() error {
  709. switch c.protocol {
  710. case ProtocolSFTP:
  711. return sftp.ErrSSHFxNoSuchFile
  712. default:
  713. return ErrNotExist
  714. }
  715. }
  716. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  717. func (c *BaseConnection) GetOpUnsupportedError() error {
  718. switch c.protocol {
  719. case ProtocolSFTP:
  720. return sftp.ErrSSHFxOpUnsupported
  721. default:
  722. return ErrOpUnsupported
  723. }
  724. }
  725. // GetGenericError returns an appropriate generic error for the connection protocol
  726. func (c *BaseConnection) GetGenericError() error {
  727. switch c.protocol {
  728. case ProtocolSFTP:
  729. return sftp.ErrSSHFxFailure
  730. default:
  731. return ErrGenericFailure
  732. }
  733. }
  734. // GetFsError converts a filesystem error to a protocol error
  735. func (c *BaseConnection) GetFsError(err error) error {
  736. if c.Fs.IsNotExist(err) {
  737. return c.GetNotExistError()
  738. } else if c.Fs.IsPermission(err) {
  739. return c.GetPermissionDeniedError()
  740. } else if err != nil {
  741. return c.GetGenericError()
  742. }
  743. return nil
  744. }