Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

server.go 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016-2017 Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "fmt"
  8. "net"
  9. "net/http"
  10. _ "net/http/pprof"
  11. "os"
  12. "os/signal"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "syscall"
  17. "time"
  18. "github.com/ergochat/irc-go/ircfmt"
  19. "github.com/okzk/sdnotify"
  20. "github.com/ergochat/ergo/irc/caps"
  21. "github.com/ergochat/ergo/irc/connection_limits"
  22. "github.com/ergochat/ergo/irc/flatip"
  23. "github.com/ergochat/ergo/irc/flock"
  24. "github.com/ergochat/ergo/irc/history"
  25. "github.com/ergochat/ergo/irc/logger"
  26. "github.com/ergochat/ergo/irc/modes"
  27. "github.com/ergochat/ergo/irc/mysql"
  28. "github.com/ergochat/ergo/irc/sno"
  29. "github.com/ergochat/ergo/irc/utils"
  30. "github.com/tidwall/buntdb"
  31. )
  32. const (
  33. alwaysOnMaintenanceInterval = 30 * time.Minute
  34. )
  35. var (
  36. // common error line to sub values into
  37. errorMsg = "ERROR :%s\r\n"
  38. // three final parameters of 004 RPL_MYINFO, enumerating our supported modes
  39. rplMyInfo1, rplMyInfo2, rplMyInfo3 = modes.RplMyInfo()
  40. // CHANMODES isupport token
  41. chanmodesToken = modes.ChanmodesToken()
  42. // whitelist of caps to serve on the STS-only listener. In particular,
  43. // never advertise SASL, to discourage people from sending their passwords:
  44. stsOnlyCaps = caps.NewSet(caps.STS, caps.MessageTags, caps.ServerTime, caps.Batch, caps.LabeledResponse, caps.EchoMessage, caps.Nope)
  45. // we only have standard channels for now. TODO: any updates to this
  46. // will also need to be reflected in CasefoldChannel
  47. chanTypes = "#"
  48. throttleMessage = "You have attempted to connect too many times within a short duration. Wait a while, and you will be able to connect."
  49. )
  50. // Server is the main Oragono server.
  51. type Server struct {
  52. accepts AcceptManager
  53. accounts AccountManager
  54. channels ChannelManager
  55. channelRegistry ChannelRegistry
  56. clients ClientManager
  57. config utils.ConfigStore[Config]
  58. configFilename string
  59. connectionLimiter connection_limits.Limiter
  60. ctime time.Time
  61. dlines *DLineManager
  62. helpIndexManager HelpIndexManager
  63. klines *KLineManager
  64. listeners map[string]IRCListener
  65. logger *logger.Manager
  66. monitorManager MonitorManager
  67. name string
  68. nameCasefolded string
  69. rehashMutex sync.Mutex // tier 4
  70. rehashSignal chan os.Signal
  71. pprofServer *http.Server
  72. exitSignals chan os.Signal
  73. snomasks SnoManager
  74. store *buntdb.DB
  75. historyDB mysql.MySQL
  76. torLimiter connection_limits.TorLimiter
  77. whoWas WhoWasList
  78. stats Stats
  79. semaphores ServerSemaphores
  80. flock flock.Flocker
  81. defcon uint32
  82. }
  83. // NewServer returns a new Oragono server.
  84. func NewServer(config *Config, logger *logger.Manager) (*Server, error) {
  85. // initialize data structures
  86. server := &Server{
  87. ctime: time.Now().UTC(),
  88. listeners: make(map[string]IRCListener),
  89. logger: logger,
  90. rehashSignal: make(chan os.Signal, 1),
  91. exitSignals: make(chan os.Signal, len(utils.ServerExitSignals)),
  92. defcon: 5,
  93. }
  94. server.accepts.Initialize()
  95. server.clients.Initialize()
  96. server.semaphores.Initialize()
  97. server.whoWas.Initialize(config.Limits.WhowasEntries)
  98. server.monitorManager.Initialize()
  99. server.snomasks.Initialize()
  100. if err := server.applyConfig(config); err != nil {
  101. return nil, err
  102. }
  103. // Attempt to clean up when receiving these signals.
  104. signal.Notify(server.exitSignals, utils.ServerExitSignals...)
  105. signal.Notify(server.rehashSignal, syscall.SIGHUP)
  106. time.AfterFunc(alwaysOnMaintenanceInterval, server.periodicAlwaysOnMaintenance)
  107. return server, nil
  108. }
  109. // Shutdown shuts down the server.
  110. func (server *Server) Shutdown() {
  111. sdnotify.Stopping()
  112. server.logger.Info("server", "Stopping server")
  113. //TODO(dan): Make sure we disallow new nicks
  114. for _, client := range server.clients.AllClients() {
  115. client.Notice("Server is shutting down")
  116. }
  117. // flush data associated with always-on clients:
  118. server.performAlwaysOnMaintenance(false, true)
  119. if err := server.store.Close(); err != nil {
  120. server.logger.Error("shutdown", fmt.Sprintln("Could not close datastore:", err))
  121. }
  122. server.historyDB.Close()
  123. server.logger.Info("server", fmt.Sprintf("%s exiting", Ver))
  124. }
  125. // Run starts the server.
  126. func (server *Server) Run() {
  127. defer server.Shutdown()
  128. for {
  129. select {
  130. case <-server.exitSignals:
  131. return
  132. case <-server.rehashSignal:
  133. server.logger.Info("server", "Rehashing due to SIGHUP")
  134. go server.rehash()
  135. }
  136. }
  137. }
  138. func (server *Server) checkBans(config *Config, ipaddr net.IP, checkScripts bool) (banned bool, requireSASL bool, message string) {
  139. // #671: do not enforce bans against loopback, as a failsafe
  140. // note that this function is not used for Tor connections (checkTorLimits is used instead)
  141. if ipaddr.IsLoopback() {
  142. return
  143. }
  144. if server.Defcon() == 1 {
  145. if !utils.IPInNets(ipaddr, server.Config().Server.secureNets) {
  146. return true, false, "New connections to this server are temporarily restricted"
  147. }
  148. }
  149. flat := flatip.FromNetIP(ipaddr)
  150. // check DLINEs
  151. isBanned, info := server.dlines.CheckIP(flat)
  152. if isBanned {
  153. if info.RequireSASL {
  154. server.logger.Info("connect-ip", "Requiring SASL from client due to d-line", ipaddr.String())
  155. return false, true, info.BanMessage("You must authenticate with SASL to connect from this IP (%s)")
  156. } else {
  157. server.logger.Info("connect-ip", "Client rejected by d-line", ipaddr.String())
  158. return true, false, info.BanMessage("You are banned from this server (%s)")
  159. }
  160. }
  161. // check connection limits
  162. err := server.connectionLimiter.AddClient(flat)
  163. if err == connection_limits.ErrLimitExceeded {
  164. // too many connections from one client, tell the client and close the connection
  165. server.logger.Info("connect-ip", "Client rejected for connection limit", ipaddr.String())
  166. return true, false, "Too many clients from your network"
  167. } else if err == connection_limits.ErrThrottleExceeded {
  168. server.logger.Info("connect-ip", "Client exceeded connection throttle", ipaddr.String())
  169. return true, false, throttleMessage
  170. } else if err != nil {
  171. server.logger.Warning("internal", "unexpected ban result", err.Error())
  172. }
  173. if checkScripts && config.Server.IPCheckScript.Enabled && !config.Server.IPCheckScript.ExemptSASL {
  174. output, err := CheckIPBan(server.semaphores.IPCheckScript, config.Server.IPCheckScript, ipaddr)
  175. if err != nil {
  176. server.logger.Error("internal", "couldn't check IP ban script", ipaddr.String(), err.Error())
  177. return false, false, ""
  178. }
  179. // TODO: currently no way to cache IPAccepted
  180. if (output.Result == IPBanned || output.Result == IPRequireSASL) && output.CacheSeconds != 0 {
  181. network, err := flatip.ParseToNormalizedNet(output.CacheNet)
  182. if err != nil {
  183. server.logger.Error("internal", "invalid dline net from IP ban script", ipaddr.String(), output.CacheNet)
  184. } else {
  185. dlineDuration := time.Duration(output.CacheSeconds) * time.Second
  186. err := server.dlines.AddNetwork(network, dlineDuration, output.Result == IPRequireSASL, output.BanMessage, "", "")
  187. if err != nil {
  188. server.logger.Error("internal", "couldn't set dline from IP ban script", ipaddr.String(), err.Error())
  189. }
  190. }
  191. }
  192. if output.Result == IPBanned {
  193. // XXX roll back IP connection/throttling addition for the IP
  194. server.connectionLimiter.RemoveClient(flat)
  195. server.logger.Info("connect-ip", "Rejected client due to ip-check-script", ipaddr.String())
  196. return true, false, output.BanMessage
  197. } else if output.Result == IPRequireSASL {
  198. server.logger.Info("connect-ip", "Requiring SASL from client due to ip-check-script", ipaddr.String())
  199. return false, true, output.BanMessage
  200. }
  201. }
  202. return false, false, ""
  203. }
  204. func (server *Server) checkTorLimits() (banned bool, message string) {
  205. switch server.torLimiter.AddClient() {
  206. case connection_limits.ErrLimitExceeded:
  207. return true, "Too many clients from the Tor network"
  208. case connection_limits.ErrThrottleExceeded:
  209. return true, "Exceeded connection throttle for the Tor network"
  210. default:
  211. return false, ""
  212. }
  213. }
  214. func (server *Server) periodicAlwaysOnMaintenance() {
  215. defer func() {
  216. // reschedule whether or not there was a panic
  217. time.AfterFunc(alwaysOnMaintenanceInterval, server.periodicAlwaysOnMaintenance)
  218. }()
  219. defer server.HandlePanic()
  220. server.logger.Info("accounts", "Performing periodic always-on client checks")
  221. server.performAlwaysOnMaintenance(true, true)
  222. }
  223. func (server *Server) performAlwaysOnMaintenance(checkExpiration, flushTimestamps bool) {
  224. config := server.Config()
  225. for _, client := range server.clients.AllClients() {
  226. if checkExpiration && client.IsExpiredAlwaysOn(config) {
  227. // TODO save the channels list, use it for autojoin if/when they return?
  228. server.logger.Info("accounts", "Expiring always-on client", client.AccountName())
  229. client.destroy(nil)
  230. continue
  231. }
  232. if flushTimestamps && client.shouldFlushTimestamps() {
  233. account := client.Account()
  234. server.accounts.saveLastSeen(account, client.copyLastSeen())
  235. server.accounts.saveReadMarkers(account, client.copyReadMarkers())
  236. }
  237. }
  238. }
  239. // handles server.ip-check-script.exempt-sasl:
  240. // run the ip check script at the end of the handshake, only for anonymous connections
  241. func (server *Server) checkBanScriptExemptSASL(config *Config, session *Session) (outcome AuthOutcome) {
  242. // TODO add caching for this; see related code in (*server).checkBans;
  243. // we should probably just put an LRU around this instead of using the DLINE system
  244. ipaddr := session.IP()
  245. output, err := CheckIPBan(server.semaphores.IPCheckScript, config.Server.IPCheckScript, ipaddr)
  246. if err != nil {
  247. server.logger.Error("internal", "couldn't check IP ban script", ipaddr.String(), err.Error())
  248. return authSuccess
  249. }
  250. if output.Result == IPBanned || output.Result == IPRequireSASL {
  251. server.logger.Info("connect-ip", "Rejecting unauthenticated client due to ip-check-script", ipaddr.String())
  252. if output.BanMessage != "" {
  253. session.client.requireSASLMessage = output.BanMessage
  254. }
  255. return authFailSaslRequired
  256. }
  257. return authSuccess
  258. }
  259. func (server *Server) tryRegister(c *Client, session *Session) (exiting bool) {
  260. // XXX PROXY or WEBIRC MUST be sent as the first line of the session;
  261. // if we are here at all that means we have the final value of the IP
  262. if session.rawHostname == "" {
  263. session.client.lookupHostname(session, false)
  264. }
  265. // try to complete registration normally
  266. // XXX(#1057) username can be filled in by an ident query without the client
  267. // having sent USER: check for both username and realname to ensure they did
  268. if c.preregNick == "" || c.username == "" || c.realname == "" || session.capState == caps.NegotiatingState {
  269. return
  270. }
  271. if c.isSTSOnly {
  272. server.playSTSBurst(session)
  273. return true
  274. }
  275. // client MUST send PASS if necessary, or authenticate with SASL if necessary,
  276. // before completing the other registration commands
  277. config := server.Config()
  278. authOutcome := c.isAuthorized(server, config, session, c.requireSASL)
  279. if authOutcome == authSuccess && c.account == "" &&
  280. config.Server.IPCheckScript.Enabled && config.Server.IPCheckScript.ExemptSASL {
  281. authOutcome = server.checkBanScriptExemptSASL(config, session)
  282. }
  283. var quitMessage string
  284. switch authOutcome {
  285. case authFailPass:
  286. quitMessage = c.t("Password incorrect")
  287. c.Send(nil, server.name, ERR_PASSWDMISMATCH, "*", quitMessage)
  288. case authFailSaslRequired, authFailTorSaslRequired:
  289. quitMessage = c.requireSASLMessage
  290. if quitMessage == "" {
  291. quitMessage = c.t("You must log in with SASL to join this server")
  292. }
  293. c.Send(nil, c.server.name, "FAIL", "*", "ACCOUNT_REQUIRED", quitMessage)
  294. }
  295. if authOutcome != authSuccess {
  296. c.Quit(quitMessage, nil)
  297. return true
  298. }
  299. c.requireSASLMessage = ""
  300. rb := NewResponseBuffer(session)
  301. nickError := performNickChange(server, c, c, session, c.preregNick, rb)
  302. rb.Send(true)
  303. if nickError == errInsecureReattach {
  304. c.Quit(c.t("You can't mix secure and insecure connections to this account"), nil)
  305. return true
  306. } else if nickError != nil {
  307. c.preregNick = ""
  308. return false
  309. }
  310. if session.client != c {
  311. // reattached, bail out.
  312. // we'll play the reg burst later, on the new goroutine associated with
  313. // (thisSession, otherClient). This is to avoid having to transfer state
  314. // like nickname, hostname, etc. to show the correct values in the reg burst.
  315. return false
  316. }
  317. // Apply default user modes (without updating the invisible counter)
  318. // The number of invisible users will be updated by server.stats.Register
  319. // if we're using default user mode +i.
  320. for _, defaultMode := range config.Accounts.defaultUserModes {
  321. c.SetMode(defaultMode, true)
  322. }
  323. // count new user in statistics (before checking KLINEs, see #1303)
  324. server.stats.Register(c.HasMode(modes.Invisible))
  325. // check KLINEs (#671: ignore KLINEs for loopback connections)
  326. if !session.IP().IsLoopback() || session.isTor {
  327. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  328. if isBanned {
  329. c.setKlined()
  330. c.Quit(info.BanMessage(c.t("You are banned from this server (%s)")), nil)
  331. server.logger.Info("connect", "Client rejected by k-line", c.NickMaskString())
  332. return true
  333. }
  334. }
  335. server.playRegistrationBurst(session)
  336. return false
  337. }
  338. func (server *Server) playSTSBurst(session *Session) {
  339. nick := utils.SafeErrorParam(session.client.preregNick)
  340. session.Send(nil, server.name, RPL_WELCOME, nick, fmt.Sprintf("Welcome to the Internet Relay Network %s", nick))
  341. session.Send(nil, server.name, RPL_YOURHOST, nick, fmt.Sprintf("Your host is %[1]s, running version %[2]s", server.name, "ergo"))
  342. session.Send(nil, server.name, RPL_CREATED, nick, fmt.Sprintf("This server was created %s", time.Time{}.Format(time.RFC1123)))
  343. session.Send(nil, server.name, RPL_MYINFO, nick, server.name, "ergo", "o", "o", "o")
  344. session.Send(nil, server.name, RPL_ISUPPORT, nick, "CASEMAPPING=ascii", "are supported by this server")
  345. session.Send(nil, server.name, ERR_NOMOTD, nick, "MOTD is unavailable")
  346. for _, line := range server.Config().Server.STS.bannerLines {
  347. session.Send(nil, server.name, "NOTICE", nick, line)
  348. }
  349. }
  350. func (server *Server) playRegistrationBurst(session *Session) {
  351. c := session.client
  352. // continue registration
  353. d := c.Details()
  354. server.logger.Info("connect", fmt.Sprintf("Client connected [%s] [u:%s] [r:%s]", d.nick, d.username, d.realname))
  355. server.snomasks.Send(sno.LocalConnects, fmt.Sprintf("Client connected [%s] [u:%s] [h:%s] [ip:%s] [r:%s]", d.nick, d.username, session.rawHostname, session.IP().String(), d.realname))
  356. if d.account != "" {
  357. server.sendLoginSnomask(d.nickMask, d.accountName)
  358. }
  359. // send welcome text
  360. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  361. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  362. config := server.Config()
  363. session.Send(nil, server.name, RPL_WELCOME, d.nick, fmt.Sprintf(c.t("Welcome to the %s IRC Network %s"), config.Network.Name, d.nick))
  364. session.Send(nil, server.name, RPL_YOURHOST, d.nick, fmt.Sprintf(c.t("Your host is %[1]s, running version %[2]s"), server.name, Ver))
  365. session.Send(nil, server.name, RPL_CREATED, d.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  366. session.Send(nil, server.name, RPL_MYINFO, d.nick, server.name, Ver, rplMyInfo1, rplMyInfo2, rplMyInfo3)
  367. rb := NewResponseBuffer(session)
  368. server.RplISupport(c, rb)
  369. server.Lusers(c, rb)
  370. server.MOTD(c, rb)
  371. rb.Send(true)
  372. modestring := c.ModeString()
  373. if modestring != "+" {
  374. session.Send(nil, server.name, RPL_UMODEIS, d.nick, modestring)
  375. }
  376. c.attemptAutoOper(session)
  377. if server.logger.IsLoggingRawIO() {
  378. session.Send(nil, c.server.name, "NOTICE", d.nick, c.t("This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect."))
  379. }
  380. }
  381. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  382. func (server *Server) RplISupport(client *Client, rb *ResponseBuffer) {
  383. translatedISupport := client.t("are supported by this server")
  384. nick := client.Nick()
  385. config := server.Config()
  386. for _, cachedTokenLine := range config.Server.isupport.CachedReply {
  387. length := len(cachedTokenLine) + 2
  388. tokenline := make([]string, length)
  389. tokenline[0] = nick
  390. copy(tokenline[1:], cachedTokenLine)
  391. tokenline[length-1] = translatedISupport
  392. rb.Add(nil, server.name, RPL_ISUPPORT, tokenline...)
  393. }
  394. }
  395. func (server *Server) Lusers(client *Client, rb *ResponseBuffer) {
  396. nick := client.Nick()
  397. config := server.Config()
  398. var stats StatsValues
  399. var numChannels int
  400. if !config.Server.SuppressLusers || client.HasRoleCapabs("ban") {
  401. stats = server.stats.GetValues()
  402. numChannels = server.channels.Len()
  403. }
  404. rb.Add(nil, server.name, RPL_LUSERCLIENT, nick, fmt.Sprintf(client.t("There are %[1]d users and %[2]d invisible on %[3]d server(s)"), stats.Total-stats.Invisible, stats.Invisible, 1))
  405. rb.Add(nil, server.name, RPL_LUSEROP, nick, strconv.Itoa(stats.Operators), client.t("IRC Operators online"))
  406. rb.Add(nil, server.name, RPL_LUSERUNKNOWN, nick, strconv.Itoa(stats.Unknown), client.t("unregistered connections"))
  407. rb.Add(nil, server.name, RPL_LUSERCHANNELS, nick, strconv.Itoa(numChannels), client.t("channels formed"))
  408. rb.Add(nil, server.name, RPL_LUSERME, nick, fmt.Sprintf(client.t("I have %[1]d clients and %[2]d servers"), stats.Total, 0))
  409. total := strconv.Itoa(stats.Total)
  410. max := strconv.Itoa(stats.Max)
  411. rb.Add(nil, server.name, RPL_LOCALUSERS, nick, total, max, fmt.Sprintf(client.t("Current local users %[1]s, max %[2]s"), total, max))
  412. rb.Add(nil, server.name, RPL_GLOBALUSERS, nick, total, max, fmt.Sprintf(client.t("Current global users %[1]s, max %[2]s"), total, max))
  413. }
  414. // MOTD serves the Message of the Day.
  415. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  416. motdLines := server.Config().Server.motdLines
  417. if len(motdLines) < 1 {
  418. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  419. return
  420. }
  421. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  422. for _, line := range motdLines {
  423. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  424. }
  425. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  426. }
  427. func (client *Client) whoisChannelsNames(target *Client, multiPrefix bool, hasPrivs bool) []string {
  428. var chstrs []string
  429. targetInvis := target.HasMode(modes.Invisible)
  430. for _, channel := range target.Channels() {
  431. if !hasPrivs && (targetInvis || channel.flags.HasMode(modes.Secret)) && !channel.hasClient(client) {
  432. // client can't see *this* channel membership
  433. continue
  434. }
  435. chstrs = append(chstrs, channel.ClientPrefixes(target, multiPrefix)+channel.name)
  436. }
  437. return chstrs
  438. }
  439. func (client *Client) getWhoisOf(target *Client, hasPrivs bool, rb *ResponseBuffer) {
  440. oper := client.Oper()
  441. cnick := client.Nick()
  442. targetInfo := target.Details()
  443. rb.Add(nil, client.server.name, RPL_WHOISUSER, cnick, targetInfo.nick, targetInfo.username, targetInfo.hostname, "*", targetInfo.realname)
  444. tnick := targetInfo.nick
  445. whoischannels := client.whoisChannelsNames(target, rb.session.capabilities.Has(caps.MultiPrefix), oper.HasRoleCapab("sajoin"))
  446. if whoischannels != nil {
  447. for _, line := range utils.BuildTokenLines(maxLastArgLength, whoischannels, " ") {
  448. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, cnick, tnick, line)
  449. }
  450. }
  451. if target.HasMode(modes.Operator) && operStatusVisible(client, target, oper != nil) {
  452. tOper := target.Oper()
  453. if tOper != nil {
  454. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, cnick, tnick, tOper.WhoisLine)
  455. }
  456. }
  457. if client == target || oper.HasRoleCapab("ban") {
  458. ip, hostname := target.getWhoisActually()
  459. rb.Add(nil, client.server.name, RPL_WHOISACTUALLY, cnick, tnick, fmt.Sprintf("%s@%s", targetInfo.username, hostname), utils.IPStringToHostname(ip.String()), client.t("Actual user@host, Actual IP"))
  460. }
  461. if client == target || oper.HasRoleCapab("samode") {
  462. rb.Add(nil, client.server.name, RPL_WHOISMODES, cnick, tnick, fmt.Sprintf(client.t("is using modes +%s"), target.modes.String()))
  463. }
  464. if target.HasMode(modes.TLS) {
  465. rb.Add(nil, client.server.name, RPL_WHOISSECURE, cnick, tnick, client.t("is using a secure connection"))
  466. }
  467. if targetInfo.accountName != "*" {
  468. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, cnick, tnick, targetInfo.accountName, client.t("is logged in as"))
  469. }
  470. if target.HasMode(modes.Bot) {
  471. rb.Add(nil, client.server.name, RPL_WHOISBOT, cnick, tnick, fmt.Sprintf(ircfmt.Unescape(client.t("is a $bBot$b on %s")), client.server.Config().Network.Name))
  472. }
  473. if client == target || oper.HasRoleCapab("ban") {
  474. for _, session := range target.Sessions() {
  475. if session.certfp != "" {
  476. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, cnick, tnick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), session.certfp))
  477. }
  478. }
  479. }
  480. rb.Add(nil, client.server.name, RPL_WHOISIDLE, cnick, tnick, strconv.FormatUint(target.IdleSeconds(), 10), strconv.FormatInt(target.SignonTime(), 10), client.t("seconds idle, signon time"))
  481. if away, awayMessage := target.Away(); away {
  482. rb.Add(nil, client.server.name, RPL_AWAY, cnick, tnick, awayMessage)
  483. }
  484. }
  485. // rehash reloads the config and applies the changes from the config file.
  486. func (server *Server) rehash() error {
  487. // #1570; this needs its own panic handling because it can be invoked via SIGHUP
  488. defer server.HandlePanic()
  489. server.logger.Info("server", "Attempting rehash")
  490. // only let one REHASH go on at a time
  491. server.rehashMutex.Lock()
  492. defer server.rehashMutex.Unlock()
  493. sdnotify.Reloading()
  494. defer sdnotify.Ready()
  495. config, err := LoadConfig(server.configFilename)
  496. if err != nil {
  497. server.logger.Error("server", "failed to load config file", err.Error())
  498. return err
  499. }
  500. err = server.applyConfig(config)
  501. if err != nil {
  502. server.logger.Error("server", "Failed to rehash", err.Error())
  503. return err
  504. }
  505. server.logger.Info("server", "Rehash completed successfully")
  506. return nil
  507. }
  508. func (server *Server) applyConfig(config *Config) (err error) {
  509. oldConfig := server.Config()
  510. initial := oldConfig == nil
  511. if initial {
  512. server.configFilename = config.Filename
  513. server.name = config.Server.Name
  514. server.nameCasefolded = config.Server.nameCasefolded
  515. globalCasemappingSetting = config.Server.Casemapping
  516. globalUtf8EnforcementSetting = config.Server.EnforceUtf8
  517. MaxLineLen = config.Server.MaxLineLen
  518. } else {
  519. // enforce configs that can't be changed after launch:
  520. if server.name != config.Server.Name {
  521. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  522. } else if oldConfig.Datastore.Path != config.Datastore.Path {
  523. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  524. } else if globalCasemappingSetting != config.Server.Casemapping {
  525. return fmt.Errorf("Casemapping cannot be changed after launching the server, rehash aborted")
  526. } else if globalUtf8EnforcementSetting != config.Server.EnforceUtf8 {
  527. return fmt.Errorf("UTF-8 enforcement cannot be changed after launching the server, rehash aborted")
  528. } else if oldConfig.Accounts.Multiclient.AlwaysOn != config.Accounts.Multiclient.AlwaysOn {
  529. return fmt.Errorf("Default always-on setting cannot be changed after launching the server, rehash aborted")
  530. } else if oldConfig.Server.Relaymsg.Enabled != config.Server.Relaymsg.Enabled {
  531. return fmt.Errorf("Cannot enable or disable relaying after launching the server, rehash aborted")
  532. } else if oldConfig.Server.Relaymsg.Separators != config.Server.Relaymsg.Separators {
  533. return fmt.Errorf("Cannot change relaying separators after launching the server, rehash aborted")
  534. } else if oldConfig.Server.IPCheckScript.MaxConcurrency != config.Server.IPCheckScript.MaxConcurrency ||
  535. oldConfig.Accounts.AuthScript.MaxConcurrency != config.Accounts.AuthScript.MaxConcurrency {
  536. return fmt.Errorf("Cannot change max-concurrency for scripts after launching the server, rehash aborted")
  537. } else if oldConfig.Server.OverrideServicesHostname != config.Server.OverrideServicesHostname {
  538. return fmt.Errorf("Cannot change override-services-hostname after launching the server, rehash aborted")
  539. } else if !oldConfig.Datastore.MySQL.Enabled && config.Datastore.MySQL.Enabled {
  540. return fmt.Errorf("Cannot enable MySQL after launching the server, rehash aborted")
  541. } else if oldConfig.Server.MaxLineLen != config.Server.MaxLineLen {
  542. return fmt.Errorf("Cannot change max-line-len after launching the server, rehash aborted")
  543. }
  544. }
  545. server.logger.Info("server", "Using config file", server.configFilename)
  546. if initial {
  547. if config.LockFile != "" {
  548. server.flock, err = flock.TryAcquireFlock(config.LockFile)
  549. if err != nil {
  550. return fmt.Errorf("failed to acquire flock on %s: %w",
  551. config.LockFile, err)
  552. }
  553. }
  554. // the lock is never released until quit; we need to save a pointer
  555. // to the (*flock.Flock) object so it doesn't get GC'ed, which would
  556. // close the file and surrender the lock
  557. }
  558. // first, reload config sections for functionality implemented in subpackages:
  559. wasLoggingRawIO := !initial && server.logger.IsLoggingRawIO()
  560. err = server.logger.ApplyConfig(config.Logging)
  561. if err != nil {
  562. return err
  563. }
  564. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  565. // notify existing clients if raw i/o logging was enabled by a rehash
  566. sendRawOutputNotice := !wasLoggingRawIO && nowLoggingRawIO
  567. server.connectionLimiter.ApplyConfig(&config.Server.IPLimits)
  568. tlConf := &config.Server.TorListeners
  569. server.torLimiter.Configure(tlConf.MaxConnections, tlConf.ThrottleDuration, tlConf.MaxConnectionsPerDuration)
  570. // Translations
  571. server.logger.Debug("server", "Regenerating HELP indexes for new languages")
  572. server.helpIndexManager.GenerateIndices(config.languageManager)
  573. if initial {
  574. maxIPConc := int(config.Server.IPCheckScript.MaxConcurrency)
  575. if maxIPConc != 0 {
  576. server.semaphores.IPCheckScript = utils.NewSemaphore(maxIPConc)
  577. }
  578. maxAuthConc := int(config.Accounts.AuthScript.MaxConcurrency)
  579. if maxAuthConc != 0 {
  580. server.semaphores.AuthScript = utils.NewSemaphore(maxAuthConc)
  581. }
  582. if err := overrideServicePrefixes(config.Server.OverrideServicesHostname); err != nil {
  583. return err
  584. }
  585. }
  586. if oldConfig != nil {
  587. // if certain features were enabled by rehash, we need to load the corresponding data
  588. // from the store
  589. if !oldConfig.Accounts.NickReservation.Enabled {
  590. server.accounts.buildNickToAccountIndex(config)
  591. }
  592. if !oldConfig.Channels.Registration.Enabled {
  593. server.channels.loadRegisteredChannels(config)
  594. }
  595. // resize history buffers as needed
  596. if config.historyChangedFrom(oldConfig) {
  597. for _, channel := range server.channels.Channels() {
  598. channel.resizeHistory(config)
  599. }
  600. for _, client := range server.clients.AllClients() {
  601. client.resizeHistory(config)
  602. }
  603. }
  604. if oldConfig.Accounts.Registration.Throttling != config.Accounts.Registration.Throttling {
  605. server.accounts.resetRegisterThrottle(config)
  606. }
  607. }
  608. server.logger.Info("server", "Using datastore", config.Datastore.Path)
  609. if initial {
  610. if err := server.loadDatastore(config); err != nil {
  611. return err
  612. }
  613. } else {
  614. if config.Datastore.MySQL.Enabled && config.Datastore.MySQL != oldConfig.Datastore.MySQL {
  615. server.historyDB.SetConfig(config.Datastore.MySQL)
  616. }
  617. }
  618. // now that the datastore is initialized, we can load the cloak secret from it
  619. // XXX this modifies config after the initial load, which is naughty,
  620. // but there's no data race because we haven't done SetConfig yet
  621. config.Server.Cloaks.SetSecret(LoadCloakSecret(server.store))
  622. // activate the new config
  623. server.config.Set(config)
  624. // load [dk]-lines, registered users and channels, etc.
  625. if initial {
  626. if err := server.loadFromDatastore(config); err != nil {
  627. return err
  628. }
  629. }
  630. // burst new and removed caps
  631. addedCaps, removedCaps := config.Diff(oldConfig)
  632. var capBurstSessions []*Session
  633. added := make(map[caps.Version][]string)
  634. var removed []string
  635. if !addedCaps.Empty() || !removedCaps.Empty() {
  636. capBurstSessions = server.clients.AllWithCapsNotify()
  637. added[caps.Cap301] = addedCaps.Strings(caps.Cap301, config.Server.capValues, 0)
  638. added[caps.Cap302] = addedCaps.Strings(caps.Cap302, config.Server.capValues, 0)
  639. // removed never has values, so we leave it as Cap301
  640. removed = removedCaps.Strings(caps.Cap301, config.Server.capValues, 0)
  641. }
  642. for _, sSession := range capBurstSessions {
  643. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  644. if !removedCaps.Empty() {
  645. for _, capStr := range removed {
  646. sSession.Send(nil, server.name, "CAP", sSession.client.Nick(), "DEL", capStr)
  647. }
  648. }
  649. if !addedCaps.Empty() {
  650. for _, capStr := range added[sSession.capVersion] {
  651. sSession.Send(nil, server.name, "CAP", sSession.client.Nick(), "NEW", capStr)
  652. }
  653. }
  654. }
  655. server.setupPprofListener(config)
  656. // set RPL_ISUPPORT
  657. var newISupportReplies [][]string
  658. if oldConfig != nil {
  659. newISupportReplies = oldConfig.Server.isupport.GetDifference(&config.Server.isupport)
  660. }
  661. if len(config.Server.ProxyAllowedFrom) != 0 {
  662. server.logger.Info("server", "Proxied IPs will be accepted from", strings.Join(config.Server.ProxyAllowedFrom, ", "))
  663. }
  664. // we are now ready to receive connections:
  665. err = server.setupListeners(config)
  666. if initial && err == nil {
  667. server.logger.Info("server", "Server running")
  668. sdnotify.Ready()
  669. }
  670. if !initial {
  671. // push new info to all of our clients
  672. for _, sClient := range server.clients.AllClients() {
  673. for _, tokenline := range newISupportReplies {
  674. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  675. }
  676. if sendRawOutputNotice {
  677. sClient.Notice(sClient.t("This server is in debug mode and is logging all user I/O. If you do not wish for everything you send to be readable by the server owner(s), please disconnect."))
  678. }
  679. }
  680. }
  681. // send other config warnings
  682. if config.Accounts.RequireSasl.Enabled && config.Accounts.Registration.Enabled {
  683. server.logger.Warning("server", "Warning: although require-sasl is enabled, users can still register accounts. If your server is not intended to be public, you must set accounts.registration.enabled to false.")
  684. }
  685. return err
  686. }
  687. func (server *Server) setupPprofListener(config *Config) {
  688. pprofListener := config.Debug.PprofListener
  689. if server.pprofServer != nil {
  690. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  691. server.logger.Info("server", "Stopping pprof listener", server.pprofServer.Addr)
  692. server.pprofServer.Close()
  693. server.pprofServer = nil
  694. }
  695. }
  696. if pprofListener != "" && server.pprofServer == nil {
  697. ps := http.Server{
  698. Addr: pprofListener,
  699. }
  700. go func() {
  701. if err := ps.ListenAndServe(); err != nil {
  702. server.logger.Error("server", "pprof listener failed", err.Error())
  703. }
  704. }()
  705. server.pprofServer = &ps
  706. server.logger.Info("server", "Started pprof listener", server.pprofServer.Addr)
  707. }
  708. }
  709. func (server *Server) loadDatastore(config *Config) error {
  710. // open the datastore and load server state for which it (rather than config)
  711. // is the source of truth
  712. _, err := os.Stat(config.Datastore.Path)
  713. if os.IsNotExist(err) {
  714. server.logger.Warning("server", "database does not exist, creating it", config.Datastore.Path)
  715. err = initializeDB(config.Datastore.Path)
  716. if err != nil {
  717. return err
  718. }
  719. }
  720. db, err := OpenDatabase(config)
  721. if err == nil {
  722. server.store = db
  723. return nil
  724. } else {
  725. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  726. }
  727. }
  728. func (server *Server) loadFromDatastore(config *Config) (err error) {
  729. // load *lines (from the datastores)
  730. server.logger.Debug("server", "Loading D/Klines")
  731. server.loadDLines()
  732. server.loadKLines()
  733. server.channelRegistry.Initialize(server)
  734. server.channels.Initialize(server)
  735. server.accounts.Initialize(server)
  736. if config.Datastore.MySQL.Enabled {
  737. server.historyDB.Initialize(server.logger, config.Datastore.MySQL)
  738. err = server.historyDB.Open()
  739. if err != nil {
  740. server.logger.Error("internal", "could not connect to mysql", err.Error())
  741. return err
  742. }
  743. }
  744. return nil
  745. }
  746. func (server *Server) setupListeners(config *Config) (err error) {
  747. logListener := func(addr string, config utils.ListenerConfig) {
  748. server.logger.Info("listeners",
  749. fmt.Sprintf("now listening on %s, tls=%t, proxy=%t, tor=%t, websocket=%t.", addr, (config.TLSConfig != nil), config.RequireProxy, config.Tor, config.WebSocket),
  750. )
  751. }
  752. // update or destroy all existing listeners
  753. for addr := range server.listeners {
  754. currentListener := server.listeners[addr]
  755. newConfig, stillConfigured := config.Server.trueListeners[addr]
  756. if stillConfigured {
  757. if reloadErr := currentListener.Reload(newConfig); reloadErr == nil {
  758. logListener(addr, newConfig)
  759. } else {
  760. // stop the listener; we will attempt to replace it below
  761. currentListener.Stop()
  762. delete(server.listeners, addr)
  763. }
  764. } else {
  765. currentListener.Stop()
  766. delete(server.listeners, addr)
  767. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  768. }
  769. }
  770. publicPlaintextListener := ""
  771. // create new listeners that were not previously configured,
  772. // or that couldn't be reloaded above:
  773. for newAddr, newConfig := range config.Server.trueListeners {
  774. if strings.HasPrefix(newAddr, ":") && !newConfig.Tor && !newConfig.STSOnly && newConfig.TLSConfig == nil {
  775. publicPlaintextListener = newAddr
  776. }
  777. _, exists := server.listeners[newAddr]
  778. if !exists {
  779. // make a new listener
  780. newListener, newErr := NewListener(server, newAddr, newConfig, config.Server.UnixBindMode)
  781. if newErr == nil {
  782. server.listeners[newAddr] = newListener
  783. logListener(newAddr, newConfig)
  784. } else {
  785. server.logger.Error("server", "couldn't listen on", newAddr, newErr.Error())
  786. err = newErr
  787. }
  788. }
  789. }
  790. if publicPlaintextListener != "" {
  791. server.logger.Warning("listeners", fmt.Sprintf("Warning: your server is configured with public plaintext listener %s. Consider disabling it for improved security and privacy.", publicPlaintextListener))
  792. }
  793. return
  794. }
  795. // Gets the abstract sequence from which we're going to query history;
  796. // we may already know the channel we're querying, or we may have
  797. // to look it up via a string query. This function is responsible for
  798. // privilege checking.
  799. // XXX: call this with providedChannel==nil and query=="" to get a sequence
  800. // suitable for ListCorrespondents (i.e., this function is still used to
  801. // decide whether the ringbuf or mysql is authoritative about the client's
  802. // message history).
  803. func (server *Server) GetHistorySequence(providedChannel *Channel, client *Client, query string) (channel *Channel, sequence history.Sequence, err error) {
  804. config := server.Config()
  805. // 4 cases: {persistent, ephemeral} x {normal, conversation}
  806. // with ephemeral history, target is implicit in the choice of `hist`,
  807. // and correspondent is "" if we're retrieving a channel or *, and the correspondent's name
  808. // if we're retrieving a DM conversation ("query buffer"). with persistent history,
  809. // target is always nonempty, and correspondent is either empty or nonempty as before.
  810. var status HistoryStatus
  811. var target, correspondent string
  812. var hist *history.Buffer
  813. restriction := HistoryCutoffNone
  814. channel = providedChannel
  815. if channel == nil {
  816. if strings.HasPrefix(query, "#") {
  817. channel = server.channels.Get(query)
  818. if channel == nil {
  819. return
  820. }
  821. }
  822. }
  823. var joinTimeCutoff time.Time
  824. if channel != nil {
  825. if present, cutoff := channel.joinTimeCutoff(client); present {
  826. joinTimeCutoff = cutoff
  827. } else {
  828. err = errInsufficientPrivs
  829. return
  830. }
  831. status, target, restriction = channel.historyStatus(config)
  832. switch status {
  833. case HistoryEphemeral:
  834. hist = &channel.history
  835. case HistoryPersistent:
  836. // already set `target`
  837. default:
  838. return
  839. }
  840. } else {
  841. status, target = client.historyStatus(config)
  842. if query != "" {
  843. correspondent, err = CasefoldName(query)
  844. if err != nil {
  845. return
  846. }
  847. }
  848. switch status {
  849. case HistoryEphemeral:
  850. hist = &client.history
  851. case HistoryPersistent:
  852. // already set `target`, and `correspondent` if necessary
  853. default:
  854. return
  855. }
  856. }
  857. var cutoff time.Time
  858. if config.History.Restrictions.ExpireTime != 0 {
  859. cutoff = time.Now().UTC().Add(-time.Duration(config.History.Restrictions.ExpireTime))
  860. }
  861. // #836: registration date cutoff is always enforced for DMs
  862. // either way, take the later of the two cutoffs
  863. if restriction == HistoryCutoffRegistrationTime || channel == nil {
  864. regCutoff := client.historyCutoff()
  865. if regCutoff.After(cutoff) {
  866. cutoff = regCutoff
  867. }
  868. } else if restriction == HistoryCutoffJoinTime {
  869. if joinTimeCutoff.After(cutoff) {
  870. cutoff = joinTimeCutoff
  871. }
  872. }
  873. // #836 again: grace period is never applied to DMs
  874. if !cutoff.IsZero() && channel != nil && restriction != HistoryCutoffJoinTime {
  875. cutoff = cutoff.Add(-time.Duration(config.History.Restrictions.GracePeriod))
  876. }
  877. if hist != nil {
  878. sequence = hist.MakeSequence(correspondent, cutoff)
  879. } else if target != "" {
  880. sequence = server.historyDB.MakeSequence(target, correspondent, cutoff)
  881. }
  882. return
  883. }
  884. func (server *Server) ForgetHistory(accountName string) {
  885. // sanity check
  886. if accountName == "*" {
  887. return
  888. }
  889. config := server.Config()
  890. if !config.History.Enabled {
  891. return
  892. }
  893. if cfAccount, err := CasefoldName(accountName); err == nil {
  894. server.historyDB.Forget(cfAccount)
  895. }
  896. persistent := config.History.Persistent
  897. if persistent.Enabled && persistent.UnregisteredChannels && persistent.RegisteredChannels == PersistentMandatory && persistent.DirectMessages == PersistentMandatory {
  898. return
  899. }
  900. predicate := func(item *history.Item) bool { return item.AccountName == accountName }
  901. for _, channel := range server.channels.Channels() {
  902. channel.history.Delete(predicate)
  903. }
  904. for _, client := range server.clients.AllClients() {
  905. client.history.Delete(predicate)
  906. }
  907. }
  908. // deletes a message. target is a hint about what buffer it's in (not required for
  909. // persistent history, where all the msgids are indexed together). if accountName
  910. // is anything other than "*", it must match the recorded AccountName of the message
  911. func (server *Server) DeleteMessage(target, msgid, accountName string) (err error) {
  912. config := server.Config()
  913. var hist *history.Buffer
  914. if target != "" {
  915. if target[0] == '#' {
  916. channel := server.channels.Get(target)
  917. if channel != nil {
  918. if status, _, _ := channel.historyStatus(config); status == HistoryEphemeral {
  919. hist = &channel.history
  920. }
  921. }
  922. } else {
  923. client := server.clients.Get(target)
  924. if client != nil {
  925. if status, _ := client.historyStatus(config); status == HistoryEphemeral {
  926. hist = &client.history
  927. }
  928. }
  929. }
  930. }
  931. if hist == nil {
  932. err = server.historyDB.DeleteMsgid(msgid, accountName)
  933. } else {
  934. count := hist.Delete(func(item *history.Item) bool {
  935. return item.Message.Msgid == msgid && (accountName == "*" || item.AccountName == accountName)
  936. })
  937. if count == 0 {
  938. err = errNoop
  939. }
  940. }
  941. return
  942. }
  943. func (server *Server) UnfoldName(cfname string) (name string) {
  944. if strings.HasPrefix(cfname, "#") {
  945. return server.channels.UnfoldName(cfname)
  946. }
  947. return server.clients.UnfoldNick(cfname)
  948. }
  949. // elistMatcher takes and matches ELIST conditions
  950. type elistMatcher struct {
  951. MinClientsActive bool
  952. MinClients int
  953. MaxClientsActive bool
  954. MaxClients int
  955. }
  956. // Matches checks whether the given channel matches our matches.
  957. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  958. if matcher.MinClientsActive {
  959. if len(channel.Members()) < matcher.MinClients {
  960. return false
  961. }
  962. }
  963. if matcher.MaxClientsActive {
  964. if len(channel.Members()) > matcher.MaxClients {
  965. return false
  966. }
  967. }
  968. return true
  969. }
  970. var (
  971. infoString1 = strings.Split(`
  972. __ __ ______ ___ ______ ___
  973. __/ // /_/ ____/ __ \/ ____/ __ \
  974. /_ // __/ __/ / /_/ / / __/ / / /
  975. /_ // __/ /___/ _, _/ /_/ / /_/ /
  976. /_//_/ /_____/_/ |_|\____/\____/
  977. https://ergo.chat/
  978. https://github.com/ergochat/ergo
  979. `, "\n")[1:] // XXX: cut off initial blank line
  980. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  981. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  982. `, "\n")
  983. infoString3 = strings.Split(` Jeremy Latt, jlatt
  984. Edmund Huber, edmund-huber
  985. `, "\n")
  986. )