connection.go 34 KB

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