common.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. // Package common defines code shared among file transfer packages and protocols
  2. package common
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. "github.com/pires/go-proxyproto"
  19. "github.com/drakkan/sftpgo/v2/dataprovider"
  20. "github.com/drakkan/sftpgo/v2/httpclient"
  21. "github.com/drakkan/sftpgo/v2/logger"
  22. "github.com/drakkan/sftpgo/v2/metric"
  23. "github.com/drakkan/sftpgo/v2/util"
  24. "github.com/drakkan/sftpgo/v2/vfs"
  25. )
  26. // constants
  27. const (
  28. logSender = "common"
  29. uploadLogSender = "Upload"
  30. downloadLogSender = "Download"
  31. renameLogSender = "Rename"
  32. rmdirLogSender = "Rmdir"
  33. mkdirLogSender = "Mkdir"
  34. symlinkLogSender = "Symlink"
  35. removeLogSender = "Remove"
  36. chownLogSender = "Chown"
  37. chmodLogSender = "Chmod"
  38. chtimesLogSender = "Chtimes"
  39. truncateLogSender = "Truncate"
  40. operationDownload = "download"
  41. operationUpload = "upload"
  42. operationDelete = "delete"
  43. // Pre-download action name
  44. OperationPreDownload = "pre-download"
  45. // Pre-upload action name
  46. OperationPreUpload = "pre-upload"
  47. operationPreDelete = "pre-delete"
  48. operationRename = "rename"
  49. operationMkdir = "mkdir"
  50. operationRmdir = "rmdir"
  51. // SSH command action name
  52. OperationSSHCmd = "ssh_cmd"
  53. chtimesFormat = "2006-01-02T15:04:05" // YYYY-MM-DDTHH:MM:SS
  54. idleTimeoutCheckInterval = 3 * time.Minute
  55. periodicTimeoutCheckInterval = 1 * time.Minute
  56. )
  57. // Stat flags
  58. const (
  59. StatAttrUIDGID = 1
  60. StatAttrPerms = 2
  61. StatAttrTimes = 4
  62. StatAttrSize = 8
  63. )
  64. // Transfer types
  65. const (
  66. TransferUpload = iota
  67. TransferDownload
  68. )
  69. // Supported protocols
  70. const (
  71. ProtocolSFTP = "SFTP"
  72. ProtocolSCP = "SCP"
  73. ProtocolSSH = "SSH"
  74. ProtocolFTP = "FTP"
  75. ProtocolWebDAV = "DAV"
  76. ProtocolHTTP = "HTTP"
  77. ProtocolHTTPShare = "HTTPShare"
  78. ProtocolDataRetention = "DataRetention"
  79. )
  80. // Upload modes
  81. const (
  82. UploadModeStandard = iota
  83. UploadModeAtomic
  84. UploadModeAtomicWithResume
  85. )
  86. func init() {
  87. Connections.clients = clientsMap{
  88. clients: make(map[string]int),
  89. }
  90. }
  91. // errors definitions
  92. var (
  93. ErrPermissionDenied = errors.New("permission denied")
  94. ErrNotExist = errors.New("no such file or directory")
  95. ErrOpUnsupported = errors.New("operation unsupported")
  96. ErrGenericFailure = errors.New("failure")
  97. ErrQuotaExceeded = errors.New("denying write due to space limit")
  98. ErrReadQuotaExceeded = errors.New("denying read due to quota limit")
  99. ErrSkipPermissionsCheck = errors.New("permission check skipped")
  100. ErrConnectionDenied = errors.New("you are not allowed to connect")
  101. ErrNoBinding = errors.New("no binding configured")
  102. ErrCrtRevoked = errors.New("your certificate has been revoked")
  103. ErrNoCredentials = errors.New("no credential provided")
  104. ErrInternalFailure = errors.New("internal failure")
  105. ErrTransferAborted = errors.New("transfer aborted")
  106. errNoTransfer = errors.New("requested transfer not found")
  107. errTransferMismatch = errors.New("transfer mismatch")
  108. )
  109. var (
  110. // Config is the configuration for the supported protocols
  111. Config Configuration
  112. // Connections is the list of active connections
  113. Connections ActiveConnections
  114. // QuotaScans is the list of active quota scans
  115. QuotaScans ActiveScans
  116. transfersChecker TransfersChecker
  117. periodicTimeoutTicker *time.Ticker
  118. periodicTimeoutTickerDone chan bool
  119. supportedProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP, ProtocolWebDAV,
  120. ProtocolHTTP, ProtocolHTTPShare}
  121. disconnHookProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP}
  122. // the map key is the protocol, for each protocol we can have multiple rate limiters
  123. rateLimiters map[string][]*rateLimiter
  124. )
  125. // Initialize sets the common configuration
  126. func Initialize(c Configuration, isShared int) error {
  127. Config = c
  128. Config.idleLoginTimeout = 2 * time.Minute
  129. Config.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute
  130. startPeriodicTimeoutTicker(periodicTimeoutCheckInterval)
  131. Config.defender = nil
  132. rateLimiters = make(map[string][]*rateLimiter)
  133. for _, rlCfg := range c.RateLimitersConfig {
  134. if rlCfg.isEnabled() {
  135. if err := rlCfg.validate(); err != nil {
  136. return fmt.Errorf("rate limiters initialization error: %v", err)
  137. }
  138. allowList, err := util.ParseAllowedIPAndRanges(rlCfg.AllowList)
  139. if err != nil {
  140. return fmt.Errorf("unable to parse rate limiter allow list %v: %v", rlCfg.AllowList, err)
  141. }
  142. rateLimiter := rlCfg.getLimiter()
  143. rateLimiter.allowList = allowList
  144. for _, protocol := range rlCfg.Protocols {
  145. rateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)
  146. }
  147. }
  148. }
  149. if c.DefenderConfig.Enabled {
  150. if !util.IsStringInSlice(c.DefenderConfig.Driver, supportedDefenderDrivers) {
  151. return fmt.Errorf("unsupported defender driver %#v", c.DefenderConfig.Driver)
  152. }
  153. var defender Defender
  154. var err error
  155. switch c.DefenderConfig.Driver {
  156. case DefenderDriverProvider:
  157. defender, err = newDBDefender(&c.DefenderConfig)
  158. default:
  159. defender, err = newInMemoryDefender(&c.DefenderConfig)
  160. }
  161. if err != nil {
  162. return fmt.Errorf("defender initialization error: %v", err)
  163. }
  164. logger.Info(logSender, "", "defender initialized with config %+v", c.DefenderConfig)
  165. Config.defender = defender
  166. }
  167. vfs.SetTempPath(c.TempPath)
  168. dataprovider.SetTempPath(c.TempPath)
  169. transfersChecker = getTransfersChecker(isShared)
  170. return nil
  171. }
  172. // LimitRate blocks until all the configured rate limiters
  173. // allow one event to happen.
  174. // It returns an error if the time to wait exceeds the max
  175. // allowed delay
  176. func LimitRate(protocol, ip string) (time.Duration, error) {
  177. for _, limiter := range rateLimiters[protocol] {
  178. if delay, err := limiter.Wait(ip); err != nil {
  179. logger.Debug(logSender, "", "protocol %v ip %v: %v", protocol, ip, err)
  180. return delay, err
  181. }
  182. }
  183. return 0, nil
  184. }
  185. // ReloadDefender reloads the defender's block and safe lists
  186. func ReloadDefender() error {
  187. if Config.defender == nil {
  188. return nil
  189. }
  190. return Config.defender.Reload()
  191. }
  192. // IsBanned returns true if the specified IP address is banned
  193. func IsBanned(ip string) bool {
  194. if Config.defender == nil {
  195. return false
  196. }
  197. return Config.defender.IsBanned(ip)
  198. }
  199. // GetDefenderBanTime returns the ban time for the given IP
  200. // or nil if the IP is not banned or the defender is disabled
  201. func GetDefenderBanTime(ip string) (*time.Time, error) {
  202. if Config.defender == nil {
  203. return nil, nil
  204. }
  205. return Config.defender.GetBanTime(ip)
  206. }
  207. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  208. func GetDefenderHosts() ([]dataprovider.DefenderEntry, error) {
  209. if Config.defender == nil {
  210. return nil, nil
  211. }
  212. return Config.defender.GetHosts()
  213. }
  214. // GetDefenderHost returns a defender host by ip, if any
  215. func GetDefenderHost(ip string) (dataprovider.DefenderEntry, error) {
  216. if Config.defender == nil {
  217. return dataprovider.DefenderEntry{}, errors.New("defender is disabled")
  218. }
  219. return Config.defender.GetHost(ip)
  220. }
  221. // DeleteDefenderHost removes the specified IP address from the defender lists
  222. func DeleteDefenderHost(ip string) bool {
  223. if Config.defender == nil {
  224. return false
  225. }
  226. return Config.defender.DeleteHost(ip)
  227. }
  228. // GetDefenderScore returns the score for the given IP
  229. func GetDefenderScore(ip string) (int, error) {
  230. if Config.defender == nil {
  231. return 0, nil
  232. }
  233. return Config.defender.GetScore(ip)
  234. }
  235. // AddDefenderEvent adds the specified defender event for the given IP
  236. func AddDefenderEvent(ip string, event HostEvent) {
  237. if Config.defender == nil {
  238. return
  239. }
  240. Config.defender.AddEvent(ip, event)
  241. }
  242. // the ticker cannot be started/stopped from multiple goroutines
  243. func startPeriodicTimeoutTicker(duration time.Duration) {
  244. stopPeriodicTimeoutTicker()
  245. periodicTimeoutTicker = time.NewTicker(duration)
  246. periodicTimeoutTickerDone = make(chan bool)
  247. go func() {
  248. counter := int64(0)
  249. ratio := idleTimeoutCheckInterval / periodicTimeoutCheckInterval
  250. for {
  251. select {
  252. case <-periodicTimeoutTickerDone:
  253. return
  254. case <-periodicTimeoutTicker.C:
  255. counter++
  256. if Config.IdleTimeout > 0 && counter >= int64(ratio) {
  257. counter = 0
  258. Connections.checkIdles()
  259. }
  260. go Connections.checkTransfers()
  261. }
  262. }
  263. }()
  264. }
  265. func stopPeriodicTimeoutTicker() {
  266. if periodicTimeoutTicker != nil {
  267. periodicTimeoutTicker.Stop()
  268. periodicTimeoutTickerDone <- true
  269. periodicTimeoutTicker = nil
  270. }
  271. }
  272. // ActiveTransfer defines the interface for the current active transfers
  273. type ActiveTransfer interface {
  274. GetID() int64
  275. GetType() int
  276. GetSize() int64
  277. GetDownloadedSize() int64
  278. GetUploadedSize() int64
  279. GetVirtualPath() string
  280. GetStartTime() time.Time
  281. SignalClose(err error)
  282. Truncate(fsPath string, size int64) (int64, error)
  283. GetRealFsPath(fsPath string) string
  284. SetTimes(fsPath string, atime time.Time, mtime time.Time) bool
  285. GetTruncatedSize() int64
  286. HasSizeLimit() bool
  287. }
  288. // ActiveConnection defines the interface for the current active connections
  289. type ActiveConnection interface {
  290. GetID() string
  291. GetUsername() string
  292. GetLocalAddress() string
  293. GetRemoteAddress() string
  294. GetClientVersion() string
  295. GetProtocol() string
  296. GetConnectionTime() time.Time
  297. GetLastActivity() time.Time
  298. GetCommand() string
  299. Disconnect() error
  300. AddTransfer(t ActiveTransfer)
  301. RemoveTransfer(t ActiveTransfer)
  302. GetTransfers() []ConnectionTransfer
  303. SignalTransferClose(transferID int64, err error)
  304. CloseFS() error
  305. }
  306. // StatAttributes defines the attributes for set stat commands
  307. type StatAttributes struct {
  308. Mode os.FileMode
  309. Atime time.Time
  310. Mtime time.Time
  311. UID int
  312. GID int
  313. Flags int
  314. Size int64
  315. }
  316. // ConnectionTransfer defines the trasfer details to expose
  317. type ConnectionTransfer struct {
  318. ID int64 `json:"-"`
  319. OperationType string `json:"operation_type"`
  320. StartTime int64 `json:"start_time"`
  321. Size int64 `json:"size"`
  322. VirtualPath string `json:"path"`
  323. HasSizeLimit bool `json:"-"`
  324. ULSize int64 `json:"-"`
  325. DLSize int64 `json:"-"`
  326. }
  327. func (t *ConnectionTransfer) getConnectionTransferAsString() string {
  328. result := ""
  329. switch t.OperationType {
  330. case operationUpload:
  331. result += "UL "
  332. case operationDownload:
  333. result += "DL "
  334. }
  335. result += fmt.Sprintf("%#v ", t.VirtualPath)
  336. if t.Size > 0 {
  337. elapsed := time.Since(util.GetTimeFromMsecSinceEpoch(t.StartTime))
  338. speed := float64(t.Size) / float64(util.GetTimeAsMsSinceEpoch(time.Now())-t.StartTime)
  339. result += fmt.Sprintf("Size: %#v Elapsed: %#v Speed: \"%.1f KB/s\"", util.ByteCountIEC(t.Size),
  340. util.GetDurationAsString(elapsed), speed)
  341. }
  342. return result
  343. }
  344. // Configuration defines configuration parameters common to all supported protocols
  345. type Configuration struct {
  346. // Maximum idle timeout as minutes. If a client is idle for a time that exceeds this setting it will be disconnected.
  347. // 0 means disabled
  348. IdleTimeout int `json:"idle_timeout" mapstructure:"idle_timeout"`
  349. // UploadMode 0 means standard, the files are uploaded directly to the requested path.
  350. // 1 means atomic: the files are uploaded to a temporary path and renamed to the requested path
  351. // when the client ends the upload. Atomic mode avoid problems such as a web server that
  352. // serves partial files when the files are being uploaded.
  353. // In atomic mode if there is an upload error the temporary file is deleted and so the requested
  354. // upload path will not contain a partial file.
  355. // 2 means atomic with resume support: as atomic but if there is an upload error the temporary
  356. // file is renamed to the requested path and not deleted, this way a client can reconnect and resume
  357. // the upload.
  358. UploadMode int `json:"upload_mode" mapstructure:"upload_mode"`
  359. // Actions to execute for SFTP file operations and SSH commands
  360. Actions ProtocolActions `json:"actions" mapstructure:"actions"`
  361. // SetstatMode 0 means "normal mode": requests for changing permissions and owner/group are executed.
  362. // 1 means "ignore mode": requests for changing permissions and owner/group are silently ignored.
  363. // 2 means "ignore mode for cloud fs": requests for changing permissions and owner/group are
  364. // silently ignored for cloud based filesystem such as S3, GCS, Azure Blob. Requests for changing
  365. // modification times are ignored for cloud based filesystem if they are not supported.
  366. SetstatMode int `json:"setstat_mode" mapstructure:"setstat_mode"`
  367. // TempPath defines the path for temporary files such as those used for atomic uploads or file pipes.
  368. // If you set this option you must make sure that the defined path exists, is accessible for writing
  369. // by the user running SFTPGo, and is on the same filesystem as the users home directories otherwise
  370. // the renaming for atomic uploads will become a copy and therefore may take a long time.
  371. // The temporary files are not namespaced. The default is generally fine. Leave empty for the default.
  372. TempPath string `json:"temp_path" mapstructure:"temp_path"`
  373. // Support for HAProxy PROXY protocol.
  374. // If you are running SFTPGo behind a proxy server such as HAProxy, AWS ELB or NGNIX, you can enable
  375. // the proxy protocol. It provides a convenient way to safely transport connection information
  376. // such as a client's address across multiple layers of NAT or TCP proxies to get the real
  377. // client IP address instead of the proxy IP. Both protocol versions 1 and 2 are supported.
  378. // - 0 means disabled
  379. // - 1 means proxy protocol enabled. Proxy header will be used and requests without proxy header will be accepted.
  380. // - 2 means proxy protocol required. Proxy header will be used and requests without proxy header will be rejected.
  381. // If the proxy protocol is enabled in SFTPGo then you have to enable the protocol in your proxy configuration too,
  382. // for example for HAProxy add "send-proxy" or "send-proxy-v2" to each server configuration line.
  383. ProxyProtocol int `json:"proxy_protocol" mapstructure:"proxy_protocol"`
  384. // List of IP addresses and IP ranges allowed to send the proxy header.
  385. // If proxy protocol is set to 1 and we receive a proxy header from an IP that is not in the list then the
  386. // connection will be accepted and the header will be ignored.
  387. // If proxy protocol is set to 2 and we receive a proxy header from an IP that is not in the list then the
  388. // connection will be rejected.
  389. ProxyAllowed []string `json:"proxy_allowed" mapstructure:"proxy_allowed"`
  390. // Absolute path to an external program or an HTTP URL to invoke as soon as SFTPGo starts.
  391. // If you define an HTTP URL it will be invoked using a `GET` request.
  392. // Please note that SFTPGo services may not yet be available when this hook is run.
  393. // Leave empty do disable.
  394. StartupHook string `json:"startup_hook" mapstructure:"startup_hook"`
  395. // Absolute path to an external program or an HTTP URL to invoke after a user connects
  396. // and before he tries to login. It allows you to reject the connection based on the source
  397. // ip address. Leave empty do disable.
  398. PostConnectHook string `json:"post_connect_hook" mapstructure:"post_connect_hook"`
  399. // Absolute path to an external program or an HTTP URL to invoke after an SSH/FTP connection ends.
  400. // Leave empty do disable.
  401. PostDisconnectHook string `json:"post_disconnect_hook" mapstructure:"post_disconnect_hook"`
  402. // Absolute path to an external program or an HTTP URL to invoke after a data retention check completes.
  403. // Leave empty do disable.
  404. DataRetentionHook string `json:"data_retention_hook" mapstructure:"data_retention_hook"`
  405. // Maximum number of concurrent client connections. 0 means unlimited
  406. MaxTotalConnections int `json:"max_total_connections" mapstructure:"max_total_connections"`
  407. // Maximum number of concurrent client connections from the same host (IP). 0 means unlimited
  408. MaxPerHostConnections int `json:"max_per_host_connections" mapstructure:"max_per_host_connections"`
  409. // Defender configuration
  410. DefenderConfig DefenderConfig `json:"defender" mapstructure:"defender"`
  411. // Rate limiter configurations
  412. RateLimitersConfig []RateLimiterConfig `json:"rate_limiters" mapstructure:"rate_limiters"`
  413. idleTimeoutAsDuration time.Duration
  414. idleLoginTimeout time.Duration
  415. defender Defender
  416. }
  417. // IsAtomicUploadEnabled returns true if atomic upload is enabled
  418. func (c *Configuration) IsAtomicUploadEnabled() bool {
  419. return c.UploadMode == UploadModeAtomic || c.UploadMode == UploadModeAtomicWithResume
  420. }
  421. // GetProxyListener returns a wrapper for the given listener that supports the
  422. // HAProxy Proxy Protocol
  423. func (c *Configuration) GetProxyListener(listener net.Listener) (*proxyproto.Listener, error) {
  424. var err error
  425. if c.ProxyProtocol > 0 {
  426. var policyFunc func(upstream net.Addr) (proxyproto.Policy, error)
  427. if c.ProxyProtocol == 1 && len(c.ProxyAllowed) > 0 {
  428. policyFunc, err = proxyproto.LaxWhiteListPolicy(c.ProxyAllowed)
  429. if err != nil {
  430. return nil, err
  431. }
  432. }
  433. if c.ProxyProtocol == 2 {
  434. if len(c.ProxyAllowed) == 0 {
  435. policyFunc = func(upstream net.Addr) (proxyproto.Policy, error) {
  436. return proxyproto.REQUIRE, nil
  437. }
  438. } else {
  439. policyFunc, err = proxyproto.StrictWhiteListPolicy(c.ProxyAllowed)
  440. if err != nil {
  441. return nil, err
  442. }
  443. }
  444. }
  445. return &proxyproto.Listener{
  446. Listener: listener,
  447. Policy: policyFunc,
  448. ReadHeaderTimeout: 5 * time.Second,
  449. }, nil
  450. }
  451. return nil, errors.New("proxy protocol not configured")
  452. }
  453. // ExecuteStartupHook runs the startup hook if defined
  454. func (c *Configuration) ExecuteStartupHook() error {
  455. if c.StartupHook == "" {
  456. return nil
  457. }
  458. if strings.HasPrefix(c.StartupHook, "http") {
  459. var url *url.URL
  460. url, err := url.Parse(c.StartupHook)
  461. if err != nil {
  462. logger.Warn(logSender, "", "Invalid startup hook %#v: %v", c.StartupHook, err)
  463. return err
  464. }
  465. startTime := time.Now()
  466. resp, err := httpclient.RetryableGet(url.String())
  467. if err != nil {
  468. logger.Warn(logSender, "", "Error executing startup hook: %v", err)
  469. return err
  470. }
  471. defer resp.Body.Close()
  472. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, response code: %v", time.Since(startTime), resp.StatusCode)
  473. return nil
  474. }
  475. if !filepath.IsAbs(c.StartupHook) {
  476. err := fmt.Errorf("invalid startup hook %#v", c.StartupHook)
  477. logger.Warn(logSender, "", "Invalid startup hook %#v", c.StartupHook)
  478. return err
  479. }
  480. startTime := time.Now()
  481. ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
  482. defer cancel()
  483. cmd := exec.CommandContext(ctx, c.StartupHook)
  484. err := cmd.Run()
  485. logger.Debug(logSender, "", "Startup hook executed, elapsed: %v, error: %v", time.Since(startTime), err)
  486. return nil
  487. }
  488. func (c *Configuration) executePostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  489. ipAddr := util.GetIPFromRemoteAddress(remoteAddr)
  490. connDuration := int64(time.Since(connectionTime) / time.Millisecond)
  491. if strings.HasPrefix(c.PostDisconnectHook, "http") {
  492. var url *url.URL
  493. url, err := url.Parse(c.PostDisconnectHook)
  494. if err != nil {
  495. logger.Warn(protocol, connID, "Invalid post disconnect hook %#v: %v", c.PostDisconnectHook, err)
  496. return
  497. }
  498. q := url.Query()
  499. q.Add("ip", ipAddr)
  500. q.Add("protocol", protocol)
  501. q.Add("username", username)
  502. q.Add("connection_duration", strconv.FormatInt(connDuration, 10))
  503. url.RawQuery = q.Encode()
  504. startTime := time.Now()
  505. resp, err := httpclient.RetryableGet(url.String())
  506. respCode := 0
  507. if err == nil {
  508. respCode = resp.StatusCode
  509. resp.Body.Close()
  510. }
  511. logger.Debug(protocol, connID, "Post disconnect hook response code: %v, elapsed: %v, err: %v",
  512. respCode, time.Since(startTime), err)
  513. return
  514. }
  515. if !filepath.IsAbs(c.PostDisconnectHook) {
  516. logger.Debug(protocol, connID, "invalid post disconnect hook %#v", c.PostDisconnectHook)
  517. return
  518. }
  519. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  520. defer cancel()
  521. startTime := time.Now()
  522. cmd := exec.CommandContext(ctx, c.PostDisconnectHook)
  523. cmd.Env = append(os.Environ(),
  524. fmt.Sprintf("SFTPGO_CONNECTION_IP=%v", ipAddr),
  525. fmt.Sprintf("SFTPGO_CONNECTION_USERNAME=%v", username),
  526. fmt.Sprintf("SFTPGO_CONNECTION_DURATION=%v", connDuration),
  527. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%v", protocol))
  528. err := cmd.Run()
  529. logger.Debug(protocol, connID, "Post disconnect hook executed, elapsed: %v error: %v", time.Since(startTime), err)
  530. }
  531. func (c *Configuration) checkPostDisconnectHook(remoteAddr, protocol, username, connID string, connectionTime time.Time) {
  532. if c.PostDisconnectHook == "" {
  533. return
  534. }
  535. if !util.IsStringInSlice(protocol, disconnHookProtocols) {
  536. return
  537. }
  538. go c.executePostDisconnectHook(remoteAddr, protocol, username, connID, connectionTime)
  539. }
  540. // ExecutePostConnectHook executes the post connect hook if defined
  541. func (c *Configuration) ExecutePostConnectHook(ipAddr, protocol string) error {
  542. if c.PostConnectHook == "" {
  543. return nil
  544. }
  545. if strings.HasPrefix(c.PostConnectHook, "http") {
  546. var url *url.URL
  547. url, err := url.Parse(c.PostConnectHook)
  548. if err != nil {
  549. logger.Warn(protocol, "", "Login from ip %#v denied, invalid post connect hook %#v: %v",
  550. ipAddr, c.PostConnectHook, err)
  551. return err
  552. }
  553. q := url.Query()
  554. q.Add("ip", ipAddr)
  555. q.Add("protocol", protocol)
  556. url.RawQuery = q.Encode()
  557. resp, err := httpclient.RetryableGet(url.String())
  558. if err != nil {
  559. logger.Warn(protocol, "", "Login from ip %#v denied, error executing post connect hook: %v", ipAddr, err)
  560. return err
  561. }
  562. defer resp.Body.Close()
  563. if resp.StatusCode != http.StatusOK {
  564. logger.Warn(protocol, "", "Login from ip %#v denied, post connect hook response code: %v", ipAddr, resp.StatusCode)
  565. return errUnexpectedHTTResponse
  566. }
  567. return nil
  568. }
  569. if !filepath.IsAbs(c.PostConnectHook) {
  570. err := fmt.Errorf("invalid post connect hook %#v", c.PostConnectHook)
  571. logger.Warn(protocol, "", "Login from ip %#v denied: %v", ipAddr, err)
  572. return err
  573. }
  574. ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
  575. defer cancel()
  576. cmd := exec.CommandContext(ctx, c.PostConnectHook)
  577. cmd.Env = append(os.Environ(),
  578. fmt.Sprintf("SFTPGO_CONNECTION_IP=%v", ipAddr),
  579. fmt.Sprintf("SFTPGO_CONNECTION_PROTOCOL=%v", protocol))
  580. err := cmd.Run()
  581. if err != nil {
  582. logger.Warn(protocol, "", "Login from ip %#v denied, connect hook error: %v", ipAddr, err)
  583. }
  584. return err
  585. }
  586. // SSHConnection defines an ssh connection.
  587. // Each SSH connection can open several channels for SFTP or SSH commands
  588. type SSHConnection struct {
  589. id string
  590. conn net.Conn
  591. lastActivity int64
  592. }
  593. // NewSSHConnection returns a new SSHConnection
  594. func NewSSHConnection(id string, conn net.Conn) *SSHConnection {
  595. return &SSHConnection{
  596. id: id,
  597. conn: conn,
  598. lastActivity: time.Now().UnixNano(),
  599. }
  600. }
  601. // GetID returns the ID for this SSHConnection
  602. func (c *SSHConnection) GetID() string {
  603. return c.id
  604. }
  605. // UpdateLastActivity updates last activity for this connection
  606. func (c *SSHConnection) UpdateLastActivity() {
  607. atomic.StoreInt64(&c.lastActivity, time.Now().UnixNano())
  608. }
  609. // GetLastActivity returns the last connection activity
  610. func (c *SSHConnection) GetLastActivity() time.Time {
  611. return time.Unix(0, atomic.LoadInt64(&c.lastActivity))
  612. }
  613. // Close closes the underlying network connection
  614. func (c *SSHConnection) Close() error {
  615. return c.conn.Close()
  616. }
  617. // ActiveConnections holds the currect active connections with the associated transfers
  618. type ActiveConnections struct {
  619. // clients contains both authenticated and estabilished connections and the ones waiting
  620. // for authentication
  621. clients clientsMap
  622. transfersCheckStatus int32
  623. sync.RWMutex
  624. connections []ActiveConnection
  625. sshConnections []*SSHConnection
  626. }
  627. // GetActiveSessions returns the number of active sessions for the given username.
  628. // We return the open sessions for any protocol
  629. func (conns *ActiveConnections) GetActiveSessions(username string) int {
  630. conns.RLock()
  631. defer conns.RUnlock()
  632. numSessions := 0
  633. for _, c := range conns.connections {
  634. if c.GetUsername() == username {
  635. numSessions++
  636. }
  637. }
  638. return numSessions
  639. }
  640. // Add adds a new connection to the active ones
  641. func (conns *ActiveConnections) Add(c ActiveConnection) {
  642. conns.Lock()
  643. defer conns.Unlock()
  644. conns.connections = append(conns.connections, c)
  645. metric.UpdateActiveConnectionsSize(len(conns.connections))
  646. logger.Debug(c.GetProtocol(), c.GetID(), "connection added, local address %#v, remote address %#v, num open connections: %v",
  647. c.GetLocalAddress(), c.GetRemoteAddress(), len(conns.connections))
  648. }
  649. // Swap replaces an existing connection with the given one.
  650. // This method is useful if you have to change some connection details
  651. // for example for FTP is used to update the connection once the user
  652. // authenticates
  653. func (conns *ActiveConnections) Swap(c ActiveConnection) error {
  654. conns.Lock()
  655. defer conns.Unlock()
  656. for idx, conn := range conns.connections {
  657. if conn.GetID() == c.GetID() {
  658. err := conn.CloseFS()
  659. conns.connections[idx] = c
  660. logger.Debug(logSender, c.GetID(), "connection swapped, close fs error: %v", err)
  661. conn = nil
  662. return nil
  663. }
  664. }
  665. return errors.New("connection to swap not found")
  666. }
  667. // Remove removes a connection from the active ones
  668. func (conns *ActiveConnections) Remove(connectionID string) {
  669. conns.Lock()
  670. defer conns.Unlock()
  671. for idx, conn := range conns.connections {
  672. if conn.GetID() == connectionID {
  673. err := conn.CloseFS()
  674. lastIdx := len(conns.connections) - 1
  675. conns.connections[idx] = conns.connections[lastIdx]
  676. conns.connections[lastIdx] = nil
  677. conns.connections = conns.connections[:lastIdx]
  678. metric.UpdateActiveConnectionsSize(lastIdx)
  679. logger.Debug(conn.GetProtocol(), conn.GetID(), "connection removed, local address %#v, remote address %#v close fs error: %v, num open connections: %v",
  680. conn.GetLocalAddress(), conn.GetRemoteAddress(), err, lastIdx)
  681. Config.checkPostDisconnectHook(conn.GetRemoteAddress(), conn.GetProtocol(), conn.GetUsername(),
  682. conn.GetID(), conn.GetConnectionTime())
  683. return
  684. }
  685. }
  686. logger.Warn(logSender, "", "connection id %#v to remove not found!", connectionID)
  687. }
  688. // Close closes an active connection.
  689. // It returns true on success
  690. func (conns *ActiveConnections) Close(connectionID string) bool {
  691. conns.RLock()
  692. result := false
  693. for _, c := range conns.connections {
  694. if c.GetID() == connectionID {
  695. defer func(conn ActiveConnection) {
  696. err := conn.Disconnect()
  697. logger.Debug(conn.GetProtocol(), conn.GetID(), "close connection requested, close err: %v", err)
  698. }(c)
  699. result = true
  700. break
  701. }
  702. }
  703. conns.RUnlock()
  704. return result
  705. }
  706. // AddSSHConnection adds a new ssh connection to the active ones
  707. func (conns *ActiveConnections) AddSSHConnection(c *SSHConnection) {
  708. conns.Lock()
  709. defer conns.Unlock()
  710. conns.sshConnections = append(conns.sshConnections, c)
  711. logger.Debug(logSender, c.GetID(), "ssh connection added, num open connections: %v", len(conns.sshConnections))
  712. }
  713. // RemoveSSHConnection removes a connection from the active ones
  714. func (conns *ActiveConnections) RemoveSSHConnection(connectionID string) {
  715. conns.Lock()
  716. defer conns.Unlock()
  717. for idx, conn := range conns.sshConnections {
  718. if conn.GetID() == connectionID {
  719. lastIdx := len(conns.sshConnections) - 1
  720. conns.sshConnections[idx] = conns.sshConnections[lastIdx]
  721. conns.sshConnections[lastIdx] = nil
  722. conns.sshConnections = conns.sshConnections[:lastIdx]
  723. logger.Debug(logSender, conn.GetID(), "ssh connection removed, num open ssh connections: %v", lastIdx)
  724. return
  725. }
  726. }
  727. logger.Warn(logSender, "", "ssh connection to remove with id %#v not found!", connectionID)
  728. }
  729. func (conns *ActiveConnections) checkIdles() {
  730. conns.RLock()
  731. for _, sshConn := range conns.sshConnections {
  732. idleTime := time.Since(sshConn.GetLastActivity())
  733. if idleTime > Config.idleTimeoutAsDuration {
  734. // we close the an ssh connection if it has no active connections associated
  735. idToMatch := fmt.Sprintf("_%v_", sshConn.GetID())
  736. toClose := true
  737. for _, conn := range conns.connections {
  738. if strings.Contains(conn.GetID(), idToMatch) {
  739. toClose = false
  740. break
  741. }
  742. }
  743. if toClose {
  744. defer func(c *SSHConnection) {
  745. err := c.Close()
  746. logger.Debug(logSender, c.GetID(), "close idle SSH connection, idle time: %v, close err: %v",
  747. time.Since(c.GetLastActivity()), err)
  748. }(sshConn)
  749. }
  750. }
  751. }
  752. for _, c := range conns.connections {
  753. idleTime := time.Since(c.GetLastActivity())
  754. isUnauthenticatedFTPUser := (c.GetProtocol() == ProtocolFTP && c.GetUsername() == "")
  755. if idleTime > Config.idleTimeoutAsDuration || (isUnauthenticatedFTPUser && idleTime > Config.idleLoginTimeout) {
  756. defer func(conn ActiveConnection, isFTPNoAuth bool) {
  757. err := conn.Disconnect()
  758. logger.Debug(conn.GetProtocol(), conn.GetID(), "close idle connection, idle time: %v, username: %#v close err: %v",
  759. time.Since(conn.GetLastActivity()), conn.GetUsername(), err)
  760. if isFTPNoAuth {
  761. ip := util.GetIPFromRemoteAddress(c.GetRemoteAddress())
  762. logger.ConnectionFailedLog("", ip, dataprovider.LoginMethodNoAuthTryed, c.GetProtocol(), "client idle")
  763. metric.AddNoAuthTryed()
  764. AddDefenderEvent(ip, HostEventNoLoginTried)
  765. dataprovider.ExecutePostLoginHook(&dataprovider.User{}, dataprovider.LoginMethodNoAuthTryed, ip, c.GetProtocol(),
  766. dataprovider.ErrNoAuthTryed)
  767. }
  768. }(c, isUnauthenticatedFTPUser)
  769. }
  770. }
  771. conns.RUnlock()
  772. }
  773. func (conns *ActiveConnections) checkTransfers() {
  774. if atomic.LoadInt32(&conns.transfersCheckStatus) == 1 {
  775. logger.Warn(logSender, "", "the previous transfer check is still running, skipping execution")
  776. return
  777. }
  778. atomic.StoreInt32(&conns.transfersCheckStatus, 1)
  779. defer atomic.StoreInt32(&conns.transfersCheckStatus, 0)
  780. conns.RLock()
  781. if len(conns.connections) < 2 {
  782. conns.RUnlock()
  783. return
  784. }
  785. var wg sync.WaitGroup
  786. logger.Debug(logSender, "", "start concurrent transfers check")
  787. // update the current size for transfers to monitors
  788. for _, c := range conns.connections {
  789. for _, t := range c.GetTransfers() {
  790. if t.HasSizeLimit {
  791. wg.Add(1)
  792. go func(transfer ConnectionTransfer, connID string) {
  793. defer wg.Done()
  794. transfersChecker.UpdateTransferCurrentSizes(transfer.ULSize, transfer.DLSize, transfer.ID, connID)
  795. }(t, c.GetID())
  796. }
  797. }
  798. }
  799. conns.RUnlock()
  800. logger.Debug(logSender, "", "waiting for the update of the transfers current size")
  801. wg.Wait()
  802. logger.Debug(logSender, "", "getting overquota transfers")
  803. overquotaTransfers := transfersChecker.GetOverquotaTransfers()
  804. logger.Debug(logSender, "", "number of overquota transfers: %v", len(overquotaTransfers))
  805. if len(overquotaTransfers) == 0 {
  806. return
  807. }
  808. conns.RLock()
  809. defer conns.RUnlock()
  810. for _, c := range conns.connections {
  811. for _, overquotaTransfer := range overquotaTransfers {
  812. if c.GetID() == overquotaTransfer.ConnID {
  813. logger.Info(logSender, c.GetID(), "user %#v is overquota, try to close transfer id %v",
  814. c.GetUsername(), overquotaTransfer.TransferID)
  815. var err error
  816. if overquotaTransfer.TransferType == TransferDownload {
  817. err = getReadQuotaExceededError(c.GetProtocol())
  818. } else {
  819. err = getQuotaExceededError(c.GetProtocol())
  820. }
  821. c.SignalTransferClose(overquotaTransfer.TransferID, err)
  822. }
  823. }
  824. }
  825. logger.Debug(logSender, "", "transfers check completed")
  826. }
  827. // AddClientConnection stores a new client connection
  828. func (conns *ActiveConnections) AddClientConnection(ipAddr string) {
  829. conns.clients.add(ipAddr)
  830. }
  831. // RemoveClientConnection removes a disconnected client from the tracked ones
  832. func (conns *ActiveConnections) RemoveClientConnection(ipAddr string) {
  833. conns.clients.remove(ipAddr)
  834. }
  835. // GetClientConnections returns the total number of client connections
  836. func (conns *ActiveConnections) GetClientConnections() int32 {
  837. return conns.clients.getTotal()
  838. }
  839. // IsNewConnectionAllowed returns false if the maximum number of concurrent allowed connections is exceeded
  840. func (conns *ActiveConnections) IsNewConnectionAllowed(ipAddr string) bool {
  841. if Config.MaxTotalConnections == 0 && Config.MaxPerHostConnections == 0 {
  842. return true
  843. }
  844. if Config.MaxPerHostConnections > 0 {
  845. if total := conns.clients.getTotalFrom(ipAddr); total > Config.MaxPerHostConnections {
  846. logger.Debug(logSender, "", "active connections from %v %v/%v", ipAddr, total, Config.MaxPerHostConnections)
  847. AddDefenderEvent(ipAddr, HostEventLimitExceeded)
  848. return false
  849. }
  850. }
  851. if Config.MaxTotalConnections > 0 {
  852. if total := conns.clients.getTotal(); total > int32(Config.MaxTotalConnections) {
  853. logger.Debug(logSender, "", "active client connections %v/%v", total, Config.MaxTotalConnections)
  854. return false
  855. }
  856. // on a single SFTP connection we could have multiple SFTP channels or commands
  857. // so we check the estabilished connections too
  858. conns.RLock()
  859. defer conns.RUnlock()
  860. return len(conns.connections) < Config.MaxTotalConnections
  861. }
  862. return true
  863. }
  864. // GetStats returns stats for active connections
  865. func (conns *ActiveConnections) GetStats() []ConnectionStatus {
  866. conns.RLock()
  867. defer conns.RUnlock()
  868. stats := make([]ConnectionStatus, 0, len(conns.connections))
  869. for _, c := range conns.connections {
  870. stat := ConnectionStatus{
  871. Username: c.GetUsername(),
  872. ConnectionID: c.GetID(),
  873. ClientVersion: c.GetClientVersion(),
  874. RemoteAddress: c.GetRemoteAddress(),
  875. ConnectionTime: util.GetTimeAsMsSinceEpoch(c.GetConnectionTime()),
  876. LastActivity: util.GetTimeAsMsSinceEpoch(c.GetLastActivity()),
  877. Protocol: c.GetProtocol(),
  878. Command: c.GetCommand(),
  879. Transfers: c.GetTransfers(),
  880. }
  881. stats = append(stats, stat)
  882. }
  883. return stats
  884. }
  885. // ConnectionStatus returns the status for an active connection
  886. type ConnectionStatus struct {
  887. // Logged in username
  888. Username string `json:"username"`
  889. // Unique identifier for the connection
  890. ConnectionID string `json:"connection_id"`
  891. // client's version string
  892. ClientVersion string `json:"client_version,omitempty"`
  893. // Remote address for this connection
  894. RemoteAddress string `json:"remote_address"`
  895. // Connection time as unix timestamp in milliseconds
  896. ConnectionTime int64 `json:"connection_time"`
  897. // Last activity as unix timestamp in milliseconds
  898. LastActivity int64 `json:"last_activity"`
  899. // Protocol for this connection
  900. Protocol string `json:"protocol"`
  901. // active uploads/downloads
  902. Transfers []ConnectionTransfer `json:"active_transfers,omitempty"`
  903. // SSH command or WebDAV method
  904. Command string `json:"command,omitempty"`
  905. }
  906. // GetConnectionDuration returns the connection duration as string
  907. func (c *ConnectionStatus) GetConnectionDuration() string {
  908. elapsed := time.Since(util.GetTimeFromMsecSinceEpoch(c.ConnectionTime))
  909. return util.GetDurationAsString(elapsed)
  910. }
  911. // GetConnectionInfo returns connection info.
  912. // Protocol,Client Version and RemoteAddress are returned.
  913. func (c *ConnectionStatus) GetConnectionInfo() string {
  914. var result strings.Builder
  915. result.WriteString(fmt.Sprintf("%v. Client: %#v From: %#v", c.Protocol, c.ClientVersion, c.RemoteAddress))
  916. if c.Command == "" {
  917. return result.String()
  918. }
  919. switch c.Protocol {
  920. case ProtocolSSH, ProtocolFTP:
  921. result.WriteString(fmt.Sprintf(". Command: %#v", c.Command))
  922. case ProtocolWebDAV:
  923. result.WriteString(fmt.Sprintf(". Method: %#v", c.Command))
  924. }
  925. return result.String()
  926. }
  927. // GetTransfersAsString returns the active transfers as string
  928. func (c *ConnectionStatus) GetTransfersAsString() string {
  929. result := ""
  930. for _, t := range c.Transfers {
  931. if result != "" {
  932. result += ". "
  933. }
  934. result += t.getConnectionTransferAsString()
  935. }
  936. return result
  937. }
  938. // ActiveQuotaScan defines an active quota scan for a user home dir
  939. type ActiveQuotaScan struct {
  940. // Username to which the quota scan refers
  941. Username string `json:"username"`
  942. // quota scan start time as unix timestamp in milliseconds
  943. StartTime int64 `json:"start_time"`
  944. }
  945. // ActiveVirtualFolderQuotaScan defines an active quota scan for a virtual folder
  946. type ActiveVirtualFolderQuotaScan struct {
  947. // folder name to which the quota scan refers
  948. Name string `json:"name"`
  949. // quota scan start time as unix timestamp in milliseconds
  950. StartTime int64 `json:"start_time"`
  951. }
  952. // ActiveScans holds the active quota scans
  953. type ActiveScans struct {
  954. sync.RWMutex
  955. UserScans []ActiveQuotaScan
  956. FolderScans []ActiveVirtualFolderQuotaScan
  957. }
  958. // GetUsersQuotaScans returns the active quota scans for users home directories
  959. func (s *ActiveScans) GetUsersQuotaScans() []ActiveQuotaScan {
  960. s.RLock()
  961. defer s.RUnlock()
  962. scans := make([]ActiveQuotaScan, len(s.UserScans))
  963. copy(scans, s.UserScans)
  964. return scans
  965. }
  966. // AddUserQuotaScan adds a user to the ones with active quota scans.
  967. // Returns false if the user has a quota scan already running
  968. func (s *ActiveScans) AddUserQuotaScan(username string) bool {
  969. s.Lock()
  970. defer s.Unlock()
  971. for _, scan := range s.UserScans {
  972. if scan.Username == username {
  973. return false
  974. }
  975. }
  976. s.UserScans = append(s.UserScans, ActiveQuotaScan{
  977. Username: username,
  978. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  979. })
  980. return true
  981. }
  982. // RemoveUserQuotaScan removes a user from the ones with active quota scans.
  983. // Returns false if the user has no active quota scans
  984. func (s *ActiveScans) RemoveUserQuotaScan(username string) bool {
  985. s.Lock()
  986. defer s.Unlock()
  987. for idx, scan := range s.UserScans {
  988. if scan.Username == username {
  989. lastIdx := len(s.UserScans) - 1
  990. s.UserScans[idx] = s.UserScans[lastIdx]
  991. s.UserScans = s.UserScans[:lastIdx]
  992. return true
  993. }
  994. }
  995. return false
  996. }
  997. // GetVFoldersQuotaScans returns the active quota scans for virtual folders
  998. func (s *ActiveScans) GetVFoldersQuotaScans() []ActiveVirtualFolderQuotaScan {
  999. s.RLock()
  1000. defer s.RUnlock()
  1001. scans := make([]ActiveVirtualFolderQuotaScan, len(s.FolderScans))
  1002. copy(scans, s.FolderScans)
  1003. return scans
  1004. }
  1005. // AddVFolderQuotaScan adds a virtual folder to the ones with active quota scans.
  1006. // Returns false if the folder has a quota scan already running
  1007. func (s *ActiveScans) AddVFolderQuotaScan(folderName string) bool {
  1008. s.Lock()
  1009. defer s.Unlock()
  1010. for _, scan := range s.FolderScans {
  1011. if scan.Name == folderName {
  1012. return false
  1013. }
  1014. }
  1015. s.FolderScans = append(s.FolderScans, ActiveVirtualFolderQuotaScan{
  1016. Name: folderName,
  1017. StartTime: util.GetTimeAsMsSinceEpoch(time.Now()),
  1018. })
  1019. return true
  1020. }
  1021. // RemoveVFolderQuotaScan removes a folder from the ones with active quota scans.
  1022. // Returns false if the folder has no active quota scans
  1023. func (s *ActiveScans) RemoveVFolderQuotaScan(folderName string) bool {
  1024. s.Lock()
  1025. defer s.Unlock()
  1026. for idx, scan := range s.FolderScans {
  1027. if scan.Name == folderName {
  1028. lastIdx := len(s.FolderScans) - 1
  1029. s.FolderScans[idx] = s.FolderScans[lastIdx]
  1030. s.FolderScans = s.FolderScans[:lastIdx]
  1031. return true
  1032. }
  1033. }
  1034. return false
  1035. }