common.go 42 KB

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