connection.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 == 0 {
  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 != 0 {
  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. func (c *BaseConnection) ignoreSetStat() bool {
  406. if Config.SetstatMode == 1 {
  407. return true
  408. }
  409. if Config.SetstatMode == 2 && !vfs.IsLocalOsFs(c.Fs) {
  410. return true
  411. }
  412. return false
  413. }
  414. func (c *BaseConnection) handleChmod(fsPath, pathForPerms string, attributes *StatAttributes) error {
  415. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  416. return c.GetPermissionDeniedError()
  417. }
  418. if c.ignoreSetStat() {
  419. return nil
  420. }
  421. if err := c.Fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  422. c.Log(logger.LevelWarn, "failed to chmod path %#v, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  423. return c.GetFsError(err)
  424. }
  425. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  426. -1, -1, "", "", "", -1)
  427. return nil
  428. }
  429. func (c *BaseConnection) handleChown(fsPath, pathForPerms string, attributes *StatAttributes) error {
  430. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  431. return c.GetPermissionDeniedError()
  432. }
  433. if c.ignoreSetStat() {
  434. return nil
  435. }
  436. if err := c.Fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  437. c.Log(logger.LevelWarn, "failed to chown path %#v, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  438. attributes.GID, err)
  439. return c.GetFsError(err)
  440. }
  441. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  442. "", "", "", -1)
  443. return nil
  444. }
  445. func (c *BaseConnection) handleChtimes(fsPath, pathForPerms string, attributes *StatAttributes) error {
  446. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  447. return c.GetPermissionDeniedError()
  448. }
  449. if c.ignoreSetStat() {
  450. return nil
  451. }
  452. if err := c.Fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime); err != nil {
  453. c.Log(logger.LevelWarn, "failed to chtimes for path %#v, access time: %v, modification time: %v, err: %+v",
  454. fsPath, attributes.Atime, attributes.Mtime, err)
  455. return c.GetFsError(err)
  456. }
  457. accessTimeString := attributes.Atime.Format(chtimesFormat)
  458. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  459. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  460. accessTimeString, modificationTimeString, "", -1)
  461. return nil
  462. }
  463. // SetStat set StatAttributes for the specified fsPath
  464. func (c *BaseConnection) SetStat(fsPath, virtualPath string, attributes *StatAttributes) error {
  465. pathForPerms := c.getPathForSetStatPerms(fsPath, virtualPath)
  466. if attributes.Flags&StatAttrPerms != 0 {
  467. return c.handleChmod(fsPath, pathForPerms, attributes)
  468. }
  469. if attributes.Flags&StatAttrUIDGID != 0 {
  470. return c.handleChown(fsPath, pathForPerms, attributes)
  471. }
  472. if attributes.Flags&StatAttrTimes != 0 {
  473. return c.handleChtimes(fsPath, pathForPerms, attributes)
  474. }
  475. if attributes.Flags&StatAttrSize != 0 {
  476. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  477. return c.GetPermissionDeniedError()
  478. }
  479. if err := c.truncateFile(fsPath, virtualPath, attributes.Size); err != nil {
  480. c.Log(logger.LevelWarn, "failed to truncate path %#v, size: %v, err: %+v", fsPath, attributes.Size, err)
  481. return c.GetFsError(err)
  482. }
  483. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", attributes.Size)
  484. }
  485. return nil
  486. }
  487. func (c *BaseConnection) truncateFile(fsPath, virtualPath string, size int64) error {
  488. // check first if we have an open transfer for the given path and try to truncate the file already opened
  489. // if we found no transfer we truncate by path.
  490. var initialSize int64
  491. var err error
  492. initialSize, err = c.truncateOpenHandle(fsPath, size)
  493. if err == errNoTransfer {
  494. c.Log(logger.LevelDebug, "file path %#v not found in active transfers, execute trucate by path", fsPath)
  495. var info os.FileInfo
  496. info, err = c.Fs.Stat(fsPath)
  497. if err != nil {
  498. return err
  499. }
  500. initialSize = info.Size()
  501. err = c.Fs.Truncate(fsPath, size)
  502. }
  503. if err == nil && vfs.IsLocalOsFs(c.Fs) {
  504. sizeDiff := initialSize - size
  505. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  506. if err == nil {
  507. dataprovider.UpdateVirtualFolderQuota(vfolder.BaseVirtualFolder, 0, -sizeDiff, false) //nolint:errcheck
  508. if vfolder.IsIncludedInUserQuota() {
  509. dataprovider.UpdateUserQuota(c.User, 0, -sizeDiff, false) //nolint:errcheck
  510. }
  511. } else {
  512. dataprovider.UpdateUserQuota(c.User, 0, -sizeDiff, false) //nolint:errcheck
  513. }
  514. }
  515. return err
  516. }
  517. func (c *BaseConnection) checkRecursiveRenameDirPermissions(sourcePath, targetPath string) error {
  518. dstPerms := []string{
  519. dataprovider.PermCreateDirs,
  520. dataprovider.PermUpload,
  521. dataprovider.PermCreateSymlinks,
  522. }
  523. err := c.Fs.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  524. if err != nil {
  525. return err
  526. }
  527. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  528. virtualSrcPath := c.Fs.GetRelativePath(walkedPath)
  529. virtualDstPath := c.Fs.GetRelativePath(dstPath)
  530. // walk scans the directory tree in order, checking the parent directory permissions we are sure that all contents
  531. // inside the parent path was checked. If the current dir has no subdirs with defined permissions inside it
  532. // and it has all the possible permissions we can stop scanning
  533. if !c.User.HasPermissionsInside(path.Dir(virtualSrcPath)) && !c.User.HasPermissionsInside(path.Dir(virtualDstPath)) {
  534. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSrcPath)) &&
  535. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualDstPath)) {
  536. return ErrSkipPermissionsCheck
  537. }
  538. if c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSrcPath)) &&
  539. c.User.HasPerms(dstPerms, path.Dir(virtualDstPath)) {
  540. return ErrSkipPermissionsCheck
  541. }
  542. }
  543. if !c.isRenamePermitted(walkedPath, virtualSrcPath, virtualDstPath, info) {
  544. c.Log(logger.LevelInfo, "rename %#v -> %#v is not allowed, virtual destination path: %#v",
  545. walkedPath, dstPath, virtualDstPath)
  546. return os.ErrPermission
  547. }
  548. return nil
  549. })
  550. if err == ErrSkipPermissionsCheck {
  551. err = nil
  552. }
  553. return err
  554. }
  555. func (c *BaseConnection) isRenamePermitted(fsSourcePath, virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  556. if c.Fs.GetRelativePath(fsSourcePath) == "/" {
  557. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  558. return false
  559. }
  560. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  561. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  562. return false
  563. }
  564. if !c.User.IsFileAllowed(virtualSourcePath) || !c.User.IsFileAllowed(virtualTargetPath) {
  565. if fi != nil && fi.Mode().IsRegular() {
  566. c.Log(logger.LevelDebug, "renaming file is not allowed, source: %#v target: %#v",
  567. virtualSourcePath, virtualTargetPath)
  568. return false
  569. }
  570. }
  571. if c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualSourcePath)) &&
  572. c.User.HasPerm(dataprovider.PermRename, path.Dir(virtualTargetPath)) {
  573. return true
  574. }
  575. if !c.User.HasPerm(dataprovider.PermDelete, path.Dir(virtualSourcePath)) {
  576. return false
  577. }
  578. if fi != nil {
  579. if fi.IsDir() {
  580. return c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualTargetPath))
  581. } else if fi.Mode()&os.ModeSymlink != 0 {
  582. return c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath))
  583. }
  584. }
  585. return c.User.HasPerm(dataprovider.PermUpload, path.Dir(virtualTargetPath))
  586. }
  587. func (c *BaseConnection) hasSpaceForRename(virtualSourcePath, virtualTargetPath string, initialSize int64,
  588. fsSourcePath string) bool {
  589. if dataprovider.GetQuotaTracking() == 0 {
  590. return true
  591. }
  592. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  593. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  594. if errSrc != nil && errDst != nil {
  595. // rename inside the user home dir
  596. return true
  597. }
  598. if errSrc == nil && errDst == nil {
  599. // rename between virtual folders
  600. if sourceFolder.MappedPath == dstFolder.MappedPath {
  601. // rename inside the same virtual folder
  602. return true
  603. }
  604. }
  605. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  606. // rename between user root dir and a virtual folder included in user quota
  607. return true
  608. }
  609. quotaResult := c.HasSpace(true, virtualTargetPath)
  610. return c.hasSpaceForCrossRename(quotaResult, initialSize, fsSourcePath)
  611. }
  612. // hasSpaceForCrossRename checks the quota after a rename between different folders
  613. func (c *BaseConnection) hasSpaceForCrossRename(quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  614. if !quotaResult.HasSpace && initialSize == -1 {
  615. // we are over quota and this is not a file replace
  616. return false
  617. }
  618. fi, err := c.Fs.Lstat(sourcePath)
  619. if err != nil {
  620. c.Log(logger.LevelWarn, "cross rename denied, stat error for path %#v: %v", sourcePath, err)
  621. return false
  622. }
  623. var sizeDiff int64
  624. var filesDiff int
  625. if fi.Mode().IsRegular() {
  626. sizeDiff = fi.Size()
  627. filesDiff = 1
  628. if initialSize != -1 {
  629. sizeDiff -= initialSize
  630. filesDiff = 0
  631. }
  632. } else if fi.IsDir() {
  633. filesDiff, sizeDiff, err = c.Fs.GetDirSize(sourcePath)
  634. if err != nil {
  635. c.Log(logger.LevelWarn, "cross rename denied, error getting size for directory %#v: %v", sourcePath, err)
  636. return false
  637. }
  638. }
  639. if !quotaResult.HasSpace && initialSize != -1 {
  640. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  641. if quotaResult.QuotaSize == 0 {
  642. return true
  643. }
  644. c.Log(logger.LevelDebug, "cross rename overwrite, source %#v, used size %v, size to add %v",
  645. sourcePath, quotaResult.UsedSize, sizeDiff)
  646. quotaResult.UsedSize += sizeDiff
  647. return quotaResult.GetRemainingSize() >= 0
  648. }
  649. if quotaResult.QuotaFiles > 0 {
  650. remainingFiles := quotaResult.GetRemainingFiles()
  651. c.Log(logger.LevelDebug, "cross rename, source %#v remaining file %v to add %v", sourcePath,
  652. remainingFiles, filesDiff)
  653. if remainingFiles < filesDiff {
  654. return false
  655. }
  656. }
  657. if quotaResult.QuotaSize > 0 {
  658. remainingSize := quotaResult.GetRemainingSize()
  659. c.Log(logger.LevelDebug, "cross rename, source %#v remaining size %v to add %v", sourcePath,
  660. remainingSize, sizeDiff)
  661. if remainingSize < sizeDiff {
  662. return false
  663. }
  664. }
  665. return true
  666. }
  667. // GetMaxWriteSize returns the allowed size for an upload or an error
  668. // if no enough size is available for a resume/append
  669. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64) (int64, error) {
  670. maxWriteSize := quotaResult.GetRemainingSize()
  671. if isResume {
  672. if !c.Fs.IsUploadResumeSupported() {
  673. return 0, c.GetOpUnsupportedError()
  674. }
  675. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  676. return 0, ErrQuotaExceeded
  677. }
  678. if c.User.Filters.MaxUploadFileSize > 0 {
  679. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  680. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  681. maxWriteSize = maxUploadSize
  682. }
  683. }
  684. } else {
  685. if maxWriteSize > 0 {
  686. maxWriteSize += fileSize
  687. }
  688. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  689. maxWriteSize = c.User.Filters.MaxUploadFileSize
  690. }
  691. }
  692. return maxWriteSize, nil
  693. }
  694. // HasSpace checks user's quota usage
  695. func (c *BaseConnection) HasSpace(checkFiles bool, requestPath string) vfs.QuotaCheckResult {
  696. result := vfs.QuotaCheckResult{
  697. HasSpace: true,
  698. AllowedSize: 0,
  699. AllowedFiles: 0,
  700. UsedSize: 0,
  701. UsedFiles: 0,
  702. QuotaSize: 0,
  703. QuotaFiles: 0,
  704. }
  705. if dataprovider.GetQuotaTracking() == 0 {
  706. return result
  707. }
  708. var err error
  709. var vfolder vfs.VirtualFolder
  710. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  711. if err == nil && !vfolder.IsIncludedInUserQuota() {
  712. if vfolder.HasNoQuotaRestrictions(checkFiles) {
  713. return result
  714. }
  715. result.QuotaSize = vfolder.QuotaSize
  716. result.QuotaFiles = vfolder.QuotaFiles
  717. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.MappedPath)
  718. } else {
  719. if c.User.HasNoQuotaRestrictions(checkFiles) {
  720. return result
  721. }
  722. result.QuotaSize = c.User.QuotaSize
  723. result.QuotaFiles = c.User.QuotaFiles
  724. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedQuota(c.User.Username)
  725. }
  726. if err != nil {
  727. c.Log(logger.LevelWarn, "error getting used quota for %#v request path %#v: %v", c.User.Username, requestPath, err)
  728. result.HasSpace = false
  729. return result
  730. }
  731. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  732. result.AllowedSize = result.QuotaSize - result.UsedSize
  733. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  734. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  735. c.Log(logger.LevelDebug, "quota exceed for user %#v, request path %#v, num files: %v/%v, size: %v/%v check files: %v",
  736. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  737. result.HasSpace = false
  738. return result
  739. }
  740. return result
  741. }
  742. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  743. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  744. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  745. if errSrc != nil && errDst != nil {
  746. return false
  747. }
  748. if errSrc == nil && errDst == nil {
  749. return sourceFolder.MappedPath != dstFolder.MappedPath
  750. }
  751. return true
  752. }
  753. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder vfs.VirtualFolder, initialSize,
  754. filesSize int64, numFiles int) {
  755. if sourceFolder.MappedPath == dstFolder.MappedPath {
  756. // both files are inside the same virtual folder
  757. if initialSize != -1 {
  758. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, -numFiles, -initialSize, false) //nolint:errcheck
  759. if dstFolder.IsIncludedInUserQuota() {
  760. dataprovider.UpdateUserQuota(c.User, -numFiles, -initialSize, false) //nolint:errcheck
  761. }
  762. }
  763. return
  764. }
  765. // files are inside different virtual folders
  766. dataprovider.UpdateVirtualFolderQuota(sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  767. if sourceFolder.IsIncludedInUserQuota() {
  768. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  769. }
  770. if initialSize == -1 {
  771. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  772. if dstFolder.IsIncludedInUserQuota() {
  773. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  774. }
  775. } else {
  776. // we cannot have a directory here, initialSize != -1 only for files
  777. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  778. if dstFolder.IsIncludedInUserQuota() {
  779. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  780. }
  781. }
  782. }
  783. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  784. // move between a virtual folder and the user home dir
  785. dataprovider.UpdateVirtualFolderQuota(sourceFolder.BaseVirtualFolder, -numFiles, -filesSize, false) //nolint:errcheck
  786. if sourceFolder.IsIncludedInUserQuota() {
  787. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  788. }
  789. if initialSize == -1 {
  790. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  791. } else {
  792. // we cannot have a directory here, initialSize != -1 only for files
  793. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  794. }
  795. }
  796. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  797. // move between the user home dir and a virtual folder
  798. dataprovider.UpdateUserQuota(c.User, -numFiles, -filesSize, false) //nolint:errcheck
  799. if initialSize == -1 {
  800. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, numFiles, filesSize, false) //nolint:errcheck
  801. if dstFolder.IsIncludedInUserQuota() {
  802. dataprovider.UpdateUserQuota(c.User, numFiles, filesSize, false) //nolint:errcheck
  803. }
  804. } else {
  805. // we cannot have a directory here, initialSize != -1 only for files
  806. dataprovider.UpdateVirtualFolderQuota(dstFolder.BaseVirtualFolder, 0, filesSize-initialSize, false) //nolint:errcheck
  807. if dstFolder.IsIncludedInUserQuota() {
  808. dataprovider.UpdateUserQuota(c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  809. }
  810. }
  811. }
  812. func (c *BaseConnection) updateQuotaAfterRename(virtualSourcePath, virtualTargetPath, targetPath string, initialSize int64) error {
  813. // we don't allow to overwrite an existing directory so targetPath can be:
  814. // - a new file, a symlink is as a new file here
  815. // - a file overwriting an existing one
  816. // - a new directory
  817. // initialSize != -1 only when overwriting files
  818. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  819. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  820. if errSrc != nil && errDst != nil {
  821. // both files are contained inside the user home dir
  822. if initialSize != -1 {
  823. // we cannot have a directory here
  824. dataprovider.UpdateUserQuota(c.User, -1, -initialSize, false) //nolint:errcheck
  825. }
  826. return nil
  827. }
  828. filesSize := int64(0)
  829. numFiles := 1
  830. if fi, err := c.Fs.Stat(targetPath); err == nil {
  831. if fi.Mode().IsDir() {
  832. numFiles, filesSize, err = c.Fs.GetDirSize(targetPath)
  833. if err != nil {
  834. c.Log(logger.LevelWarn, "failed to update quota after rename, error scanning moved folder %#v: %v",
  835. targetPath, err)
  836. return err
  837. }
  838. } else {
  839. filesSize = fi.Size()
  840. }
  841. } else {
  842. c.Log(logger.LevelWarn, "failed to update quota after rename, file %#v stat error: %+v", targetPath, err)
  843. return err
  844. }
  845. if errSrc == nil && errDst == nil {
  846. c.updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder, initialSize, filesSize, numFiles)
  847. }
  848. if errSrc == nil && errDst != nil {
  849. c.updateQuotaMoveFromVFolder(sourceFolder, initialSize, filesSize, numFiles)
  850. }
  851. if errSrc != nil && errDst == nil {
  852. c.updateQuotaMoveToVFolder(dstFolder, initialSize, filesSize, numFiles)
  853. }
  854. return nil
  855. }
  856. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  857. func (c *BaseConnection) GetPermissionDeniedError() error {
  858. switch c.protocol {
  859. case ProtocolSFTP:
  860. return sftp.ErrSSHFxPermissionDenied
  861. case ProtocolWebDAV:
  862. return os.ErrPermission
  863. default:
  864. return ErrPermissionDenied
  865. }
  866. }
  867. // GetNotExistError returns an appropriate not exist error for the connection protocol
  868. func (c *BaseConnection) GetNotExistError() error {
  869. switch c.protocol {
  870. case ProtocolSFTP:
  871. return sftp.ErrSSHFxNoSuchFile
  872. case ProtocolWebDAV:
  873. return os.ErrNotExist
  874. default:
  875. return ErrNotExist
  876. }
  877. }
  878. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  879. func (c *BaseConnection) GetOpUnsupportedError() error {
  880. switch c.protocol {
  881. case ProtocolSFTP:
  882. return sftp.ErrSSHFxOpUnsupported
  883. default:
  884. return ErrOpUnsupported
  885. }
  886. }
  887. // GetGenericError returns an appropriate generic error for the connection protocol
  888. func (c *BaseConnection) GetGenericError(err error) error {
  889. switch c.protocol {
  890. case ProtocolSFTP:
  891. return sftp.ErrSSHFxFailure
  892. default:
  893. if err == ErrPermissionDenied || err == ErrNotExist || err == ErrOpUnsupported || err == ErrQuotaExceeded {
  894. return err
  895. }
  896. return ErrGenericFailure
  897. }
  898. }
  899. // GetFsError converts a filesystem error to a protocol error
  900. func (c *BaseConnection) GetFsError(err error) error {
  901. if c.Fs.IsNotExist(err) {
  902. return c.GetNotExistError()
  903. } else if c.Fs.IsPermission(err) {
  904. return c.GetPermissionDeniedError()
  905. } else if c.Fs.IsNotSupported(err) {
  906. return c.GetOpUnsupportedError()
  907. } else if err != nil {
  908. return c.GetGenericError(err)
  909. }
  910. return nil
  911. }