connection.go 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  1. // Copyright (C) 2019 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package common
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/fs"
  20. "os"
  21. "path"
  22. "slices"
  23. "strings"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. ftpserver "github.com/fclairamb/ftpserverlib"
  28. "github.com/pkg/sftp"
  29. "github.com/sftpgo/sdk"
  30. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  31. "github.com/drakkan/sftpgo/v2/internal/logger"
  32. "github.com/drakkan/sftpgo/v2/internal/util"
  33. "github.com/drakkan/sftpgo/v2/internal/vfs"
  34. )
  35. // BaseConnection defines common fields for a connection using any supported protocol
  36. type BaseConnection struct {
  37. // last activity for this connection.
  38. // Since this field is accessed atomically we put it as first element of the struct to achieve 64 bit alignment
  39. lastActivity atomic.Int64
  40. uploadDone atomic.Bool
  41. downloadDone atomic.Bool
  42. // unique ID for a transfer.
  43. // This field is accessed atomically so we put it at the beginning of the struct to achieve 64 bit alignment
  44. transferID atomic.Int64
  45. // Unique identifier for the connection
  46. ID string
  47. // user associated with this connection if any
  48. User dataprovider.User
  49. // start time for this connection
  50. startTime time.Time
  51. protocol string
  52. remoteAddr string
  53. localAddr string
  54. sync.RWMutex
  55. activeTransfers []ActiveTransfer
  56. }
  57. // NewBaseConnection returns a new BaseConnection
  58. func NewBaseConnection(id, protocol, localAddr, remoteAddr string, user dataprovider.User) *BaseConnection {
  59. connID := id
  60. if slices.Contains(supportedProtocols, protocol) {
  61. connID = fmt.Sprintf("%s_%s", protocol, id)
  62. }
  63. user.UploadBandwidth, user.DownloadBandwidth = user.GetBandwidthForIP(util.GetIPFromRemoteAddress(remoteAddr), connID)
  64. c := &BaseConnection{
  65. ID: connID,
  66. User: user,
  67. startTime: time.Now(),
  68. protocol: protocol,
  69. localAddr: localAddr,
  70. remoteAddr: remoteAddr,
  71. }
  72. c.transferID.Store(0)
  73. c.lastActivity.Store(time.Now().UnixNano())
  74. return c
  75. }
  76. // Log outputs a log entry to the configured logger
  77. func (c *BaseConnection) Log(level logger.LogLevel, format string, v ...any) {
  78. logger.Log(level, c.protocol, c.ID, format, v...)
  79. }
  80. // GetTransferID returns an unique transfer ID for this connection
  81. func (c *BaseConnection) GetTransferID() int64 {
  82. return c.transferID.Add(1)
  83. }
  84. // GetID returns the connection ID
  85. func (c *BaseConnection) GetID() string {
  86. return c.ID
  87. }
  88. // GetUsername returns the authenticated username associated with this connection if any
  89. func (c *BaseConnection) GetUsername() string {
  90. return c.User.Username
  91. }
  92. // GetRole returns the role for the user associated with this connection
  93. func (c *BaseConnection) GetRole() string {
  94. return c.User.Role
  95. }
  96. // GetMaxSessions returns the maximum number of concurrent sessions allowed
  97. func (c *BaseConnection) GetMaxSessions() int {
  98. return c.User.MaxSessions
  99. }
  100. // isAccessAllowed returns true if the user's access conditions are met
  101. func (c *BaseConnection) isAccessAllowed() bool {
  102. if err := c.User.CheckLoginConditions(); err != nil {
  103. return false
  104. }
  105. return true
  106. }
  107. // GetProtocol returns the protocol for the connection
  108. func (c *BaseConnection) GetProtocol() string {
  109. return c.protocol
  110. }
  111. // GetRemoteIP returns the remote ip address
  112. func (c *BaseConnection) GetRemoteIP() string {
  113. return util.GetIPFromRemoteAddress(c.remoteAddr)
  114. }
  115. // SetProtocol sets the protocol for this connection
  116. func (c *BaseConnection) SetProtocol(protocol string) {
  117. c.protocol = protocol
  118. if slices.Contains(supportedProtocols, c.protocol) {
  119. c.ID = fmt.Sprintf("%v_%v", c.protocol, c.ID)
  120. }
  121. }
  122. // GetConnectionTime returns the initial connection time
  123. func (c *BaseConnection) GetConnectionTime() time.Time {
  124. return c.startTime
  125. }
  126. // UpdateLastActivity updates last activity for this connection
  127. func (c *BaseConnection) UpdateLastActivity() {
  128. c.lastActivity.Store(time.Now().UnixNano())
  129. }
  130. // GetLastActivity returns the last connection activity
  131. func (c *BaseConnection) GetLastActivity() time.Time {
  132. return time.Unix(0, c.lastActivity.Load())
  133. }
  134. // CloseFS closes the underlying fs
  135. func (c *BaseConnection) CloseFS() error {
  136. return c.User.CloseFs()
  137. }
  138. // AddTransfer associates a new transfer to this connection
  139. func (c *BaseConnection) AddTransfer(t ActiveTransfer) {
  140. c.Lock()
  141. defer c.Unlock()
  142. c.activeTransfers = append(c.activeTransfers, t)
  143. c.Log(logger.LevelDebug, "transfer added, id: %v, active transfers: %v", t.GetID(), len(c.activeTransfers))
  144. if t.HasSizeLimit() {
  145. folderName := ""
  146. if t.GetType() == TransferUpload {
  147. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(t.GetVirtualPath()))
  148. if err == nil {
  149. if !vfolder.IsIncludedInUserQuota() {
  150. folderName = vfolder.Name
  151. }
  152. }
  153. }
  154. go transfersChecker.AddTransfer(dataprovider.ActiveTransfer{
  155. ID: t.GetID(),
  156. Type: t.GetType(),
  157. ConnID: c.ID,
  158. Username: c.GetUsername(),
  159. FolderName: folderName,
  160. IP: c.GetRemoteIP(),
  161. TruncatedSize: t.GetTruncatedSize(),
  162. CreatedAt: util.GetTimeAsMsSinceEpoch(time.Now()),
  163. UpdatedAt: util.GetTimeAsMsSinceEpoch(time.Now()),
  164. })
  165. }
  166. }
  167. // RemoveTransfer removes the specified transfer from the active ones
  168. func (c *BaseConnection) RemoveTransfer(t ActiveTransfer) {
  169. c.Lock()
  170. defer c.Unlock()
  171. if t.HasSizeLimit() {
  172. go transfersChecker.RemoveTransfer(t.GetID(), c.ID)
  173. }
  174. for idx, transfer := range c.activeTransfers {
  175. if transfer.GetID() == t.GetID() {
  176. lastIdx := len(c.activeTransfers) - 1
  177. c.activeTransfers[idx] = c.activeTransfers[lastIdx]
  178. c.activeTransfers[lastIdx] = nil
  179. c.activeTransfers = c.activeTransfers[:lastIdx]
  180. c.Log(logger.LevelDebug, "transfer removed, id: %v active transfers: %v", t.GetID(), len(c.activeTransfers))
  181. return
  182. }
  183. }
  184. c.Log(logger.LevelWarn, "transfer to remove with id %v not found!", t.GetID())
  185. }
  186. // SignalTransferClose makes the transfer fail on the next read/write with the
  187. // specified error
  188. func (c *BaseConnection) SignalTransferClose(transferID int64, err error) {
  189. c.RLock()
  190. defer c.RUnlock()
  191. for _, t := range c.activeTransfers {
  192. if t.GetID() == transferID {
  193. c.Log(logger.LevelInfo, "signal transfer close for transfer id %v", transferID)
  194. t.SignalClose(err)
  195. }
  196. }
  197. }
  198. // GetTransfers returns the active transfers
  199. func (c *BaseConnection) GetTransfers() []ConnectionTransfer {
  200. c.RLock()
  201. defer c.RUnlock()
  202. transfers := make([]ConnectionTransfer, 0, len(c.activeTransfers))
  203. for _, t := range c.activeTransfers {
  204. var operationType string
  205. switch t.GetType() {
  206. case TransferDownload:
  207. operationType = operationDownload
  208. case TransferUpload:
  209. operationType = operationUpload
  210. }
  211. transfers = append(transfers, ConnectionTransfer{
  212. ID: t.GetID(),
  213. OperationType: operationType,
  214. StartTime: util.GetTimeAsMsSinceEpoch(t.GetStartTime()),
  215. Size: t.GetSize(),
  216. VirtualPath: t.GetVirtualPath(),
  217. HasSizeLimit: t.HasSizeLimit(),
  218. ULSize: t.GetUploadedSize(),
  219. DLSize: t.GetDownloadedSize(),
  220. })
  221. }
  222. return transfers
  223. }
  224. // SignalTransfersAbort signals to the active transfers to exit as soon as possible
  225. func (c *BaseConnection) SignalTransfersAbort() error {
  226. c.RLock()
  227. defer c.RUnlock()
  228. if len(c.activeTransfers) == 0 {
  229. return errors.New("no active transfer found")
  230. }
  231. for _, t := range c.activeTransfers {
  232. t.SignalClose(ErrTransferAborted)
  233. }
  234. return nil
  235. }
  236. func (c *BaseConnection) getRealFsPath(fsPath string) string {
  237. c.RLock()
  238. defer c.RUnlock()
  239. for _, t := range c.activeTransfers {
  240. if p := t.GetRealFsPath(fsPath); p != "" {
  241. return p
  242. }
  243. }
  244. return fsPath
  245. }
  246. func (c *BaseConnection) setTimes(fsPath string, atime time.Time, mtime time.Time) bool {
  247. c.RLock()
  248. defer c.RUnlock()
  249. for _, t := range c.activeTransfers {
  250. if t.SetTimes(fsPath, atime, mtime) {
  251. return true
  252. }
  253. }
  254. return false
  255. }
  256. func (c *BaseConnection) truncateOpenHandle(fsPath string, size int64) (int64, error) {
  257. c.RLock()
  258. defer c.RUnlock()
  259. for _, t := range c.activeTransfers {
  260. initialSize, err := t.Truncate(fsPath, size)
  261. if err != errTransferMismatch {
  262. return initialSize, err
  263. }
  264. }
  265. return 0, errNoTransfer
  266. }
  267. // ListDir reads the directory matching virtualPath and returns a list of directory entries
  268. func (c *BaseConnection) ListDir(virtualPath string) (*DirListerAt, error) {
  269. if !c.User.HasPerm(dataprovider.PermListItems, virtualPath) {
  270. return nil, c.GetPermissionDeniedError()
  271. }
  272. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  273. if err != nil {
  274. return nil, err
  275. }
  276. lister, err := fs.ReadDir(fsPath)
  277. if err != nil {
  278. c.Log(logger.LevelDebug, "error listing directory: %+v", err)
  279. return nil, c.GetFsError(fs, err)
  280. }
  281. return &DirListerAt{
  282. virtualPath: virtualPath,
  283. user: &c.User,
  284. info: c.User.GetVirtualFoldersInfo(virtualPath),
  285. id: c.ID,
  286. protocol: c.protocol,
  287. lister: lister,
  288. }, nil
  289. }
  290. // CheckParentDirs tries to create the specified directory and any missing parent dirs
  291. func (c *BaseConnection) CheckParentDirs(virtualPath string) error {
  292. fs, err := c.User.GetFilesystemForPath(virtualPath, c.GetID())
  293. if err != nil {
  294. return err
  295. }
  296. if fs.HasVirtualFolders() {
  297. return nil
  298. }
  299. if _, err := c.DoStat(virtualPath, 0, false); !c.IsNotExistError(err) {
  300. return err
  301. }
  302. dirs := util.GetDirsForVirtualPath(virtualPath)
  303. for idx := len(dirs) - 1; idx >= 0; idx-- {
  304. fs, err = c.User.GetFilesystemForPath(dirs[idx], c.GetID())
  305. if err != nil {
  306. return err
  307. }
  308. if fs.HasVirtualFolders() {
  309. continue
  310. }
  311. if err = c.createDirIfMissing(dirs[idx]); err != nil {
  312. return fmt.Errorf("unable to check/create missing parent dir %q for virtual path %q: %w",
  313. dirs[idx], virtualPath, err)
  314. }
  315. }
  316. return nil
  317. }
  318. // GetCreateChecks returns the checks for creating new files
  319. func (c *BaseConnection) GetCreateChecks(virtualPath string, isNewFile bool, isResume bool) int {
  320. result := 0
  321. if !isNewFile {
  322. if isResume {
  323. result += vfs.CheckResume
  324. }
  325. return result
  326. }
  327. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  328. result += vfs.CheckParentDir
  329. return result
  330. }
  331. return result
  332. }
  333. // CreateDir creates a new directory at the specified fsPath
  334. func (c *BaseConnection) CreateDir(virtualPath string, checkFilePatterns bool) error {
  335. if !c.User.HasPerm(dataprovider.PermCreateDirs, path.Dir(virtualPath)) {
  336. return c.GetPermissionDeniedError()
  337. }
  338. if checkFilePatterns {
  339. if ok, _ := c.User.IsFileAllowed(virtualPath); !ok {
  340. return c.GetPermissionDeniedError()
  341. }
  342. }
  343. if c.User.IsVirtualFolder(virtualPath) {
  344. c.Log(logger.LevelWarn, "mkdir not allowed %q is a virtual folder", virtualPath)
  345. return c.GetPermissionDeniedError()
  346. }
  347. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  348. if err != nil {
  349. return err
  350. }
  351. startTime := time.Now()
  352. if err := fs.Mkdir(fsPath); err != nil {
  353. c.Log(logger.LevelError, "error creating dir: %q error: %+v", fsPath, err)
  354. return c.GetFsError(fs, err)
  355. }
  356. vfs.SetPathPermissions(fs, fsPath, c.User.GetUID(), c.User.GetGID())
  357. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  358. logger.CommandLog(mkdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  359. c.localAddr, c.remoteAddr, elapsed)
  360. ExecuteActionNotification(c, operationMkdir, fsPath, virtualPath, "", "", "", 0, nil, elapsed, nil) //nolint:errcheck
  361. return nil
  362. }
  363. // IsRemoveFileAllowed returns an error if removing this file is not allowed
  364. func (c *BaseConnection) IsRemoveFileAllowed(virtualPath string) error {
  365. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteFiles, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  366. return c.GetPermissionDeniedError()
  367. }
  368. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  369. c.Log(logger.LevelDebug, "removing file %q is not allowed", virtualPath)
  370. return c.GetErrorForDeniedFile(policy)
  371. }
  372. return nil
  373. }
  374. // RemoveFile removes a file at the specified fsPath
  375. func (c *BaseConnection) RemoveFile(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo) error {
  376. if err := c.IsRemoveFileAllowed(virtualPath); err != nil {
  377. return err
  378. }
  379. size := info.Size()
  380. status, err := ExecutePreAction(c, operationPreDelete, fsPath, virtualPath, size, 0)
  381. if err != nil {
  382. c.Log(logger.LevelDebug, "delete for file %q denied by pre action: %v", virtualPath, err)
  383. return c.GetPermissionDeniedError()
  384. }
  385. updateQuota := true
  386. startTime := time.Now()
  387. if err := fs.Remove(fsPath, false); err != nil {
  388. if status > 0 && fs.IsNotExist(err) {
  389. // file removed in the pre-action, if the file was deleted from the EventManager the quota is already updated
  390. c.Log(logger.LevelDebug, "file deleted from the hook, status: %d", status)
  391. updateQuota = (status == 1)
  392. } else {
  393. c.Log(logger.LevelError, "failed to remove file/symlink %q: %+v", fsPath, err)
  394. return c.GetFsError(fs, err)
  395. }
  396. }
  397. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  398. logger.CommandLog(removeLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  399. c.localAddr, c.remoteAddr, elapsed)
  400. if updateQuota && info.Mode()&os.ModeSymlink == 0 {
  401. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  402. if err == nil {
  403. dataprovider.UpdateUserFolderQuota(&vfolder, &c.User, -1, -size, false)
  404. } else {
  405. dataprovider.UpdateUserQuota(&c.User, -1, -size, false) //nolint:errcheck
  406. }
  407. }
  408. ExecuteActionNotification(c, operationDelete, fsPath, virtualPath, "", "", "", size, nil, elapsed, nil) //nolint:errcheck
  409. return nil
  410. }
  411. // IsRemoveDirAllowed returns an error if removing this directory is not allowed
  412. func (c *BaseConnection) IsRemoveDirAllowed(fs vfs.Fs, fsPath, virtualPath string) error {
  413. if virtualPath == "/" || fs.GetRelativePath(fsPath) == "/" {
  414. c.Log(logger.LevelWarn, "removing root dir is not allowed")
  415. return c.GetPermissionDeniedError()
  416. }
  417. if c.User.IsVirtualFolder(virtualPath) {
  418. c.Log(logger.LevelWarn, "removing a virtual folder is not allowed: %q", virtualPath)
  419. return fmt.Errorf("removing virtual folders is not allowed: %w", c.GetPermissionDeniedError())
  420. }
  421. if c.User.HasVirtualFoldersInside(virtualPath) {
  422. c.Log(logger.LevelWarn, "removing a directory with a virtual folder inside is not allowed: %q", virtualPath)
  423. return fmt.Errorf("cannot remove directory %q with virtual folders inside: %w", virtualPath, c.GetOpUnsupportedError())
  424. }
  425. if c.User.IsMappedPath(fsPath) {
  426. c.Log(logger.LevelWarn, "removing a directory mapped as virtual folder is not allowed: %q", fsPath)
  427. return fmt.Errorf("removing the directory %q mapped as virtual folder is not allowed: %w",
  428. virtualPath, c.GetPermissionDeniedError())
  429. }
  430. if !c.User.HasAnyPerm([]string{dataprovider.PermDeleteDirs, dataprovider.PermDelete}, path.Dir(virtualPath)) {
  431. return c.GetPermissionDeniedError()
  432. }
  433. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  434. c.Log(logger.LevelDebug, "removing directory %q is not allowed", virtualPath)
  435. return c.GetErrorForDeniedFile(policy)
  436. }
  437. return nil
  438. }
  439. // RemoveDir removes a directory at the specified fsPath
  440. func (c *BaseConnection) RemoveDir(virtualPath string) error {
  441. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  442. if err != nil {
  443. return err
  444. }
  445. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  446. return err
  447. }
  448. var fi os.FileInfo
  449. if fi, err = fs.Lstat(fsPath); err != nil {
  450. // see #149
  451. if fs.IsNotExist(err) && fs.HasVirtualFolders() {
  452. return nil
  453. }
  454. c.Log(logger.LevelError, "failed to remove a dir %q: stat error: %+v", fsPath, err)
  455. return c.GetFsError(fs, err)
  456. }
  457. if !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
  458. c.Log(logger.LevelError, "cannot remove %q is not a directory", fsPath)
  459. return c.GetGenericError(nil)
  460. }
  461. startTime := time.Now()
  462. if err := fs.Remove(fsPath, true); err != nil {
  463. c.Log(logger.LevelError, "failed to remove directory %q: %+v", fsPath, err)
  464. return c.GetFsError(fs, err)
  465. }
  466. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  467. logger.CommandLog(rmdirLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "", "", -1,
  468. c.localAddr, c.remoteAddr, elapsed)
  469. ExecuteActionNotification(c, operationRmdir, fsPath, virtualPath, "", "", "", 0, nil, elapsed, nil) //nolint:errcheck
  470. return nil
  471. }
  472. func (c *BaseConnection) doRecursiveRemoveDirEntry(virtualPath string, info os.FileInfo, recursion int) error {
  473. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  474. if err != nil {
  475. return err
  476. }
  477. return c.doRecursiveRemove(fs, fsPath, virtualPath, info, recursion)
  478. }
  479. func (c *BaseConnection) doRecursiveRemove(fs vfs.Fs, fsPath, virtualPath string, info os.FileInfo, recursion int) error {
  480. if info.IsDir() {
  481. if recursion >= util.MaxRecursion {
  482. c.Log(logger.LevelError, "recursive rename failed, recursion too depth: %d", recursion)
  483. return util.ErrRecursionTooDeep
  484. }
  485. recursion++
  486. lister, err := c.ListDir(virtualPath)
  487. if err != nil {
  488. return fmt.Errorf("unable to get lister for dir %q: %w", virtualPath, err)
  489. }
  490. defer lister.Close()
  491. for {
  492. entries, err := lister.Next(vfs.ListerBatchSize)
  493. finished := errors.Is(err, io.EOF)
  494. if err != nil && !finished {
  495. return fmt.Errorf("unable to get content for dir %q: %w", virtualPath, err)
  496. }
  497. for _, fi := range entries {
  498. targetPath := path.Join(virtualPath, fi.Name())
  499. if err := c.doRecursiveRemoveDirEntry(targetPath, fi, recursion); err != nil {
  500. return err
  501. }
  502. }
  503. if finished {
  504. lister.Close()
  505. break
  506. }
  507. }
  508. return c.RemoveDir(virtualPath)
  509. }
  510. return c.RemoveFile(fs, fsPath, virtualPath, info)
  511. }
  512. // RemoveAll removes the specified path and any children it contains
  513. func (c *BaseConnection) RemoveAll(virtualPath string) error {
  514. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  515. if err != nil {
  516. return err
  517. }
  518. fi, err := fs.Lstat(fsPath)
  519. if err != nil {
  520. c.Log(logger.LevelDebug, "failed to remove path %q: stat error: %+v", fsPath, err)
  521. return c.GetFsError(fs, err)
  522. }
  523. if fi.IsDir() && fi.Mode()&os.ModeSymlink == 0 {
  524. if err := c.IsRemoveDirAllowed(fs, fsPath, virtualPath); err != nil {
  525. return err
  526. }
  527. return c.doRecursiveRemove(fs, fsPath, virtualPath, fi, 0)
  528. }
  529. return c.RemoveFile(fs, fsPath, virtualPath, fi)
  530. }
  531. func (c *BaseConnection) checkCopy(srcInfo, dstInfo os.FileInfo, virtualSource, virtualTarget string) error {
  532. _, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSource)
  533. if err != nil {
  534. return err
  535. }
  536. _, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTarget)
  537. if err != nil {
  538. return err
  539. }
  540. if srcInfo.IsDir() {
  541. if dstInfo != nil && !dstInfo.IsDir() {
  542. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualTarget, virtualSource, c.GetOpUnsupportedError())
  543. }
  544. if util.IsDirOverlapped(virtualSource, virtualTarget, true, "/") {
  545. return fmt.Errorf("nested copy %q => %q is not supported: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  546. }
  547. if util.IsDirOverlapped(fsSourcePath, fsTargetPath, true, c.User.FsConfig.GetPathSeparator()) {
  548. c.Log(logger.LevelWarn, "nested fs copy %q => %q not allowed", fsSourcePath, fsTargetPath)
  549. return fmt.Errorf("nested fs copy is not supported: %w", c.GetOpUnsupportedError())
  550. }
  551. return nil
  552. }
  553. if dstInfo != nil && dstInfo.IsDir() {
  554. return fmt.Errorf("cannot overwrite file %q with dir %q: %w", virtualSource, virtualTarget, c.GetOpUnsupportedError())
  555. }
  556. if fsSourcePath == fsTargetPath {
  557. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  558. }
  559. return nil
  560. }
  561. func (c *BaseConnection) copyFile(virtualSourcePath, virtualTargetPath string, srcInfo os.FileInfo) error {
  562. if !c.User.HasPerm(dataprovider.PermCopy, virtualSourcePath) || !c.User.HasPerm(dataprovider.PermCopy, virtualTargetPath) {
  563. return c.GetPermissionDeniedError()
  564. }
  565. if ok, _ := c.User.IsFileAllowed(virtualTargetPath); !ok {
  566. return fmt.Errorf("file %q is not allowed: %w", virtualTargetPath, c.GetPermissionDeniedError())
  567. }
  568. if c.IsSameResource(virtualSourcePath, virtualTargetPath) {
  569. fs, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  570. if err != nil {
  571. return err
  572. }
  573. if copier, ok := fs.(vfs.FsFileCopier); ok {
  574. _, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  575. if err != nil {
  576. return err
  577. }
  578. startTime := time.Now()
  579. numFiles, sizeDiff, err := copier.CopyFile(fsSourcePath, fsTargetPath, srcInfo)
  580. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  581. updateUserQuotaAfterFileWrite(c, virtualTargetPath, numFiles, sizeDiff)
  582. logger.CommandLog(copyLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  583. "", "", "", srcInfo.Size(), c.localAddr, c.remoteAddr, elapsed)
  584. ExecuteActionNotification(c, operationCopy, fsSourcePath, virtualSourcePath, fsTargetPath, virtualTargetPath, "", srcInfo.Size(), err, elapsed, nil) //nolint:errcheck
  585. return err
  586. }
  587. }
  588. reader, rCancelFn, err := getFileReader(c, virtualSourcePath)
  589. if err != nil {
  590. return fmt.Errorf("unable to get reader for path %q: %w", virtualSourcePath, err)
  591. }
  592. defer rCancelFn()
  593. defer reader.Close()
  594. writer, numFiles, truncatedSize, wCancelFn, err := getFileWriter(c, virtualTargetPath, srcInfo.Size())
  595. if err != nil {
  596. return fmt.Errorf("unable to get writer for path %q: %w", virtualTargetPath, err)
  597. }
  598. defer wCancelFn()
  599. startTime := time.Now()
  600. _, err = io.Copy(writer, reader)
  601. return closeWriterAndUpdateQuota(writer, c, virtualSourcePath, virtualTargetPath, numFiles, truncatedSize,
  602. err, operationCopy, startTime)
  603. }
  604. func (c *BaseConnection) doRecursiveCopy(virtualSourcePath, virtualTargetPath string, srcInfo os.FileInfo,
  605. createTargetDir bool, recursion int,
  606. ) error {
  607. if srcInfo.IsDir() {
  608. if recursion >= util.MaxRecursion {
  609. c.Log(logger.LevelError, "recursive copy failed, recursion too depth: %d", recursion)
  610. return util.ErrRecursionTooDeep
  611. }
  612. recursion++
  613. if createTargetDir {
  614. if err := c.CreateDir(virtualTargetPath, false); err != nil {
  615. return fmt.Errorf("unable to create directory %q: %w", virtualTargetPath, err)
  616. }
  617. }
  618. lister, err := c.ListDir(virtualSourcePath)
  619. if err != nil {
  620. return fmt.Errorf("unable to get lister for dir %q: %w", virtualSourcePath, err)
  621. }
  622. defer lister.Close()
  623. for {
  624. entries, err := lister.Next(vfs.ListerBatchSize)
  625. finished := errors.Is(err, io.EOF)
  626. if err != nil && !finished {
  627. return fmt.Errorf("unable to get contents for dir %q: %w", virtualSourcePath, err)
  628. }
  629. if err := c.recursiveCopyEntries(virtualSourcePath, virtualTargetPath, entries, recursion); err != nil {
  630. return err
  631. }
  632. if finished {
  633. return nil
  634. }
  635. }
  636. }
  637. if !srcInfo.Mode().IsRegular() {
  638. c.Log(logger.LevelInfo, "skipping copy for non regular file %q", virtualSourcePath)
  639. return nil
  640. }
  641. return c.copyFile(virtualSourcePath, virtualTargetPath, srcInfo)
  642. }
  643. func (c *BaseConnection) recursiveCopyEntries(virtualSourcePath, virtualTargetPath string, entries []os.FileInfo, recursion int) error {
  644. for _, info := range entries {
  645. sourcePath := path.Join(virtualSourcePath, info.Name())
  646. targetPath := path.Join(virtualTargetPath, info.Name())
  647. targetInfo, err := c.DoStat(targetPath, 1, false)
  648. if err == nil {
  649. if info.IsDir() && targetInfo.IsDir() {
  650. c.Log(logger.LevelDebug, "target copy dir %q already exists", targetPath)
  651. continue
  652. }
  653. }
  654. if err != nil && !c.IsNotExistError(err) {
  655. return err
  656. }
  657. if err := c.checkCopy(info, targetInfo, sourcePath, targetPath); err != nil {
  658. return err
  659. }
  660. if err := c.doRecursiveCopy(sourcePath, targetPath, info, true, recursion); err != nil {
  661. if c.IsNotExistError(err) {
  662. c.Log(logger.LevelInfo, "skipping copy for source path %q: %v", sourcePath, err)
  663. continue
  664. }
  665. return err
  666. }
  667. }
  668. return nil
  669. }
  670. // Copy virtualSourcePath to virtualTargetPath
  671. func (c *BaseConnection) Copy(virtualSourcePath, virtualTargetPath string) error {
  672. copyFromSource := strings.HasSuffix(virtualSourcePath, "/")
  673. copyInTarget := strings.HasSuffix(virtualTargetPath, "/")
  674. virtualSourcePath = path.Clean(virtualSourcePath)
  675. virtualTargetPath = path.Clean(virtualTargetPath)
  676. if virtualSourcePath == virtualTargetPath {
  677. return fmt.Errorf("the copy source and target cannot be the same: %w", c.GetOpUnsupportedError())
  678. }
  679. srcInfo, err := c.DoStat(virtualSourcePath, 1, false)
  680. if err != nil {
  681. return err
  682. }
  683. if srcInfo.Mode()&os.ModeSymlink != 0 {
  684. return fmt.Errorf("copying symlinks is not supported: %w", c.GetOpUnsupportedError())
  685. }
  686. dstInfo, err := c.DoStat(virtualTargetPath, 1, false)
  687. if err == nil && !copyFromSource {
  688. copyInTarget = dstInfo.IsDir()
  689. }
  690. if err != nil && !c.IsNotExistError(err) {
  691. return err
  692. }
  693. destPath := virtualTargetPath
  694. if copyInTarget {
  695. destPath = path.Join(virtualTargetPath, path.Base(virtualSourcePath))
  696. dstInfo, err = c.DoStat(destPath, 1, false)
  697. if err != nil && !c.IsNotExistError(err) {
  698. return err
  699. }
  700. }
  701. createTargetDir := true
  702. if dstInfo != nil && dstInfo.IsDir() {
  703. createTargetDir = false
  704. }
  705. if err := c.checkCopy(srcInfo, dstInfo, virtualSourcePath, destPath); err != nil {
  706. return err
  707. }
  708. if err := c.CheckParentDirs(path.Dir(destPath)); err != nil {
  709. return err
  710. }
  711. done := make(chan bool)
  712. defer close(done)
  713. go keepConnectionAlive(c, done, 2*time.Minute)
  714. return c.doRecursiveCopy(virtualSourcePath, destPath, srcInfo, createTargetDir, 0)
  715. }
  716. // Rename renames (moves) virtualSourcePath to virtualTargetPath
  717. func (c *BaseConnection) Rename(virtualSourcePath, virtualTargetPath string) error {
  718. return c.renameInternal(virtualSourcePath, virtualTargetPath, false, vfs.CheckParentDir)
  719. }
  720. func (c *BaseConnection) renameInternal(virtualSourcePath, virtualTargetPath string,
  721. checkParentDestination bool, checks int,
  722. ) error {
  723. if virtualSourcePath == virtualTargetPath {
  724. return fmt.Errorf("the rename source and target cannot be the same: %w", c.GetOpUnsupportedError())
  725. }
  726. fsSrc, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  727. if err != nil {
  728. return err
  729. }
  730. fsDst, fsTargetPath, err := c.GetFsAndResolvedPath(virtualTargetPath)
  731. if err != nil {
  732. return err
  733. }
  734. startTime := time.Now()
  735. srcInfo, err := fsSrc.Lstat(fsSourcePath)
  736. if err != nil {
  737. return c.GetFsError(fsSrc, err)
  738. }
  739. if !c.isRenamePermitted(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo) {
  740. return c.GetPermissionDeniedError()
  741. }
  742. initialSize := int64(-1)
  743. if dstInfo, err := fsDst.Lstat(fsTargetPath); err == nil {
  744. checkParentDestination = false
  745. if dstInfo.IsDir() {
  746. c.Log(logger.LevelWarn, "attempted to rename %q overwriting an existing directory %q",
  747. fsSourcePath, fsTargetPath)
  748. return c.GetOpUnsupportedError()
  749. }
  750. // we are overwriting an existing file/symlink
  751. if dstInfo.Mode().IsRegular() {
  752. initialSize = dstInfo.Size()
  753. }
  754. if !c.User.HasPerm(dataprovider.PermOverwrite, path.Dir(virtualTargetPath)) {
  755. c.Log(logger.LevelDebug, "renaming %q -> %q is not allowed. Target exists but the user %q"+
  756. "has no overwrite permission", virtualSourcePath, virtualTargetPath, c.User.Username)
  757. return c.GetPermissionDeniedError()
  758. }
  759. }
  760. if srcInfo.IsDir() {
  761. if err := c.checkFolderRename(fsSrc, fsDst, fsSourcePath, fsTargetPath, virtualSourcePath, virtualTargetPath, srcInfo); err != nil {
  762. return err
  763. }
  764. }
  765. if !c.hasSpaceForRename(fsSrc, virtualSourcePath, virtualTargetPath, initialSize, fsSourcePath) {
  766. c.Log(logger.LevelInfo, "denying cross rename due to space limit")
  767. return c.GetGenericError(ErrQuotaExceeded)
  768. }
  769. if checkParentDestination {
  770. c.CheckParentDirs(path.Dir(virtualTargetPath)) //nolint:errcheck
  771. }
  772. done := make(chan bool)
  773. defer close(done)
  774. go keepConnectionAlive(c, done, 2*time.Minute)
  775. files, size, err := fsDst.Rename(fsSourcePath, fsTargetPath, checks)
  776. if err != nil {
  777. c.Log(logger.LevelError, "failed to rename %q -> %q: %+v", fsSourcePath, fsTargetPath, err)
  778. return c.GetFsError(fsSrc, err)
  779. }
  780. vfs.SetPathPermissions(fsDst, fsTargetPath, c.User.GetUID(), c.User.GetGID())
  781. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  782. c.updateQuotaAfterRename(fsDst, virtualSourcePath, virtualTargetPath, fsTargetPath, initialSize, files, size) //nolint:errcheck
  783. logger.CommandLog(renameLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1,
  784. "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  785. ExecuteActionNotification(c, operationRename, fsSourcePath, virtualSourcePath, fsTargetPath, //nolint:errcheck
  786. virtualTargetPath, "", 0, nil, elapsed, nil)
  787. return nil
  788. }
  789. // CreateSymlink creates fsTargetPath as a symbolic link to fsSourcePath
  790. func (c *BaseConnection) CreateSymlink(virtualSourcePath, virtualTargetPath string) error {
  791. var relativePath string
  792. if !path.IsAbs(virtualSourcePath) {
  793. relativePath = virtualSourcePath
  794. virtualSourcePath = path.Join(path.Dir(virtualTargetPath), relativePath)
  795. c.Log(logger.LevelDebug, "link relative path %q resolved as %q, target path %q",
  796. relativePath, virtualSourcePath, virtualTargetPath)
  797. }
  798. if c.isCrossFoldersRequest(virtualSourcePath, virtualTargetPath) {
  799. c.Log(logger.LevelWarn, "cross folder symlink is not supported, src: %v dst: %v", virtualSourcePath, virtualTargetPath)
  800. return c.GetOpUnsupportedError()
  801. }
  802. // we cannot have a cross folder request here so only one fs is enough
  803. fs, fsSourcePath, err := c.GetFsAndResolvedPath(virtualSourcePath)
  804. if err != nil {
  805. return err
  806. }
  807. fsTargetPath, err := fs.ResolvePath(virtualTargetPath)
  808. if err != nil {
  809. return c.GetFsError(fs, err)
  810. }
  811. if fs.GetRelativePath(fsSourcePath) == "/" {
  812. c.Log(logger.LevelError, "symlinking root dir is not allowed")
  813. return c.GetPermissionDeniedError()
  814. }
  815. if fs.GetRelativePath(fsTargetPath) == "/" {
  816. c.Log(logger.LevelError, "symlinking to root dir is not allowed")
  817. return c.GetPermissionDeniedError()
  818. }
  819. if !c.User.HasPerm(dataprovider.PermCreateSymlinks, path.Dir(virtualTargetPath)) {
  820. return c.GetPermissionDeniedError()
  821. }
  822. ok, policy := c.User.IsFileAllowed(virtualSourcePath)
  823. if !ok && policy == sdk.DenyPolicyHide {
  824. c.Log(logger.LevelError, "symlink source path %q is not allowed", virtualSourcePath)
  825. return c.GetNotExistError()
  826. }
  827. if ok, _ = c.User.IsFileAllowed(virtualTargetPath); !ok {
  828. c.Log(logger.LevelError, "symlink target path %q is not allowed", virtualTargetPath)
  829. return c.GetPermissionDeniedError()
  830. }
  831. if relativePath != "" {
  832. fsSourcePath = relativePath
  833. }
  834. startTime := time.Now()
  835. if err := fs.Symlink(fsSourcePath, fsTargetPath); err != nil {
  836. c.Log(logger.LevelError, "failed to create symlink %q -> %q: %+v", fsSourcePath, fsTargetPath, err)
  837. return c.GetFsError(fs, err)
  838. }
  839. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  840. logger.CommandLog(symlinkLogSender, fsSourcePath, fsTargetPath, c.User.Username, "", c.ID, c.protocol, -1, -1, "",
  841. "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  842. return nil
  843. }
  844. func (c *BaseConnection) getPathForSetStatPerms(fs vfs.Fs, fsPath, virtualPath string) string {
  845. pathForPerms := virtualPath
  846. if fi, err := fs.Lstat(fsPath); err == nil {
  847. if fi.IsDir() {
  848. pathForPerms = path.Dir(virtualPath)
  849. }
  850. }
  851. return pathForPerms
  852. }
  853. func (c *BaseConnection) doStatInternal(virtualPath string, mode int, checkFilePatterns,
  854. convertResult bool,
  855. ) (os.FileInfo, error) {
  856. // for some vfs we don't create intermediary folders so we cannot simply check
  857. // if virtualPath is a virtual folder. Allowing stat for hidden virtual folders
  858. // is by purpose.
  859. vfolders := c.User.GetVirtualFoldersInPath(path.Dir(virtualPath))
  860. if _, ok := vfolders[virtualPath]; ok {
  861. return vfs.NewFileInfo(virtualPath, true, 0, time.Unix(0, 0), false), nil
  862. }
  863. if checkFilePatterns && virtualPath != "/" {
  864. ok, policy := c.User.IsFileAllowed(virtualPath)
  865. if !ok && policy == sdk.DenyPolicyHide {
  866. return nil, c.GetNotExistError()
  867. }
  868. }
  869. var info os.FileInfo
  870. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  871. if err != nil {
  872. return nil, err
  873. }
  874. if mode == 1 {
  875. info, err = fs.Lstat(c.getRealFsPath(fsPath))
  876. } else {
  877. info, err = fs.Stat(c.getRealFsPath(fsPath))
  878. }
  879. if err != nil {
  880. if !fs.IsNotExist(err) {
  881. c.Log(logger.LevelWarn, "stat error for path %q: %+v", virtualPath, err)
  882. }
  883. return nil, c.GetFsError(fs, err)
  884. }
  885. if convertResult && vfs.IsCryptOsFs(fs) {
  886. info = fs.(*vfs.CryptFs).ConvertFileInfo(info)
  887. }
  888. return info, nil
  889. }
  890. // DoStat execute a Stat if mode = 0, Lstat if mode = 1
  891. func (c *BaseConnection) DoStat(virtualPath string, mode int, checkFilePatterns bool) (os.FileInfo, error) {
  892. return c.doStatInternal(virtualPath, mode, checkFilePatterns, true)
  893. }
  894. func (c *BaseConnection) createDirIfMissing(name string) error {
  895. _, err := c.DoStat(name, 0, false)
  896. if c.IsNotExistError(err) {
  897. return c.CreateDir(name, false)
  898. }
  899. return err
  900. }
  901. func (c *BaseConnection) ignoreSetStat(fs vfs.Fs) bool {
  902. if Config.SetstatMode == 1 {
  903. return true
  904. }
  905. if Config.SetstatMode == 2 && !vfs.IsLocalOrSFTPFs(fs) && !vfs.IsCryptOsFs(fs) {
  906. return true
  907. }
  908. return false
  909. }
  910. func (c *BaseConnection) handleChmod(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  911. if !c.User.HasPerm(dataprovider.PermChmod, pathForPerms) {
  912. return c.GetPermissionDeniedError()
  913. }
  914. if c.ignoreSetStat(fs) {
  915. return nil
  916. }
  917. startTime := time.Now()
  918. if err := fs.Chmod(c.getRealFsPath(fsPath), attributes.Mode); err != nil {
  919. c.Log(logger.LevelError, "failed to chmod path %q, mode: %v, err: %+v", fsPath, attributes.Mode.String(), err)
  920. return c.GetFsError(fs, err)
  921. }
  922. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  923. logger.CommandLog(chmodLogSender, fsPath, "", c.User.Username, attributes.Mode.String(), c.ID, c.protocol,
  924. -1, -1, "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  925. return nil
  926. }
  927. func (c *BaseConnection) handleChown(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  928. if !c.User.HasPerm(dataprovider.PermChown, pathForPerms) {
  929. return c.GetPermissionDeniedError()
  930. }
  931. if c.ignoreSetStat(fs) {
  932. return nil
  933. }
  934. startTime := time.Now()
  935. if err := fs.Chown(c.getRealFsPath(fsPath), attributes.UID, attributes.GID); err != nil {
  936. c.Log(logger.LevelError, "failed to chown path %q, uid: %v, gid: %v, err: %+v", fsPath, attributes.UID,
  937. attributes.GID, err)
  938. return c.GetFsError(fs, err)
  939. }
  940. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  941. logger.CommandLog(chownLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, attributes.UID, attributes.GID,
  942. "", "", "", -1, c.localAddr, c.remoteAddr, elapsed)
  943. return nil
  944. }
  945. func (c *BaseConnection) handleChtimes(fs vfs.Fs, fsPath, pathForPerms string, attributes *StatAttributes) error {
  946. if !c.User.HasPerm(dataprovider.PermChtimes, pathForPerms) {
  947. return c.GetPermissionDeniedError()
  948. }
  949. if Config.SetstatMode == 1 {
  950. return nil
  951. }
  952. startTime := time.Now()
  953. isUploading := c.setTimes(fsPath, attributes.Atime, attributes.Mtime)
  954. if err := fs.Chtimes(c.getRealFsPath(fsPath), attributes.Atime, attributes.Mtime, isUploading); err != nil {
  955. c.setTimes(fsPath, time.Time{}, time.Time{})
  956. if errors.Is(err, vfs.ErrVfsUnsupported) && Config.SetstatMode == 2 {
  957. return nil
  958. }
  959. c.Log(logger.LevelError, "failed to chtimes for path %q, access time: %v, modification time: %v, err: %+v",
  960. fsPath, attributes.Atime, attributes.Mtime, err)
  961. return c.GetFsError(fs, err)
  962. }
  963. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  964. accessTimeString := attributes.Atime.Format(chtimesFormat)
  965. modificationTimeString := attributes.Mtime.Format(chtimesFormat)
  966. logger.CommandLog(chtimesLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1,
  967. accessTimeString, modificationTimeString, "", -1, c.localAddr, c.remoteAddr, elapsed)
  968. return nil
  969. }
  970. // SetStat set StatAttributes for the specified fsPath
  971. func (c *BaseConnection) SetStat(virtualPath string, attributes *StatAttributes) error {
  972. if ok, policy := c.User.IsFileAllowed(virtualPath); !ok {
  973. return c.GetErrorForDeniedFile(policy)
  974. }
  975. fs, fsPath, err := c.GetFsAndResolvedPath(virtualPath)
  976. if err != nil {
  977. return err
  978. }
  979. pathForPerms := c.getPathForSetStatPerms(fs, fsPath, virtualPath)
  980. if attributes.Flags&StatAttrTimes != 0 {
  981. if err = c.handleChtimes(fs, fsPath, pathForPerms, attributes); err != nil {
  982. return err
  983. }
  984. }
  985. if attributes.Flags&StatAttrPerms != 0 {
  986. if err = c.handleChmod(fs, fsPath, pathForPerms, attributes); err != nil {
  987. return err
  988. }
  989. }
  990. if attributes.Flags&StatAttrUIDGID != 0 {
  991. if err = c.handleChown(fs, fsPath, pathForPerms, attributes); err != nil {
  992. return err
  993. }
  994. }
  995. if attributes.Flags&StatAttrSize != 0 {
  996. if !c.User.HasPerm(dataprovider.PermOverwrite, pathForPerms) {
  997. return c.GetPermissionDeniedError()
  998. }
  999. startTime := time.Now()
  1000. if err = c.truncateFile(fs, fsPath, virtualPath, attributes.Size); err != nil {
  1001. c.Log(logger.LevelError, "failed to truncate path %q, size: %v, err: %+v", fsPath, attributes.Size, err)
  1002. return c.GetFsError(fs, err)
  1003. }
  1004. elapsed := time.Since(startTime).Nanoseconds() / 1000000
  1005. logger.CommandLog(truncateLogSender, fsPath, "", c.User.Username, "", c.ID, c.protocol, -1, -1, "", "",
  1006. "", attributes.Size, c.localAddr, c.remoteAddr, elapsed)
  1007. }
  1008. return nil
  1009. }
  1010. func (c *BaseConnection) truncateFile(fs vfs.Fs, fsPath, virtualPath string, size int64) error {
  1011. // check first if we have an open transfer for the given path and try to truncate the file already opened
  1012. // if we found no transfer we truncate by path.
  1013. var initialSize int64
  1014. var err error
  1015. initialSize, err = c.truncateOpenHandle(fsPath, size)
  1016. if err == errNoTransfer {
  1017. c.Log(logger.LevelDebug, "file path %q not found in active transfers, execute trucate by path", fsPath)
  1018. var info os.FileInfo
  1019. info, err = fs.Stat(fsPath)
  1020. if err != nil {
  1021. return err
  1022. }
  1023. initialSize = info.Size()
  1024. err = fs.Truncate(fsPath, size)
  1025. }
  1026. if err == nil && vfs.HasTruncateSupport(fs) {
  1027. sizeDiff := initialSize - size
  1028. vfolder, err := c.User.GetVirtualFolderForPath(path.Dir(virtualPath))
  1029. if err == nil {
  1030. dataprovider.UpdateUserFolderQuota(&vfolder, &c.User, 0, -sizeDiff, false)
  1031. } else {
  1032. dataprovider.UpdateUserQuota(&c.User, 0, -sizeDiff, false) //nolint:errcheck
  1033. }
  1034. }
  1035. return err
  1036. }
  1037. func (c *BaseConnection) checkRecursiveRenameDirPermissions(fsSrc, fsDst vfs.Fs, sourcePath, targetPath,
  1038. virtualSourcePath, virtualTargetPath string, fi os.FileInfo,
  1039. ) error {
  1040. if !c.User.HasPermissionsInside(virtualSourcePath) &&
  1041. !c.User.HasPermissionsInside(virtualTargetPath) {
  1042. if !c.isRenamePermitted(fsSrc, fsDst, sourcePath, targetPath, virtualSourcePath, virtualTargetPath, fi) {
  1043. c.Log(logger.LevelInfo, "rename %q -> %q is not allowed, virtual destination path: %q",
  1044. sourcePath, targetPath, virtualTargetPath)
  1045. return c.GetPermissionDeniedError()
  1046. }
  1047. // if all rename permissions are granted we have finished, otherwise we have to walk
  1048. // because we could have the rename dir permission but not the rename file and the dir to
  1049. // rename could contain files
  1050. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) && c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  1051. return nil
  1052. }
  1053. }
  1054. return fsSrc.Walk(sourcePath, func(walkedPath string, info os.FileInfo, err error) error {
  1055. if err != nil {
  1056. return c.GetFsError(fsSrc, err)
  1057. }
  1058. if walkedPath != sourcePath && !vfs.IsRenameAtomic(fsSrc) && Config.RenameMode == 0 {
  1059. c.Log(logger.LevelInfo, "cannot rename non empty directory %q on this filesystem", virtualSourcePath)
  1060. return c.GetOpUnsupportedError()
  1061. }
  1062. dstPath := strings.Replace(walkedPath, sourcePath, targetPath, 1)
  1063. virtualSrcPath := fsSrc.GetRelativePath(walkedPath)
  1064. virtualDstPath := fsDst.GetRelativePath(dstPath)
  1065. if !c.isRenamePermitted(fsSrc, fsDst, walkedPath, dstPath, virtualSrcPath, virtualDstPath, info) {
  1066. c.Log(logger.LevelInfo, "rename %q -> %q is not allowed, virtual destination path: %q",
  1067. walkedPath, dstPath, virtualDstPath)
  1068. return c.GetPermissionDeniedError()
  1069. }
  1070. return nil
  1071. })
  1072. }
  1073. func (c *BaseConnection) hasRenamePerms(virtualSourcePath, virtualTargetPath string, fi os.FileInfo) bool {
  1074. if c.User.HasPermsRenameAll(path.Dir(virtualSourcePath)) &&
  1075. c.User.HasPermsRenameAll(path.Dir(virtualTargetPath)) {
  1076. return true
  1077. }
  1078. if fi == nil {
  1079. // we don't know if this is a file or a directory and we don't have all the rename perms, return false
  1080. return false
  1081. }
  1082. if fi.IsDir() {
  1083. perms := []string{
  1084. dataprovider.PermRenameDirs,
  1085. dataprovider.PermRename,
  1086. }
  1087. return c.User.HasAnyPerm(perms, path.Dir(virtualSourcePath)) &&
  1088. c.User.HasAnyPerm(perms, path.Dir(virtualTargetPath))
  1089. }
  1090. // file or symlink
  1091. perms := []string{
  1092. dataprovider.PermRenameFiles,
  1093. dataprovider.PermRename,
  1094. }
  1095. return c.User.HasAnyPerm(perms, path.Dir(virtualSourcePath)) &&
  1096. c.User.HasAnyPerm(perms, path.Dir(virtualTargetPath))
  1097. }
  1098. func (c *BaseConnection) checkFolderRename(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath,
  1099. virtualTargetPath string, fi os.FileInfo) error {
  1100. if util.IsDirOverlapped(virtualSourcePath, virtualTargetPath, true, "/") {
  1101. c.Log(logger.LevelDebug, "renaming the folder %q->%q is not supported: nested folders",
  1102. virtualSourcePath, virtualTargetPath)
  1103. return fmt.Errorf("nested rename %q => %q is not supported: %w",
  1104. virtualSourcePath, virtualTargetPath, c.GetOpUnsupportedError())
  1105. }
  1106. if util.IsDirOverlapped(fsSourcePath, fsTargetPath, true, c.User.FsConfig.GetPathSeparator()) {
  1107. c.Log(logger.LevelDebug, "renaming the folder %q->%q is not supported: nested fs folders",
  1108. fsSourcePath, fsTargetPath)
  1109. return fmt.Errorf("nested fs rename %q => %q is not supported: %w",
  1110. fsSourcePath, fsTargetPath, c.GetOpUnsupportedError())
  1111. }
  1112. if c.User.HasVirtualFoldersInside(virtualSourcePath) {
  1113. c.Log(logger.LevelDebug, "renaming the folder %q is not supported: it has virtual folders inside it",
  1114. virtualSourcePath)
  1115. return fmt.Errorf("folder %q has virtual folders inside it: %w", virtualSourcePath, c.GetOpUnsupportedError())
  1116. }
  1117. if c.User.HasVirtualFoldersInside(virtualTargetPath) {
  1118. c.Log(logger.LevelDebug, "renaming the folder %q is not supported, the target %q has virtual folders inside it",
  1119. virtualSourcePath, virtualTargetPath)
  1120. return fmt.Errorf("folder %q has virtual folders inside it: %w", virtualTargetPath, c.GetOpUnsupportedError())
  1121. }
  1122. if err := c.checkRecursiveRenameDirPermissions(fsSrc, fsDst, fsSourcePath, fsTargetPath,
  1123. virtualSourcePath, virtualTargetPath, fi); err != nil {
  1124. c.Log(logger.LevelDebug, "error checking recursive permissions before renaming %q: %+v", fsSourcePath, err)
  1125. return err
  1126. }
  1127. return nil
  1128. }
  1129. func (c *BaseConnection) isRenamePermitted(fsSrc, fsDst vfs.Fs, fsSourcePath, fsTargetPath, virtualSourcePath,
  1130. virtualTargetPath string, fi os.FileInfo,
  1131. ) bool {
  1132. if !c.IsSameResource(virtualSourcePath, virtualTargetPath) {
  1133. c.Log(logger.LevelInfo, "rename %q->%q is not allowed: the paths must be on the same resource",
  1134. virtualSourcePath, virtualTargetPath)
  1135. return false
  1136. }
  1137. if c.User.IsMappedPath(fsSourcePath) && vfs.IsLocalOrCryptoFs(fsSrc) {
  1138. c.Log(logger.LevelWarn, "renaming a directory mapped as virtual folder is not allowed: %q", fsSourcePath)
  1139. return false
  1140. }
  1141. if c.User.IsMappedPath(fsTargetPath) && vfs.IsLocalOrCryptoFs(fsDst) {
  1142. c.Log(logger.LevelWarn, "renaming to a directory mapped as virtual folder is not allowed: %q", fsTargetPath)
  1143. return false
  1144. }
  1145. if virtualSourcePath == "/" || virtualTargetPath == "/" || fsSrc.GetRelativePath(fsSourcePath) == "/" {
  1146. c.Log(logger.LevelWarn, "renaming root dir is not allowed")
  1147. return false
  1148. }
  1149. if c.User.IsVirtualFolder(virtualSourcePath) || c.User.IsVirtualFolder(virtualTargetPath) {
  1150. c.Log(logger.LevelWarn, "renaming a virtual folder is not allowed")
  1151. return false
  1152. }
  1153. isSrcAllowed, _ := c.User.IsFileAllowed(virtualSourcePath)
  1154. isDstAllowed, _ := c.User.IsFileAllowed(virtualTargetPath)
  1155. if !isSrcAllowed || !isDstAllowed {
  1156. c.Log(logger.LevelDebug, "renaming source: %q to target: %q not allowed", virtualSourcePath,
  1157. virtualTargetPath)
  1158. return false
  1159. }
  1160. return c.hasRenamePerms(virtualSourcePath, virtualTargetPath, fi)
  1161. }
  1162. func (c *BaseConnection) hasSpaceForRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath string, initialSize int64,
  1163. fsSourcePath string) bool {
  1164. if dataprovider.GetQuotaTracking() == 0 {
  1165. return true
  1166. }
  1167. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1168. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1169. if errSrc != nil && errDst != nil {
  1170. // rename inside the user home dir
  1171. return true
  1172. }
  1173. if errSrc == nil && errDst == nil {
  1174. // rename between virtual folders
  1175. if sourceFolder.Name == dstFolder.Name {
  1176. // rename inside the same virtual folder
  1177. return true
  1178. }
  1179. }
  1180. if errSrc != nil && dstFolder.IsIncludedInUserQuota() {
  1181. // rename between user root dir and a virtual folder included in user quota
  1182. return true
  1183. }
  1184. if errDst != nil && sourceFolder.IsIncludedInUserQuota() {
  1185. // rename between a virtual folder included in user quota and the user root dir
  1186. return true
  1187. }
  1188. quotaResult, _ := c.HasSpace(true, false, virtualTargetPath)
  1189. if quotaResult.HasSpace && quotaResult.QuotaSize == 0 && quotaResult.QuotaFiles == 0 {
  1190. // no quota restrictions
  1191. return true
  1192. }
  1193. return c.hasSpaceForCrossRename(fs, quotaResult, initialSize, fsSourcePath)
  1194. }
  1195. // hasSpaceForCrossRename checks the quota after a rename between different folders
  1196. func (c *BaseConnection) hasSpaceForCrossRename(fs vfs.Fs, quotaResult vfs.QuotaCheckResult, initialSize int64, sourcePath string) bool {
  1197. if !quotaResult.HasSpace && initialSize == -1 {
  1198. // we are over quota and this is not a file replace
  1199. return false
  1200. }
  1201. fi, err := fs.Lstat(sourcePath)
  1202. if err != nil {
  1203. c.Log(logger.LevelError, "cross rename denied, stat error for path %q: %v", sourcePath, err)
  1204. return false
  1205. }
  1206. var sizeDiff int64
  1207. var filesDiff int
  1208. if fi.Mode().IsRegular() {
  1209. sizeDiff = fi.Size()
  1210. filesDiff = 1
  1211. if initialSize != -1 {
  1212. sizeDiff -= initialSize
  1213. filesDiff = 0
  1214. }
  1215. } else if fi.IsDir() {
  1216. filesDiff, sizeDiff, err = fs.GetDirSize(sourcePath)
  1217. if err != nil {
  1218. c.Log(logger.LevelError, "cross rename denied, error getting size for directory %q: %v", sourcePath, err)
  1219. return false
  1220. }
  1221. }
  1222. if !quotaResult.HasSpace && initialSize != -1 {
  1223. // we are over quota but we are overwriting an existing file so we check if the quota size after the rename is ok
  1224. if quotaResult.QuotaSize == 0 {
  1225. return true
  1226. }
  1227. c.Log(logger.LevelDebug, "cross rename overwrite, source %q, used size %d, size to add %d",
  1228. sourcePath, quotaResult.UsedSize, sizeDiff)
  1229. quotaResult.UsedSize += sizeDiff
  1230. return quotaResult.GetRemainingSize() >= 0
  1231. }
  1232. if quotaResult.QuotaFiles > 0 {
  1233. remainingFiles := quotaResult.GetRemainingFiles()
  1234. c.Log(logger.LevelDebug, "cross rename, source %q remaining file %d to add %d", sourcePath,
  1235. remainingFiles, filesDiff)
  1236. if remainingFiles < filesDiff {
  1237. return false
  1238. }
  1239. }
  1240. if quotaResult.QuotaSize > 0 {
  1241. remainingSize := quotaResult.GetRemainingSize()
  1242. c.Log(logger.LevelDebug, "cross rename, source %q remaining size %d to add %d", sourcePath,
  1243. remainingSize, sizeDiff)
  1244. if remainingSize < sizeDiff {
  1245. return false
  1246. }
  1247. }
  1248. return true
  1249. }
  1250. // GetMaxWriteSize returns the allowed size for an upload or an error
  1251. // if no enough size is available for a resume/append
  1252. func (c *BaseConnection) GetMaxWriteSize(quotaResult vfs.QuotaCheckResult, isResume bool, fileSize int64,
  1253. isUploadResumeSupported bool,
  1254. ) (int64, error) {
  1255. maxWriteSize := quotaResult.GetRemainingSize()
  1256. if isResume {
  1257. if !isUploadResumeSupported {
  1258. return 0, c.GetOpUnsupportedError()
  1259. }
  1260. if c.User.Filters.MaxUploadFileSize > 0 && c.User.Filters.MaxUploadFileSize <= fileSize {
  1261. return 0, c.GetQuotaExceededError()
  1262. }
  1263. if c.User.Filters.MaxUploadFileSize > 0 {
  1264. maxUploadSize := c.User.Filters.MaxUploadFileSize - fileSize
  1265. if maxUploadSize < maxWriteSize || maxWriteSize == 0 {
  1266. maxWriteSize = maxUploadSize
  1267. }
  1268. }
  1269. } else {
  1270. if maxWriteSize > 0 {
  1271. maxWriteSize += fileSize
  1272. }
  1273. if c.User.Filters.MaxUploadFileSize > 0 && (c.User.Filters.MaxUploadFileSize < maxWriteSize || maxWriteSize == 0) {
  1274. maxWriteSize = c.User.Filters.MaxUploadFileSize
  1275. }
  1276. }
  1277. return maxWriteSize, nil
  1278. }
  1279. // GetTransferQuota returns the data transfers quota
  1280. func (c *BaseConnection) GetTransferQuota() dataprovider.TransferQuota {
  1281. result, _, _ := c.checkUserQuota()
  1282. return result
  1283. }
  1284. func (c *BaseConnection) checkUserQuota() (dataprovider.TransferQuota, int, int64) {
  1285. ul, dl, total := c.User.GetDataTransferLimits()
  1286. result := dataprovider.TransferQuota{
  1287. ULSize: ul,
  1288. DLSize: dl,
  1289. TotalSize: total,
  1290. AllowedULSize: 0,
  1291. AllowedDLSize: 0,
  1292. AllowedTotalSize: 0,
  1293. }
  1294. if !c.User.HasTransferQuotaRestrictions() {
  1295. return result, -1, -1
  1296. }
  1297. usedFiles, usedSize, usedULSize, usedDLSize, err := dataprovider.GetUsedQuota(c.User.Username)
  1298. if err != nil {
  1299. c.Log(logger.LevelError, "error getting used quota for %q: %v", c.User.Username, err)
  1300. result.AllowedTotalSize = -1
  1301. return result, -1, -1
  1302. }
  1303. if result.TotalSize > 0 {
  1304. result.AllowedTotalSize = result.TotalSize - (usedULSize + usedDLSize)
  1305. }
  1306. if result.ULSize > 0 {
  1307. result.AllowedULSize = result.ULSize - usedULSize
  1308. }
  1309. if result.DLSize > 0 {
  1310. result.AllowedDLSize = result.DLSize - usedDLSize
  1311. }
  1312. return result, usedFiles, usedSize
  1313. }
  1314. // HasSpace checks user's quota usage
  1315. func (c *BaseConnection) HasSpace(checkFiles, getUsage bool, requestPath string) (vfs.QuotaCheckResult,
  1316. dataprovider.TransferQuota,
  1317. ) {
  1318. result := vfs.QuotaCheckResult{
  1319. HasSpace: true,
  1320. AllowedSize: 0,
  1321. AllowedFiles: 0,
  1322. UsedSize: 0,
  1323. UsedFiles: 0,
  1324. QuotaSize: 0,
  1325. QuotaFiles: 0,
  1326. }
  1327. if dataprovider.GetQuotaTracking() == 0 {
  1328. return result, dataprovider.TransferQuota{}
  1329. }
  1330. transferQuota, usedFiles, usedSize := c.checkUserQuota()
  1331. var err error
  1332. var vfolder vfs.VirtualFolder
  1333. vfolder, err = c.User.GetVirtualFolderForPath(path.Dir(requestPath))
  1334. if err == nil && !vfolder.IsIncludedInUserQuota() {
  1335. if vfolder.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  1336. return result, transferQuota
  1337. }
  1338. result.QuotaSize = vfolder.QuotaSize
  1339. result.QuotaFiles = vfolder.QuotaFiles
  1340. result.UsedFiles, result.UsedSize, err = dataprovider.GetUsedVirtualFolderQuota(vfolder.Name)
  1341. } else {
  1342. if c.User.HasNoQuotaRestrictions(checkFiles) && !getUsage {
  1343. return result, transferQuota
  1344. }
  1345. result.QuotaSize = c.User.QuotaSize
  1346. result.QuotaFiles = c.User.QuotaFiles
  1347. if usedSize == -1 {
  1348. result.UsedFiles, result.UsedSize, _, _, err = dataprovider.GetUsedQuota(c.User.Username)
  1349. } else {
  1350. err = nil
  1351. result.UsedFiles = usedFiles
  1352. result.UsedSize = usedSize
  1353. }
  1354. }
  1355. if err != nil {
  1356. c.Log(logger.LevelError, "error getting used quota for %q request path %q: %v", c.User.Username, requestPath, err)
  1357. result.HasSpace = false
  1358. return result, transferQuota
  1359. }
  1360. result.AllowedFiles = result.QuotaFiles - result.UsedFiles
  1361. result.AllowedSize = result.QuotaSize - result.UsedSize
  1362. if (checkFiles && result.QuotaFiles > 0 && result.UsedFiles >= result.QuotaFiles) ||
  1363. (result.QuotaSize > 0 && result.UsedSize >= result.QuotaSize) {
  1364. c.Log(logger.LevelDebug, "quota exceed for user %q, request path %q, num files: %d/%d, size: %d/%d check files: %t",
  1365. c.User.Username, requestPath, result.UsedFiles, result.QuotaFiles, result.UsedSize, result.QuotaSize, checkFiles)
  1366. result.HasSpace = false
  1367. return result, transferQuota
  1368. }
  1369. return result, transferQuota
  1370. }
  1371. // IsSameResource returns true if source and target paths are on the same resource
  1372. func (c *BaseConnection) IsSameResource(virtualSourcePath, virtualTargetPath string) bool {
  1373. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  1374. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  1375. if errSrc != nil && errDst != nil {
  1376. return true
  1377. }
  1378. if errSrc == nil && errDst == nil {
  1379. if sourceFolder.Name == dstFolder.Name {
  1380. return true
  1381. }
  1382. // we have different folders, check if they point to the same resource
  1383. return sourceFolder.FsConfig.IsSameResource(dstFolder.FsConfig)
  1384. }
  1385. if errSrc == nil {
  1386. return sourceFolder.FsConfig.IsSameResource(c.User.FsConfig)
  1387. }
  1388. return dstFolder.FsConfig.IsSameResource(c.User.FsConfig)
  1389. }
  1390. func (c *BaseConnection) isCrossFoldersRequest(virtualSourcePath, virtualTargetPath string) bool {
  1391. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(virtualSourcePath)
  1392. dstFolder, errDst := c.User.GetVirtualFolderForPath(virtualTargetPath)
  1393. if errSrc != nil && errDst != nil {
  1394. return false
  1395. }
  1396. if errSrc == nil && errDst == nil {
  1397. return sourceFolder.Name != dstFolder.Name
  1398. }
  1399. return true
  1400. }
  1401. func (c *BaseConnection) updateQuotaMoveBetweenVFolders(sourceFolder, dstFolder *vfs.VirtualFolder, initialSize,
  1402. filesSize int64, numFiles int) {
  1403. if sourceFolder.Name == dstFolder.Name {
  1404. // both files are inside the same virtual folder
  1405. if initialSize != -1 {
  1406. dataprovider.UpdateUserFolderQuota(dstFolder, &c.User, -numFiles, -initialSize, false)
  1407. }
  1408. return
  1409. }
  1410. // files are inside different virtual folders
  1411. dataprovider.UpdateUserFolderQuota(sourceFolder, &c.User, -numFiles, -filesSize, false)
  1412. if initialSize == -1 {
  1413. dataprovider.UpdateUserFolderQuota(dstFolder, &c.User, numFiles, filesSize, false)
  1414. return
  1415. }
  1416. // we cannot have a directory here, initialSize != -1 only for files
  1417. dataprovider.UpdateUserFolderQuota(dstFolder, &c.User, 0, filesSize-initialSize, false)
  1418. }
  1419. func (c *BaseConnection) updateQuotaMoveFromVFolder(sourceFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1420. // move between a virtual folder and the user home dir
  1421. dataprovider.UpdateUserFolderQuota(sourceFolder, &c.User, -numFiles, -filesSize, false)
  1422. if initialSize == -1 {
  1423. dataprovider.UpdateUserQuota(&c.User, numFiles, filesSize, false) //nolint:errcheck
  1424. return
  1425. }
  1426. // we cannot have a directory here, initialSize != -1 only for files
  1427. dataprovider.UpdateUserQuota(&c.User, 0, filesSize-initialSize, false) //nolint:errcheck
  1428. }
  1429. func (c *BaseConnection) updateQuotaMoveToVFolder(dstFolder *vfs.VirtualFolder, initialSize, filesSize int64, numFiles int) {
  1430. // move between the user home dir and a virtual folder
  1431. dataprovider.UpdateUserQuota(&c.User, -numFiles, -filesSize, false) //nolint:errcheck
  1432. if initialSize == -1 {
  1433. dataprovider.UpdateUserFolderQuota(dstFolder, &c.User, numFiles, filesSize, false)
  1434. return
  1435. }
  1436. // we cannot have a directory here, initialSize != -1 only for files
  1437. dataprovider.UpdateUserFolderQuota(dstFolder, &c.User, 0, filesSize-initialSize, false)
  1438. }
  1439. func (c *BaseConnection) updateQuotaAfterRename(fs vfs.Fs, virtualSourcePath, virtualTargetPath, targetPath string,
  1440. initialSize int64, numFiles int, filesSize int64,
  1441. ) error {
  1442. if dataprovider.GetQuotaTracking() == 0 {
  1443. return nil
  1444. }
  1445. // we don't allow to overwrite an existing directory so targetPath can be:
  1446. // - a new file, a symlink is as a new file here
  1447. // - a file overwriting an existing one
  1448. // - a new directory
  1449. // initialSize != -1 only when overwriting files
  1450. sourceFolder, errSrc := c.User.GetVirtualFolderForPath(path.Dir(virtualSourcePath))
  1451. dstFolder, errDst := c.User.GetVirtualFolderForPath(path.Dir(virtualTargetPath))
  1452. if errSrc != nil && errDst != nil {
  1453. // both files are contained inside the user home dir
  1454. if initialSize != -1 {
  1455. // we cannot have a directory here, we are overwriting an existing file
  1456. // we need to subtract the size of the overwritten file from the user quota
  1457. dataprovider.UpdateUserQuota(&c.User, -1, -initialSize, false) //nolint:errcheck
  1458. }
  1459. return nil
  1460. }
  1461. if filesSize == -1 {
  1462. // fs.Rename didn't return the affected files/sizes, we need to calculate them
  1463. numFiles = 1
  1464. if fi, err := fs.Stat(targetPath); err == nil {
  1465. if fi.Mode().IsDir() {
  1466. numFiles, filesSize, err = fs.GetDirSize(targetPath)
  1467. if err != nil {
  1468. c.Log(logger.LevelError, "failed to update quota after rename, error scanning moved folder %q: %+v",
  1469. targetPath, err)
  1470. return err
  1471. }
  1472. } else {
  1473. filesSize = fi.Size()
  1474. }
  1475. } else {
  1476. c.Log(logger.LevelError, "failed to update quota after renaming, file %q stat error: %+v", targetPath, err)
  1477. return err
  1478. }
  1479. c.Log(logger.LevelDebug, "calculated renamed files: %d, size: %d bytes", numFiles, filesSize)
  1480. } else {
  1481. c.Log(logger.LevelDebug, "returned renamed files: %d, size: %d bytes", numFiles, filesSize)
  1482. }
  1483. if errSrc == nil && errDst == nil {
  1484. c.updateQuotaMoveBetweenVFolders(&sourceFolder, &dstFolder, initialSize, filesSize, numFiles)
  1485. }
  1486. if errSrc == nil && errDst != nil {
  1487. c.updateQuotaMoveFromVFolder(&sourceFolder, initialSize, filesSize, numFiles)
  1488. }
  1489. if errSrc != nil && errDst == nil {
  1490. c.updateQuotaMoveToVFolder(&dstFolder, initialSize, filesSize, numFiles)
  1491. }
  1492. return nil
  1493. }
  1494. // IsNotExistError returns true if the specified fs error is not exist for the connection protocol
  1495. func (c *BaseConnection) IsNotExistError(err error) bool {
  1496. switch c.protocol {
  1497. case ProtocolSFTP:
  1498. return errors.Is(err, sftp.ErrSSHFxNoSuchFile)
  1499. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1500. return errors.Is(err, os.ErrNotExist)
  1501. default:
  1502. return errors.Is(err, ErrNotExist)
  1503. }
  1504. }
  1505. // GetErrorForDeniedFile return permission denied or not exist error based on the specified policy
  1506. func (c *BaseConnection) GetErrorForDeniedFile(policy int) error {
  1507. switch policy {
  1508. case sdk.DenyPolicyHide:
  1509. return c.GetNotExistError()
  1510. default:
  1511. return c.GetPermissionDeniedError()
  1512. }
  1513. }
  1514. // GetPermissionDeniedError returns an appropriate permission denied error for the connection protocol
  1515. func (c *BaseConnection) GetPermissionDeniedError() error {
  1516. return getPermissionDeniedError(c.protocol)
  1517. }
  1518. // GetNotExistError returns an appropriate not exist error for the connection protocol
  1519. func (c *BaseConnection) GetNotExistError() error {
  1520. switch c.protocol {
  1521. case ProtocolSFTP:
  1522. return sftp.ErrSSHFxNoSuchFile
  1523. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1524. return os.ErrNotExist
  1525. default:
  1526. return ErrNotExist
  1527. }
  1528. }
  1529. // GetOpUnsupportedError returns an appropriate operation not supported error for the connection protocol
  1530. func (c *BaseConnection) GetOpUnsupportedError() error {
  1531. switch c.protocol {
  1532. case ProtocolSFTP:
  1533. return sftp.ErrSSHFxOpUnsupported
  1534. default:
  1535. return ErrOpUnsupported
  1536. }
  1537. }
  1538. func getQuotaExceededError(protocol string) error {
  1539. switch protocol {
  1540. case ProtocolSFTP:
  1541. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, ErrQuotaExceeded)
  1542. case ProtocolFTP:
  1543. return ftpserver.ErrStorageExceeded
  1544. default:
  1545. return ErrQuotaExceeded
  1546. }
  1547. }
  1548. func getReadQuotaExceededError(protocol string) error {
  1549. switch protocol {
  1550. case ProtocolSFTP:
  1551. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, ErrReadQuotaExceeded)
  1552. default:
  1553. return ErrReadQuotaExceeded
  1554. }
  1555. }
  1556. // GetQuotaExceededError returns an appropriate storage limit exceeded error for the connection protocol
  1557. func (c *BaseConnection) GetQuotaExceededError() error {
  1558. return getQuotaExceededError(c.protocol)
  1559. }
  1560. // GetReadQuotaExceededError returns an appropriate read quota limit exceeded error for the connection protocol
  1561. func (c *BaseConnection) GetReadQuotaExceededError() error {
  1562. return getReadQuotaExceededError(c.protocol)
  1563. }
  1564. // IsQuotaExceededError returns true if the given error is a quota exceeded error
  1565. func (c *BaseConnection) IsQuotaExceededError(err error) bool {
  1566. switch c.protocol {
  1567. case ProtocolSFTP:
  1568. if err == nil {
  1569. return false
  1570. }
  1571. if errors.Is(err, ErrQuotaExceeded) {
  1572. return true
  1573. }
  1574. return errors.Is(err, sftp.ErrSSHFxFailure) && strings.Contains(err.Error(), ErrQuotaExceeded.Error())
  1575. case ProtocolFTP:
  1576. return errors.Is(err, ftpserver.ErrStorageExceeded) || errors.Is(err, ErrQuotaExceeded)
  1577. default:
  1578. return errors.Is(err, ErrQuotaExceeded)
  1579. }
  1580. }
  1581. func isSFTPGoError(err error) bool {
  1582. return errors.Is(err, ErrPermissionDenied) || errors.Is(err, ErrNotExist) || errors.Is(err, ErrOpUnsupported) ||
  1583. errors.Is(err, ErrQuotaExceeded) || errors.Is(err, ErrReadQuotaExceeded) ||
  1584. errors.Is(err, vfs.ErrStorageSizeUnavailable) || errors.Is(err, ErrShuttingDown)
  1585. }
  1586. // GetGenericError returns an appropriate generic error for the connection protocol
  1587. func (c *BaseConnection) GetGenericError(err error) error {
  1588. switch c.protocol {
  1589. case ProtocolSFTP:
  1590. if errors.Is(err, vfs.ErrStorageSizeUnavailable) || errors.Is(err, ErrOpUnsupported) || errors.Is(err, sftp.ErrSSHFxOpUnsupported) {
  1591. return fmt.Errorf("%w: %w", sftp.ErrSSHFxOpUnsupported, err)
  1592. }
  1593. if isSFTPGoError(err) {
  1594. return fmt.Errorf("%w: %w", sftp.ErrSSHFxFailure, err)
  1595. }
  1596. if err != nil {
  1597. var pathError *fs.PathError
  1598. if errors.As(err, &pathError) {
  1599. c.Log(logger.LevelError, "generic path error: %+v", pathError)
  1600. return fmt.Errorf("%w: %v %v", sftp.ErrSSHFxFailure, pathError.Op, pathError.Err.Error())
  1601. }
  1602. c.Log(logger.LevelError, "generic error: %+v", err)
  1603. }
  1604. return sftp.ErrSSHFxFailure
  1605. default:
  1606. if isSFTPGoError(err) {
  1607. return err
  1608. }
  1609. c.Log(logger.LevelError, "generic error: %+v", err)
  1610. return ErrGenericFailure
  1611. }
  1612. }
  1613. // GetFsError converts a filesystem error to a protocol error
  1614. func (c *BaseConnection) GetFsError(fs vfs.Fs, err error) error {
  1615. if fs.IsNotExist(err) {
  1616. return c.GetNotExistError()
  1617. } else if fs.IsPermission(err) {
  1618. return c.GetPermissionDeniedError()
  1619. } else if fs.IsNotSupported(err) {
  1620. return c.GetOpUnsupportedError()
  1621. } else if err != nil {
  1622. return c.GetGenericError(err)
  1623. }
  1624. return nil
  1625. }
  1626. func (c *BaseConnection) getNotificationStatus(err error) int {
  1627. if err == nil {
  1628. return 1
  1629. }
  1630. if c.IsQuotaExceededError(err) {
  1631. return 3
  1632. }
  1633. return 2
  1634. }
  1635. // GetFsAndResolvedPath returns the fs and the fs path matching virtualPath
  1636. func (c *BaseConnection) GetFsAndResolvedPath(virtualPath string) (vfs.Fs, string, error) {
  1637. fs, err := c.User.GetFilesystemForPath(virtualPath, c.ID)
  1638. if err != nil {
  1639. if c.protocol == ProtocolWebDAV && strings.Contains(err.Error(), vfs.ErrSFTPLoop.Error()) {
  1640. // if there is an SFTP loop we return a permission error, for WebDAV, so the problematic folder
  1641. // will not be listed
  1642. return nil, "", util.NewI18nError(c.GetPermissionDeniedError(), util.I18nError403Message)
  1643. }
  1644. return nil, "", c.GetGenericError(err)
  1645. }
  1646. if isShuttingDown.Load() {
  1647. return nil, "", c.GetFsError(fs, ErrShuttingDown)
  1648. }
  1649. fsPath, err := fs.ResolvePath(virtualPath)
  1650. if err != nil {
  1651. return nil, "", c.GetFsError(fs, err)
  1652. }
  1653. return fs, fsPath, nil
  1654. }
  1655. // DirListerAt defines a directory lister implementing the ListAt method.
  1656. type DirListerAt struct {
  1657. virtualPath string
  1658. user *dataprovider.User
  1659. info []os.FileInfo
  1660. id string
  1661. protocol string
  1662. mu sync.Mutex
  1663. lister vfs.DirLister
  1664. }
  1665. // Prepend adds the given os.FileInfo as first element of the internal cache
  1666. func (l *DirListerAt) Prepend(fi os.FileInfo) {
  1667. l.mu.Lock()
  1668. defer l.mu.Unlock()
  1669. l.info = slices.Insert(l.info, 0, fi)
  1670. }
  1671. // ListAt implements sftp.ListerAt
  1672. func (l *DirListerAt) ListAt(f []os.FileInfo, _ int64) (int, error) {
  1673. l.mu.Lock()
  1674. defer l.mu.Unlock()
  1675. if len(f) == 0 {
  1676. return 0, errors.New("invalid ListAt destination, zero size")
  1677. }
  1678. if len(f) <= len(l.info) {
  1679. files := make([]os.FileInfo, 0, len(f))
  1680. for idx := range l.info {
  1681. files = append(files, l.info[idx])
  1682. if len(files) == len(f) {
  1683. l.info = l.info[idx+1:]
  1684. n := copy(f, files)
  1685. return n, nil
  1686. }
  1687. }
  1688. }
  1689. limit := len(f) - len(l.info)
  1690. files, err := l.Next(limit)
  1691. n := copy(f, files)
  1692. return n, err
  1693. }
  1694. // Next reads the directory and returns a slice of up to n FileInfo values.
  1695. func (l *DirListerAt) Next(limit int) ([]os.FileInfo, error) {
  1696. for {
  1697. files, err := l.lister.Next(limit)
  1698. if err != nil && !errors.Is(err, io.EOF) {
  1699. logger.Debug(l.protocol, l.id, "error retrieving directory entries: %+v", err)
  1700. return files, err
  1701. }
  1702. files = l.user.FilterListDir(files, l.virtualPath)
  1703. if len(l.info) > 0 {
  1704. files = slices.Concat(l.info, files)
  1705. l.info = nil
  1706. }
  1707. if err != nil || len(files) > 0 {
  1708. return files, err
  1709. }
  1710. }
  1711. }
  1712. // Close closes the DirListerAt
  1713. func (l *DirListerAt) Close() error {
  1714. l.mu.Lock()
  1715. defer l.mu.Unlock()
  1716. return l.lister.Close()
  1717. }
  1718. func (l *DirListerAt) convertError(err error) error {
  1719. if errors.Is(err, io.EOF) {
  1720. return nil
  1721. }
  1722. return err
  1723. }
  1724. func getPermissionDeniedError(protocol string) error {
  1725. switch protocol {
  1726. case ProtocolSFTP:
  1727. return sftp.ErrSSHFxPermissionDenied
  1728. case ProtocolWebDAV, ProtocolFTP, ProtocolHTTP, ProtocolOIDC, ProtocolHTTPShare, ProtocolDataRetention:
  1729. return os.ErrPermission
  1730. default:
  1731. return ErrPermissionDenied
  1732. }
  1733. }
  1734. func keepConnectionAlive(c *BaseConnection, done chan bool, interval time.Duration) {
  1735. ticker := time.NewTicker(interval)
  1736. defer func() {
  1737. ticker.Stop()
  1738. }()
  1739. for {
  1740. select {
  1741. case <-done:
  1742. return
  1743. case <-ticker.C:
  1744. c.UpdateLastActivity()
  1745. }
  1746. }
  1747. }