common.go 42 KB

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