common.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. // Package common defines code shared among file transfer packages and protocols
  2. package common
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "sync/atomic"
  17. "time"
  18. "github.com/pires/go-proxyproto"
  19. "github.com/drakkan/sftpgo/v2/command"
  20. "github.com/drakkan/sftpgo/v2/dataprovider"
  21. "github.com/drakkan/sftpgo/v2/httpclient"
  22. "github.com/drakkan/sftpgo/v2/logger"
  23. "github.com/drakkan/sftpgo/v2/metric"
  24. "github.com/drakkan/sftpgo/v2/plugin"
  25. "github.com/drakkan/sftpgo/v2/util"
  26. "github.com/drakkan/sftpgo/v2/vfs"
  27. )
  28. // constants
  29. const (
  30. logSender = "common"
  31. uploadLogSender = "Upload"
  32. downloadLogSender = "Download"
  33. renameLogSender = "Rename"
  34. rmdirLogSender = "Rmdir"
  35. mkdirLogSender = "Mkdir"
  36. symlinkLogSender = "Symlink"
  37. removeLogSender = "Remove"
  38. chownLogSender = "Chown"
  39. chmodLogSender = "Chmod"
  40. chtimesLogSender = "Chtimes"
  41. truncateLogSender = "Truncate"
  42. operationDownload = "download"
  43. operationUpload = "upload"
  44. operationDelete = "delete"
  45. // Pre-download action name
  46. OperationPreDownload = "pre-download"
  47. // Pre-upload action name
  48. OperationPreUpload = "pre-upload"
  49. operationPreDelete = "pre-delete"
  50. operationRename = "rename"
  51. operationMkdir = "mkdir"
  52. operationRmdir = "rmdir"
  53. // SSH command action name
  54. OperationSSHCmd = "ssh_cmd"
  55. chtimesFormat = "2006-01-02T15:04:05" // YYYY-MM-DDTHH:MM:SS
  56. idleTimeoutCheckInterval = 3 * time.Minute
  57. periodicTimeoutCheckInterval = 1 * time.Minute
  58. )
  59. // Stat flags
  60. const (
  61. StatAttrUIDGID = 1
  62. StatAttrPerms = 2
  63. StatAttrTimes = 4
  64. StatAttrSize = 8
  65. )
  66. // Transfer types
  67. const (
  68. TransferUpload = iota
  69. TransferDownload
  70. )
  71. // Supported protocols
  72. const (
  73. ProtocolSFTP = "SFTP"
  74. ProtocolSCP = "SCP"
  75. ProtocolSSH = "SSH"
  76. ProtocolFTP = "FTP"
  77. ProtocolWebDAV = "DAV"
  78. ProtocolHTTP = "HTTP"
  79. ProtocolHTTPShare = "HTTPShare"
  80. ProtocolDataRetention = "DataRetention"
  81. ProtocolOIDC = "OIDC"
  82. )
  83. // Upload modes
  84. const (
  85. UploadModeStandard = iota
  86. UploadModeAtomic
  87. UploadModeAtomicWithResume
  88. )
  89. func init() {
  90. Connections.clients = clientsMap{
  91. clients: make(map[string]int),
  92. }
  93. Connections.perUserConns = make(map[string]int)
  94. }
  95. // errors definitions
  96. var (
  97. ErrPermissionDenied = errors.New("permission denied")
  98. ErrNotExist = errors.New("no such file or directory")
  99. ErrOpUnsupported = errors.New("operation unsupported")
  100. ErrGenericFailure = errors.New("failure")
  101. ErrQuotaExceeded = errors.New("denying write due to space limit")
  102. ErrReadQuotaExceeded = errors.New("denying read due to quota limit")
  103. ErrConnectionDenied = errors.New("you are not allowed to connect")
  104. ErrNoBinding = errors.New("no binding configured")
  105. ErrCrtRevoked = errors.New("your certificate has been revoked")
  106. ErrNoCredentials = errors.New("no credential provided")
  107. ErrInternalFailure = errors.New("internal failure")
  108. ErrTransferAborted = errors.New("transfer aborted")
  109. errNoTransfer = errors.New("requested transfer not found")
  110. errTransferMismatch = errors.New("transfer mismatch")
  111. )
  112. var (
  113. // Config is the configuration for the supported protocols
  114. Config Configuration
  115. // Connections is the list of active connections
  116. Connections ActiveConnections
  117. transfersChecker TransfersChecker
  118. periodicTimeoutTicker *time.Ticker
  119. periodicTimeoutTickerDone chan bool
  120. supportedProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP, ProtocolWebDAV,
  121. ProtocolHTTP, ProtocolHTTPShare, ProtocolOIDC}
  122. disconnHookProtocols = []string{ProtocolSFTP, ProtocolSCP, ProtocolSSH, ProtocolFTP}
  123. // the map key is the protocol, for each protocol we can have multiple rate limiters
  124. rateLimiters map[string][]*rateLimiter
  125. )
  126. // Initialize sets the common configuration
  127. func Initialize(c Configuration, isShared int) error {
  128. Config = c
  129. Config.Actions.ExecuteOn = util.RemoveDuplicates(Config.Actions.ExecuteOn, true)
  130. Config.Actions.ExecuteSync = util.RemoveDuplicates(Config.Actions.ExecuteSync, true)
  131. Config.ProxyAllowed = util.RemoveDuplicates(Config.ProxyAllowed, true)
  132. Config.idleLoginTimeout = 2 * time.Minute
  133. Config.idleTimeoutAsDuration = time.Duration(Config.IdleTimeout) * time.Minute
  134. startPeriodicTimeoutTicker(periodicTimeoutCheckInterval)
  135. Config.defender = nil
  136. Config.whitelist = nil
  137. rateLimiters = make(map[string][]*rateLimiter)
  138. for _, rlCfg := range c.RateLimitersConfig {
  139. if rlCfg.isEnabled() {
  140. if err := rlCfg.validate(); err != nil {
  141. return fmt.Errorf("rate limiters initialization error: %w", err)
  142. }
  143. allowList, err := util.ParseAllowedIPAndRanges(rlCfg.AllowList)
  144. if err != nil {
  145. return fmt.Errorf("unable to parse rate limiter allow list %v: %v", rlCfg.AllowList, err)
  146. }
  147. rateLimiter := rlCfg.getLimiter()
  148. rateLimiter.allowList = allowList
  149. for _, protocol := range rlCfg.Protocols {
  150. rateLimiters[protocol] = append(rateLimiters[protocol], rateLimiter)
  151. }
  152. }
  153. }
  154. if c.DefenderConfig.Enabled {
  155. if !util.Contains(supportedDefenderDrivers, c.DefenderConfig.Driver) {
  156. return fmt.Errorf("unsupported defender driver %#v", c.DefenderConfig.Driver)
  157. }
  158. var defender Defender
  159. var err error
  160. switch c.DefenderConfig.Driver {
  161. case DefenderDriverProvider:
  162. defender, err = newDBDefender(&c.DefenderConfig)
  163. default:
  164. defender, err = newInMemoryDefender(&c.DefenderConfig)
  165. }
  166. if err != nil {
  167. return fmt.Errorf("defender initialization error: %v", err)
  168. }
  169. logger.Info(logSender, "", "defender initialized with config %+v", c.DefenderConfig)
  170. Config.defender = defender
  171. }
  172. if c.WhiteListFile != "" {
  173. whitelist := &whitelist{
  174. fileName: c.WhiteListFile,
  175. }
  176. if err := whitelist.reload(); err != nil {
  177. return fmt.Errorf("whitelist initialization error: %w", err)
  178. }
  179. logger.Info(logSender, "", "whitelist initialized from file: %#v", c.WhiteListFile)
  180. Config.whitelist = whitelist
  181. }
  182. vfs.SetTempPath(c.TempPath)
  183. dataprovider.SetTempPath(c.TempPath)
  184. transfersChecker = getTransfersChecker(isShared)
  185. return nil
  186. }
  187. // LimitRate blocks until all the configured rate limiters
  188. // allow one event to happen.
  189. // It returns an error if the time to wait exceeds the max
  190. // allowed delay
  191. func LimitRate(protocol, ip string) (time.Duration, error) {
  192. for _, limiter := range rateLimiters[protocol] {
  193. if delay, err := limiter.Wait(ip); err != nil {
  194. logger.Debug(logSender, "", "protocol %v ip %v: %v", protocol, ip, err)
  195. return delay, err
  196. }
  197. }
  198. return 0, nil
  199. }
  200. // Reload reloads the whitelist, the IP filter plugin and the defender's block and safe lists
  201. func Reload() error {
  202. plugin.Handler.ReloadFilter()
  203. var errWithelist error
  204. if Config.whitelist != nil {
  205. errWithelist = Config.whitelist.reload()
  206. }
  207. if Config.defender == nil {
  208. return errWithelist
  209. }
  210. if err := Config.defender.Reload(); err != nil {
  211. return err
  212. }
  213. return errWithelist
  214. }
  215. // IsBanned returns true if the specified IP address is banned
  216. func IsBanned(ip string) bool {
  217. if plugin.Handler.IsIPBanned(ip) {
  218. return true
  219. }
  220. if Config.defender == nil {
  221. return false
  222. }
  223. return Config.defender.IsBanned(ip)
  224. }
  225. // GetDefenderBanTime returns the ban time for the given IP
  226. // or nil if the IP is not banned or the defender is disabled
  227. func GetDefenderBanTime(ip string) (*time.Time, error) {
  228. if Config.defender == nil {
  229. return nil, nil
  230. }
  231. return Config.defender.GetBanTime(ip)
  232. }
  233. // GetDefenderHosts returns hosts that are banned or for which some violations have been detected
  234. func GetDefenderHosts() ([]dataprovider.DefenderEntry, error) {
  235. if Config.defender == nil {
  236. return nil, nil
  237. }
  238. return Config.defender.GetHosts()
  239. }
  240. // GetDefenderHost returns a defender host by ip, if any
  241. func GetDefenderHost(ip string) (dataprovider.DefenderEntry, error) {
  242. if Config.defender == nil {
  243. return dataprovider.DefenderEntry{}, errors.New("defender is disabled")
  244. }
  245. return Config.defender.GetHost(ip)
  246. }
  247. // DeleteDefenderHost removes the specified IP address from the defender lists
  248. func DeleteDefenderHost(ip string) bool {
  249. if Config.defender == nil {
  250. return false
  251. }
  252. return Config.defender.DeleteHost(ip)
  253. }
  254. // GetDefenderScore returns the score for the given IP
  255. func GetDefenderScore(ip string) (int, error) {
  256. if Config.defender == nil {
  257. return 0, nil
  258. }
  259. return Config.defender.GetScore(ip)
  260. }
  261. // AddDefenderEvent adds the specified defender event for the given IP
  262. func AddDefenderEvent(ip string, event HostEvent) {
  263. if Config.defender == nil {
  264. return
  265. }
  266. Config.defender.AddEvent(ip, event)
  267. }
  268. // the ticker cannot be started/stopped from multiple goroutines
  269. func startPeriodicTimeoutTicker(duration time.Duration) {
  270. stopPeriodicTimeoutTicker()
  271. periodicTimeoutTicker = time.NewTicker(duration)
  272. periodicTimeoutTickerDone = make(chan bool)
  273. go func() {
  274. counter := int64(0)
  275. ratio := idleTimeoutCheckInterval / periodicTimeoutCheckInterval
  276. for {
  277. select {
  278. case <-periodicTimeoutTickerDone:
  279. return
  280. case <-periodicTimeoutTicker.C:
  281. counter++
  282. if Config.IdleTimeout > 0 && counter >= int64(ratio) {
  283. counter = 0
  284. Connections.checkIdles()
  285. }
  286. go Connections.checkTransfers()
  287. }
  288. }
  289. }()
  290. }
  291. func stopPeriodicTimeoutTicker() {
  292. if periodicTimeoutTicker != nil {
  293. periodicTimeoutTicker.Stop()
  294. periodicTimeoutTickerDone <- true
  295. periodicTimeoutTicker = nil
  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. 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. }