common.go 42 KB

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