You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 39KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. "bufio"
  8. "crypto/tls"
  9. "encoding/base64"
  10. "fmt"
  11. "log"
  12. "math/rand"
  13. "net"
  14. "net/http"
  15. _ "net/http/pprof"
  16. "os"
  17. "os/signal"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "syscall"
  22. "time"
  23. "github.com/goshuirc/irc-go/ircfmt"
  24. "github.com/goshuirc/irc-go/ircmsg"
  25. "github.com/oragono/oragono/irc/caps"
  26. "github.com/oragono/oragono/irc/connection_limits"
  27. "github.com/oragono/oragono/irc/isupport"
  28. "github.com/oragono/oragono/irc/languages"
  29. "github.com/oragono/oragono/irc/logger"
  30. "github.com/oragono/oragono/irc/modes"
  31. "github.com/oragono/oragono/irc/passwd"
  32. "github.com/oragono/oragono/irc/sno"
  33. "github.com/oragono/oragono/irc/utils"
  34. "github.com/tidwall/buntdb"
  35. )
  36. var (
  37. // common error line to sub values into
  38. errorMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "%s ")}[0]).Line()
  39. // common error responses
  40. couldNotParseIPMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "Unable to parse your IP address")}[0]).Line()
  41. // supportedUserModesString acts as a cache for when we introduce users
  42. supportedUserModesString = modes.SupportedUserModes.String()
  43. // supportedChannelModesString acts as a cache for when we introduce users
  44. supportedChannelModesString = modes.SupportedChannelModes.String()
  45. // SupportedCapabilities are the caps we advertise.
  46. // MaxLine, SASL and STS are set during server startup.
  47. SupportedCapabilities = caps.NewSet(caps.AccountTag, caps.AccountNotify, caps.AwayNotify, caps.Batch, caps.CapNotify, caps.ChgHost, caps.EchoMessage, caps.ExtendedJoin, caps.InviteNotify, caps.LabeledResponse, caps.Languages, caps.MessageTags, caps.MultiPrefix, caps.Rename, caps.Resume, caps.ServerTime, caps.UserhostInNames)
  48. // CapValues are the actual values we advertise to v3.2 clients.
  49. // actual values are set during server startup.
  50. CapValues = caps.NewValues()
  51. )
  52. // Limits holds the maximum limits for various things such as topic lengths.
  53. type Limits struct {
  54. AwayLen int
  55. ChannelLen int
  56. KickLen int
  57. MonitorEntries int
  58. NickLen int
  59. TopicLen int
  60. ChanListModes int
  61. LineLen LineLenLimits
  62. }
  63. // LineLenLimits holds the maximum limits for IRC lines.
  64. type LineLenLimits struct {
  65. Tags int
  66. Rest int
  67. }
  68. // ListenerWrapper wraps a listener so it can be safely reconfigured or stopped
  69. type ListenerWrapper struct {
  70. listener net.Listener
  71. tlsConfig *tls.Config
  72. shouldStop bool
  73. // protects atomic update of tlsConfig and shouldStop:
  74. configMutex sync.Mutex // tier 1
  75. }
  76. // Server is the main Oragono server.
  77. type Server struct {
  78. accountConfig *AccountConfig
  79. accounts *AccountManager
  80. batches *BatchManager
  81. channelRegistrationEnabled bool
  82. channels *ChannelManager
  83. channelRegistry *ChannelRegistry
  84. checkIdent bool
  85. clients *ClientManager
  86. configFilename string
  87. configurableStateMutex sync.RWMutex // tier 1; generic protection for server state modified by rehash()
  88. connectionLimiter *connection_limits.Limiter
  89. connectionThrottler *connection_limits.Throttler
  90. ctime time.Time
  91. defaultChannelModes modes.Modes
  92. dlines *DLineManager
  93. loggingRawIO bool
  94. isupport *isupport.List
  95. klines *KLineManager
  96. languages *languages.Manager
  97. limits Limits
  98. listeners map[string]*ListenerWrapper
  99. logger *logger.Manager
  100. maxSendQBytes uint32
  101. monitorManager *MonitorManager
  102. motdLines []string
  103. name string
  104. nameCasefolded string
  105. networkName string
  106. operators map[string]Oper
  107. operclasses map[string]OperClass
  108. password []byte
  109. passwords *passwd.SaltedManager
  110. recoverFromErrors bool
  111. rehashMutex sync.Mutex // tier 4
  112. rehashSignal chan os.Signal
  113. pprofServer *http.Server
  114. proxyAllowedFrom []string
  115. signals chan os.Signal
  116. snomasks *SnoManager
  117. store *buntdb.DB
  118. storeFilename string
  119. stsEnabled bool
  120. webirc []webircConfig
  121. whoWas *WhoWasList
  122. }
  123. var (
  124. // ServerExitSignals are the signals the server will exit on.
  125. ServerExitSignals = []os.Signal{
  126. syscall.SIGINT,
  127. syscall.SIGTERM,
  128. syscall.SIGQUIT,
  129. }
  130. )
  131. type clientConn struct {
  132. Conn net.Conn
  133. IsTLS bool
  134. }
  135. // NewServer returns a new Oragono server.
  136. func NewServer(config *Config, logger *logger.Manager) (*Server, error) {
  137. // initialize data structures
  138. server := &Server{
  139. batches: NewBatchManager(),
  140. channels: NewChannelManager(),
  141. clients: NewClientManager(),
  142. connectionLimiter: connection_limits.NewLimiter(),
  143. connectionThrottler: connection_limits.NewThrottler(),
  144. languages: languages.NewManager(config.Languages.Default, config.Languages.Data),
  145. listeners: make(map[string]*ListenerWrapper),
  146. logger: logger,
  147. monitorManager: NewMonitorManager(),
  148. rehashSignal: make(chan os.Signal, 1),
  149. signals: make(chan os.Signal, len(ServerExitSignals)),
  150. snomasks: NewSnoManager(),
  151. whoWas: NewWhoWasList(config.Limits.WhowasEntries),
  152. }
  153. if err := server.applyConfig(config, true); err != nil {
  154. return nil, err
  155. }
  156. // generate help info
  157. if err := GenerateHelpIndices(server.languages); err != nil {
  158. return nil, err
  159. }
  160. // Attempt to clean up when receiving these signals.
  161. signal.Notify(server.signals, ServerExitSignals...)
  162. signal.Notify(server.rehashSignal, syscall.SIGHUP)
  163. return server, nil
  164. }
  165. // setISupport sets up our RPL_ISUPPORT reply.
  166. func (server *Server) setISupport() {
  167. maxTargetsString := strconv.Itoa(maxTargets)
  168. server.configurableStateMutex.RLock()
  169. // add RPL_ISUPPORT tokens
  170. isupport := isupport.NewList()
  171. isupport.Add("AWAYLEN", strconv.Itoa(server.limits.AwayLen))
  172. isupport.Add("CASEMAPPING", "ascii")
  173. isupport.Add("CHANMODES", strings.Join([]string{modes.Modes{modes.BanMask, modes.ExceptMask, modes.InviteMask}.String(), "", modes.Modes{modes.UserLimit, modes.Key}.String(), modes.Modes{modes.InviteOnly, modes.Moderated, modes.NoOutside, modes.OpOnlyTopic, modes.ChanRoleplaying, modes.Secret}.String()}, ","))
  174. isupport.Add("CHANNELLEN", strconv.Itoa(server.limits.ChannelLen))
  175. isupport.Add("CHANTYPES", "#")
  176. isupport.Add("ELIST", "U")
  177. isupport.Add("EXCEPTS", "")
  178. isupport.Add("INVEX", "")
  179. isupport.Add("KICKLEN", strconv.Itoa(server.limits.KickLen))
  180. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(server.limits.ChanListModes)))
  181. isupport.Add("MAXTARGETS", maxTargetsString)
  182. isupport.Add("MODES", "")
  183. isupport.Add("MONITOR", strconv.Itoa(server.limits.MonitorEntries))
  184. isupport.Add("NETWORK", server.networkName)
  185. isupport.Add("NICKLEN", strconv.Itoa(server.limits.NickLen))
  186. isupport.Add("PREFIX", "(qaohv)~&@%+")
  187. isupport.Add("RPCHAN", "E")
  188. isupport.Add("RPUSER", "E")
  189. isupport.Add("STATUSMSG", "~&@%+")
  190. isupport.Add("TARGMAX", fmt.Sprintf("NAMES:1,LIST:1,KICK:1,WHOIS:1,USERHOST:10,PRIVMSG:%s,TAGMSG:%s,NOTICE:%s,MONITOR:", maxTargetsString, maxTargetsString, maxTargetsString))
  191. isupport.Add("TOPICLEN", strconv.Itoa(server.limits.TopicLen))
  192. isupport.Add("UTF8MAPPING", casemappingName)
  193. // account registration
  194. if server.accountConfig.Registration.Enabled {
  195. // 'none' isn't shown in the REGCALLBACKS vars
  196. var enabledCallbacks []string
  197. for _, name := range server.accountConfig.Registration.EnabledCallbacks {
  198. if name != "*" {
  199. enabledCallbacks = append(enabledCallbacks, name)
  200. }
  201. }
  202. isupport.Add("REGCOMMANDS", "CREATE,VERIFY")
  203. isupport.Add("REGCALLBACKS", strings.Join(enabledCallbacks, ","))
  204. isupport.Add("REGCREDTYPES", "passphrase,certfp")
  205. }
  206. server.configurableStateMutex.RUnlock()
  207. isupport.RegenerateCachedReply()
  208. server.configurableStateMutex.Lock()
  209. server.isupport = isupport
  210. server.configurableStateMutex.Unlock()
  211. }
  212. func loadChannelList(channel *Channel, list string, maskMode modes.Mode) {
  213. if list == "" {
  214. return
  215. }
  216. channel.lists[maskMode].AddAll(strings.Split(list, " "))
  217. }
  218. // Shutdown shuts down the server.
  219. func (server *Server) Shutdown() {
  220. //TODO(dan): Make sure we disallow new nicks
  221. for _, client := range server.clients.AllClients() {
  222. client.Notice("Server is shutting down")
  223. }
  224. if err := server.store.Close(); err != nil {
  225. server.logger.Error("shutdown", fmt.Sprintln("Could not close datastore:", err))
  226. }
  227. }
  228. // Run starts the server.
  229. func (server *Server) Run() {
  230. // defer closing db/store
  231. defer server.store.Close()
  232. for {
  233. select {
  234. case <-server.signals:
  235. server.Shutdown()
  236. return
  237. case <-server.rehashSignal:
  238. go func() {
  239. server.logger.Info("rehash", "Rehashing due to SIGHUP")
  240. err := server.rehash()
  241. if err != nil {
  242. server.logger.Error("rehash", fmt.Sprintln("Failed to rehash:", err.Error()))
  243. }
  244. }()
  245. }
  246. }
  247. }
  248. func (server *Server) acceptClient(conn clientConn) {
  249. // check IP address
  250. ipaddr := utils.AddrToIP(conn.Conn.RemoteAddr())
  251. if ipaddr != nil {
  252. isBanned, banMsg := server.checkBans(ipaddr)
  253. if isBanned {
  254. // this might not show up properly on some clients, but our objective here is just to close the connection out before it has a load impact on us
  255. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  256. conn.Conn.Close()
  257. return
  258. }
  259. }
  260. server.logger.Debug("localconnect-ip", fmt.Sprintf("Client connecting from %v", ipaddr))
  261. // prolly don't need to alert snomasks on this, only on connection reg
  262. NewClient(server, conn.Conn, conn.IsTLS)
  263. }
  264. func (server *Server) checkBans(ipaddr net.IP) (banned bool, message string) {
  265. // check DLINEs
  266. isBanned, info := server.dlines.CheckIP(ipaddr)
  267. if isBanned {
  268. server.logger.Info("localconnect-ip", fmt.Sprintf("Client from %v rejected by d-line", ipaddr))
  269. return true, info.BanMessage("You are banned from this server (%s)")
  270. }
  271. // check connection limits
  272. err := server.connectionLimiter.AddClient(ipaddr, false)
  273. if err != nil {
  274. // too many connections from one client, tell the client and close the connection
  275. server.logger.Info("localconnect-ip", fmt.Sprintf("Client from %v rejected for connection limit", ipaddr))
  276. return true, "Too many clients from your network"
  277. }
  278. // check connection throttle
  279. err = server.connectionThrottler.AddClient(ipaddr)
  280. if err != nil {
  281. // too many connections too quickly from client, tell them and close the connection
  282. duration := server.connectionThrottler.BanDuration()
  283. length := &IPRestrictTime{
  284. Duration: duration,
  285. Expires: time.Now().Add(duration),
  286. }
  287. server.dlines.AddIP(ipaddr, length, server.connectionThrottler.BanMessage(), "Exceeded automated connection throttle", "auto.connection.throttler")
  288. // they're DLINE'd for 15 minutes or whatever, so we can reset the connection throttle now,
  289. // and once their temporary DLINE is finished they can fill up the throttler again
  290. server.connectionThrottler.ResetFor(ipaddr)
  291. // this might not show up properly on some clients, but our objective here is just to close it out before it has a load impact on us
  292. server.logger.Info(
  293. "localconnect-ip",
  294. fmt.Sprintf("Client from %v exceeded connection throttle, d-lining for %v", ipaddr, duration))
  295. return true, server.connectionThrottler.BanMessage()
  296. }
  297. return false, ""
  298. }
  299. //
  300. // IRC protocol listeners
  301. //
  302. // createListener starts the given listeners.
  303. func (server *Server) createListener(addr string, tlsConfig *tls.Config) *ListenerWrapper {
  304. // make listener
  305. var listener net.Listener
  306. var err error
  307. addr = strings.TrimPrefix(addr, "unix:")
  308. if strings.HasPrefix(addr, "/") {
  309. // https://stackoverflow.com/a/34881585
  310. os.Remove(addr)
  311. listener, err = net.Listen("unix", addr)
  312. } else {
  313. listener, err = net.Listen("tcp", addr)
  314. }
  315. if err != nil {
  316. log.Fatal(server, "listen error: ", err)
  317. }
  318. // throw our details to the server so we can be modified/killed later
  319. wrapper := ListenerWrapper{
  320. listener: listener,
  321. tlsConfig: tlsConfig,
  322. shouldStop: false,
  323. }
  324. var shouldStop bool
  325. // setup accept goroutine
  326. go func() {
  327. for {
  328. conn, err := listener.Accept()
  329. // synchronously access config data:
  330. // whether TLS is enabled and whether we should stop listening
  331. wrapper.configMutex.Lock()
  332. shouldStop = wrapper.shouldStop
  333. tlsConfig = wrapper.tlsConfig
  334. wrapper.configMutex.Unlock()
  335. if err == nil {
  336. if tlsConfig != nil {
  337. conn = tls.Server(conn, tlsConfig)
  338. }
  339. newConn := clientConn{
  340. Conn: conn,
  341. IsTLS: tlsConfig != nil,
  342. }
  343. // hand off the connection
  344. go server.acceptClient(newConn)
  345. }
  346. if shouldStop {
  347. listener.Close()
  348. return
  349. }
  350. }
  351. }()
  352. return &wrapper
  353. }
  354. // generateMessageID returns a network-unique message ID.
  355. func (server *Server) generateMessageID() string {
  356. // we don't need the full like 30 chars since the unixnano below handles
  357. // most of our uniqueness requirements, so just truncate at 5
  358. lastbit := strconv.FormatInt(rand.Int63(), 36)
  359. if 5 < len(lastbit) {
  360. lastbit = lastbit[:4]
  361. }
  362. return fmt.Sprintf("%s%s", strconv.FormatInt(time.Now().UTC().UnixNano(), 36), lastbit)
  363. }
  364. //
  365. // server functionality
  366. //
  367. func (server *Server) tryRegister(c *Client) {
  368. if c.Registered() {
  369. return
  370. }
  371. preregNick := c.PreregNick()
  372. if preregNick == "" || !c.HasUsername() || c.capState == caps.NegotiatingState {
  373. return
  374. }
  375. // client MUST send PASS (or AUTHENTICATE, if skip-server-password is set)
  376. // before completing the other registration commands
  377. if !c.Authorized() {
  378. c.Quit(c.t("Bad password"))
  379. c.destroy(false)
  380. return
  381. }
  382. rb := NewResponseBuffer(c)
  383. nickAssigned := performNickChange(server, c, c, preregNick, rb)
  384. rb.Send()
  385. if !nickAssigned {
  386. c.SetPreregNick("")
  387. return
  388. }
  389. // check KLINEs
  390. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  391. if isBanned {
  392. reason := info.Reason
  393. if info.Time != nil {
  394. reason += fmt.Sprintf(" [%s]", info.Time.Duration.String())
  395. }
  396. c.Quit(fmt.Sprintf(c.t("You are banned from this server (%s)"), reason))
  397. c.destroy(false)
  398. return
  399. }
  400. // continue registration
  401. server.logger.Debug("localconnect", fmt.Sprintf("Client registered [%s] [u:%s] [r:%s]", c.nick, c.username, c.realname))
  402. server.snomasks.Send(sno.LocalConnects, fmt.Sprintf(ircfmt.Unescape("Client registered $c[grey][$r%s$c[grey]] [u:$r%s$c[grey]] [h:$r%s$c[grey]] [r:$r%s$c[grey]]"), c.nick, c.username, c.rawHostname, c.realname))
  403. c.Register()
  404. // send welcome text
  405. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  406. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  407. c.Send(nil, server.name, RPL_WELCOME, c.nick, fmt.Sprintf(c.t("Welcome to the Internet Relay Network %s"), c.nick))
  408. c.Send(nil, server.name, RPL_YOURHOST, c.nick, fmt.Sprintf(c.t("Your host is %[1]s, running version %[2]s"), server.name, Ver))
  409. c.Send(nil, server.name, RPL_CREATED, c.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  410. //TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
  411. c.Send(nil, server.name, RPL_MYINFO, c.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
  412. rb = NewResponseBuffer(c)
  413. c.RplISupport(rb)
  414. server.MOTD(c, rb)
  415. rb.Send()
  416. c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
  417. if server.logger.IsLoggingRawIO() {
  418. c.Notice(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."))
  419. }
  420. // if resumed, send fake channel joins
  421. if c.resumeDetails != nil {
  422. for _, name := range c.resumeDetails.SendFakeJoinsFor {
  423. channel := server.channels.Get(name)
  424. if channel == nil {
  425. continue
  426. }
  427. if c.capabilities.Has(caps.ExtendedJoin) {
  428. c.Send(nil, c.nickMaskString, "JOIN", channel.name, c.AccountName(), c.realname)
  429. } else {
  430. c.Send(nil, c.nickMaskString, "JOIN", channel.name)
  431. }
  432. // reuse the last rb
  433. channel.SendTopic(c, rb)
  434. channel.Names(c, rb)
  435. rb.Send()
  436. // construct and send fake modestring if necessary
  437. c.stateMutex.RLock()
  438. myModes := channel.members[c]
  439. c.stateMutex.RUnlock()
  440. if myModes == nil {
  441. continue
  442. }
  443. oldModes := myModes.String()
  444. if 0 < len(oldModes) {
  445. params := []string{channel.name, "+" + oldModes}
  446. for range oldModes {
  447. params = append(params, c.nick)
  448. }
  449. c.Send(nil, server.name, "MODE", params...)
  450. }
  451. }
  452. }
  453. }
  454. // t returns the translated version of the given string, based on the languages configured by the client.
  455. func (client *Client) t(originalString string) string {
  456. // grab this mutex to protect client.languages
  457. client.stateMutex.RLock()
  458. defer client.stateMutex.RUnlock()
  459. return client.server.languages.Translate(client.languages, originalString)
  460. }
  461. // MOTD serves the Message of the Day.
  462. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  463. server.configurableStateMutex.RLock()
  464. motdLines := server.motdLines
  465. server.configurableStateMutex.RUnlock()
  466. if len(motdLines) < 1 {
  467. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  468. return
  469. }
  470. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  471. for _, line := range motdLines {
  472. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  473. }
  474. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  475. }
  476. // wordWrap wraps the given text into a series of lines that don't exceed lineWidth characters.
  477. func wordWrap(text string, lineWidth int) []string {
  478. var lines []string
  479. var cacheLine, cacheWord string
  480. for _, char := range text {
  481. if char == '\r' {
  482. continue
  483. } else if char == '\n' {
  484. cacheLine += cacheWord
  485. lines = append(lines, cacheLine)
  486. cacheWord = ""
  487. cacheLine = ""
  488. } else if (char == ' ' || char == '-') && len(cacheLine)+len(cacheWord)+1 < lineWidth {
  489. // natural word boundary
  490. cacheLine += cacheWord + string(char)
  491. cacheWord = ""
  492. } else if lineWidth <= len(cacheLine)+len(cacheWord)+1 {
  493. // time to wrap to next line
  494. if len(cacheLine) < (lineWidth / 2) {
  495. // this word takes up more than half a line... just split in the middle of the word
  496. cacheLine += cacheWord + string(char)
  497. cacheWord = ""
  498. } else {
  499. cacheWord += string(char)
  500. }
  501. lines = append(lines, cacheLine)
  502. cacheLine = ""
  503. } else {
  504. // normal character
  505. cacheWord += string(char)
  506. }
  507. }
  508. if 0 < len(cacheWord) {
  509. cacheLine += cacheWord
  510. }
  511. if 0 < len(cacheLine) {
  512. lines = append(lines, cacheLine)
  513. }
  514. return lines
  515. }
  516. // SplitMessage represents a message that's been split for sending.
  517. type SplitMessage struct {
  518. For512 []string
  519. ForMaxLine string
  520. }
  521. func (server *Server) splitMessage(original string, origIs512 bool) SplitMessage {
  522. var newSplit SplitMessage
  523. newSplit.ForMaxLine = original
  524. if !origIs512 {
  525. newSplit.For512 = wordWrap(original, 400)
  526. } else {
  527. newSplit.For512 = []string{original}
  528. }
  529. return newSplit
  530. }
  531. // WhoisChannelsNames returns the common channel names between two users.
  532. func (client *Client) WhoisChannelsNames(target *Client) []string {
  533. isMultiPrefix := target.capabilities.Has(caps.MultiPrefix)
  534. var chstrs []string
  535. for _, channel := range client.Channels() {
  536. // channel is secret and the target can't see it
  537. if !target.flags[modes.Operator] && channel.HasMode(modes.Secret) && !channel.hasClient(target) {
  538. continue
  539. }
  540. chstrs = append(chstrs, channel.ClientPrefixes(client, isMultiPrefix)+channel.name)
  541. }
  542. return chstrs
  543. }
  544. func (client *Client) getWhoisOf(target *Client, rb *ResponseBuffer) {
  545. target.stateMutex.RLock()
  546. defer target.stateMutex.RUnlock()
  547. rb.Add(nil, client.server.name, RPL_WHOISUSER, client.nick, target.nick, target.username, target.hostname, "*", target.realname)
  548. whoischannels := client.WhoisChannelsNames(target)
  549. if whoischannels != nil {
  550. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, client.nick, target.nick, strings.Join(whoischannels, " "))
  551. }
  552. if target.class != nil {
  553. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, client.nick, target.nick, target.whoisLine)
  554. }
  555. if client.flags[modes.Operator] || client == target {
  556. rb.Add(nil, client.server.name, RPL_WHOISACTUALLY, client.nick, target.nick, fmt.Sprintf("%s@%s", target.username, utils.LookupHostname(target.IPString())), target.IPString(), client.t("Actual user@host, Actual IP"))
  557. }
  558. if target.flags[modes.TLS] {
  559. rb.Add(nil, client.server.name, RPL_WHOISSECURE, client.nick, target.nick, client.t("is using a secure connection"))
  560. }
  561. if target.LoggedIntoAccount() {
  562. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, client.nick, client.AccountName(), client.t("is logged in as"))
  563. }
  564. if target.flags[modes.Bot] {
  565. rb.Add(nil, client.server.name, RPL_WHOISBOT, client.nick, target.nick, ircfmt.Unescape(fmt.Sprintf(client.t("is a $bBot$b on %s"), client.server.networkName)))
  566. }
  567. if 0 < len(target.languages) {
  568. params := []string{client.nick, target.nick}
  569. for _, str := range client.server.languages.Codes(target.languages) {
  570. params = append(params, str)
  571. }
  572. params = append(params, client.t("can speak these languages"))
  573. rb.Add(nil, client.server.name, RPL_WHOISLANGUAGE, params...)
  574. }
  575. if target.certfp != "" && (client.flags[modes.Operator] || client == target) {
  576. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, client.nick, target.nick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), target.certfp))
  577. }
  578. rb.Add(nil, client.server.name, RPL_WHOISIDLE, client.nick, target.nick, strconv.FormatUint(target.IdleSeconds(), 10), strconv.FormatInt(target.SignonTime(), 10), client.t("seconds idle, signon time"))
  579. }
  580. // rplWhoReply returns the WHO reply between one user and another channel/user.
  581. // <channel> <user> <host> <server> <nick> ( "H" / "G" ) ["*"] [ ( "@" / "+" ) ]
  582. // :<hopcount> <real name>
  583. func (target *Client) rplWhoReply(channel *Channel, client *Client, rb *ResponseBuffer) {
  584. channelName := "*"
  585. flags := ""
  586. if client.HasMode(modes.Away) {
  587. flags = "G"
  588. } else {
  589. flags = "H"
  590. }
  591. if client.HasMode(modes.Operator) {
  592. flags += "*"
  593. }
  594. if channel != nil {
  595. flags += channel.ClientPrefixes(client, target.capabilities.Has(caps.MultiPrefix))
  596. channelName = channel.name
  597. }
  598. rb.Add(nil, target.server.name, RPL_WHOREPLY, target.nick, channelName, client.Username(), client.Hostname(), client.server.name, client.Nick(), flags, strconv.Itoa(client.hops)+" "+client.Realname())
  599. }
  600. func whoChannel(client *Client, channel *Channel, friends ClientSet, rb *ResponseBuffer) {
  601. for _, member := range channel.Members() {
  602. if !client.flags[modes.Invisible] || friends[client] {
  603. client.rplWhoReply(channel, member, rb)
  604. }
  605. }
  606. }
  607. // rehash reloads the config and applies the changes from the config file.
  608. func (server *Server) rehash() error {
  609. server.logger.Debug("rehash", "Starting rehash")
  610. // only let one REHASH go on at a time
  611. server.rehashMutex.Lock()
  612. defer server.rehashMutex.Unlock()
  613. server.logger.Debug("rehash", "Got rehash lock")
  614. config, err := LoadConfig(server.configFilename)
  615. if err != nil {
  616. return fmt.Errorf("Error loading config file config: %s", err.Error())
  617. }
  618. err = server.applyConfig(config, false)
  619. if err != nil {
  620. return fmt.Errorf("Error applying config changes: %s", err.Error())
  621. }
  622. return nil
  623. }
  624. func (server *Server) applyConfig(config *Config, initial bool) error {
  625. if initial {
  626. server.ctime = time.Now()
  627. server.configFilename = config.Filename
  628. } else {
  629. // enforce configs that can't be changed after launch:
  630. if server.limits.LineLen.Tags != config.Limits.LineLen.Tags || server.limits.LineLen.Rest != config.Limits.LineLen.Rest {
  631. return fmt.Errorf("Maximum line length (linelen) cannot be changed after launching the server, rehash aborted")
  632. } else if server.name != config.Server.Name {
  633. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  634. } else if server.storeFilename != config.Datastore.Path {
  635. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  636. }
  637. }
  638. server.logger.Info("rehash", "Using config file", server.configFilename)
  639. casefoldedName, err := Casefold(config.Server.Name)
  640. if err != nil {
  641. return fmt.Errorf("Server name isn't valid [%s]: %s", config.Server.Name, err.Error())
  642. }
  643. // confirm operator stuff all exists and is fine
  644. operclasses, err := config.OperatorClasses()
  645. if err != nil {
  646. return fmt.Errorf("Error rehashing config file operclasses: %s", err.Error())
  647. }
  648. opers, err := config.Operators(operclasses)
  649. if err != nil {
  650. return fmt.Errorf("Error rehashing config file opers: %s", err.Error())
  651. }
  652. // TODO: support rehash of existing operator perms?
  653. // sanity checks complete, start modifying server state
  654. if initial {
  655. server.name = config.Server.Name
  656. server.nameCasefolded = casefoldedName
  657. }
  658. server.configurableStateMutex.Lock()
  659. server.networkName = config.Network.Name
  660. if config.Server.Password != "" {
  661. server.password = config.Server.PasswordBytes()
  662. } else {
  663. server.password = nil
  664. }
  665. // apply new WebIRC command restrictions
  666. server.webirc = config.Server.WebIRC
  667. // apply new PROXY command restrictions
  668. server.proxyAllowedFrom = config.Server.ProxyAllowedFrom
  669. server.recoverFromErrors = true
  670. if config.Debug.RecoverFromErrors != nil {
  671. server.recoverFromErrors = *config.Debug.RecoverFromErrors
  672. }
  673. server.configurableStateMutex.Unlock()
  674. err = server.connectionLimiter.ApplyConfig(config.Server.ConnectionLimiter)
  675. if err != nil {
  676. return err
  677. }
  678. err = server.connectionThrottler.ApplyConfig(config.Server.ConnectionThrottler)
  679. if err != nil {
  680. return err
  681. }
  682. // setup new and removed caps
  683. addedCaps := caps.NewSet()
  684. removedCaps := caps.NewSet()
  685. updatedCaps := caps.NewSet()
  686. // Translations
  687. currentLanguageValue, _ := CapValues.Get(caps.Languages)
  688. langCodes := []string{strconv.Itoa(len(config.Languages.Data) + 1), "en"}
  689. for _, info := range config.Languages.Data {
  690. if info.Incomplete {
  691. langCodes = append(langCodes, "~"+info.Code)
  692. } else {
  693. langCodes = append(langCodes, info.Code)
  694. }
  695. }
  696. newLanguageValue := strings.Join(langCodes, ",")
  697. server.logger.Debug("rehash", "Languages:", newLanguageValue)
  698. if currentLanguageValue != newLanguageValue {
  699. updatedCaps.Add(caps.Languages)
  700. CapValues.Set(caps.Languages, newLanguageValue)
  701. }
  702. lm := languages.NewManager(config.Languages.Default, config.Languages.Data)
  703. server.logger.Debug("rehash", "Regenerating HELP indexes for new languages")
  704. GenerateHelpIndices(lm)
  705. server.languages = lm
  706. // SASL
  707. oldAccountConfig := server.AccountConfig()
  708. authPreviouslyEnabled := oldAccountConfig != nil && oldAccountConfig.AuthenticationEnabled
  709. if config.Accounts.AuthenticationEnabled && !authPreviouslyEnabled {
  710. // enabling SASL
  711. SupportedCapabilities.Enable(caps.SASL)
  712. CapValues.Set(caps.SASL, "PLAIN,EXTERNAL")
  713. addedCaps.Add(caps.SASL)
  714. } else if !config.Accounts.AuthenticationEnabled && authPreviouslyEnabled {
  715. // disabling SASL
  716. SupportedCapabilities.Disable(caps.SASL)
  717. removedCaps.Add(caps.SASL)
  718. }
  719. server.configurableStateMutex.Lock()
  720. server.accountConfig = &config.Accounts
  721. server.configurableStateMutex.Unlock()
  722. nickReservationPreviouslyDisabled := oldAccountConfig != nil && !oldAccountConfig.NickReservation.Enabled
  723. nickReservationNowEnabled := config.Accounts.NickReservation.Enabled
  724. if nickReservationPreviouslyDisabled && nickReservationNowEnabled {
  725. server.accounts.buildNickToAccountIndex()
  726. }
  727. // STS
  728. stsValue := config.Server.STS.Value()
  729. var stsDisabled bool
  730. stsCurrentCapValue, _ := CapValues.Get(caps.STS)
  731. server.logger.Debug("rehash", "STS Vals", stsCurrentCapValue, stsValue, fmt.Sprintf("server[%v] config[%v]", server.stsEnabled, config.Server.STS.Enabled))
  732. if config.Server.STS.Enabled && !server.stsEnabled {
  733. // enabling STS
  734. SupportedCapabilities.Enable(caps.STS)
  735. addedCaps.Add(caps.STS)
  736. CapValues.Set(caps.STS, stsValue)
  737. } else if !config.Server.STS.Enabled && server.stsEnabled {
  738. // disabling STS
  739. SupportedCapabilities.Disable(caps.STS)
  740. removedCaps.Add(caps.STS)
  741. stsDisabled = true
  742. } else if config.Server.STS.Enabled && server.stsEnabled && stsValue != stsCurrentCapValue {
  743. // STS policy updated
  744. CapValues.Set(caps.STS, stsValue)
  745. updatedCaps.Add(caps.STS)
  746. }
  747. server.stsEnabled = config.Server.STS.Enabled
  748. // burst new and removed caps
  749. var capBurstClients ClientSet
  750. added := make(map[caps.Version]string)
  751. var removed string
  752. // updated caps get DEL'd and then NEW'd
  753. // so, we can just add updated ones to both removed and added lists here and they'll be correctly handled
  754. server.logger.Debug("rehash", "Updated Caps", updatedCaps.String(caps.Cap301, CapValues), strconv.Itoa(updatedCaps.Count()))
  755. for _, capab := range updatedCaps.List() {
  756. addedCaps.Enable(capab)
  757. removedCaps.Enable(capab)
  758. }
  759. if 0 < addedCaps.Count() || 0 < removedCaps.Count() {
  760. capBurstClients = server.clients.AllWithCaps(caps.CapNotify)
  761. added[caps.Cap301] = addedCaps.String(caps.Cap301, CapValues)
  762. added[caps.Cap302] = addedCaps.String(caps.Cap302, CapValues)
  763. // removed never has values, so we leave it as Cap301
  764. removed = removedCaps.String(caps.Cap301, CapValues)
  765. }
  766. for sClient := range capBurstClients {
  767. if stsDisabled {
  768. // remove STS policy
  769. //TODO(dan): this is an ugly hack. we can write this better.
  770. stsPolicy := "sts=duration=0"
  771. if 0 < addedCaps.Count() {
  772. added[caps.Cap302] = added[caps.Cap302] + " " + stsPolicy
  773. } else {
  774. addedCaps.Enable(caps.STS)
  775. added[caps.Cap302] = stsPolicy
  776. }
  777. }
  778. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  779. if 0 < removedCaps.Count() {
  780. sClient.Send(nil, server.name, "CAP", sClient.nick, "DEL", removed)
  781. }
  782. if 0 < addedCaps.Count() {
  783. sClient.Send(nil, server.name, "CAP", sClient.nick, "NEW", added[sClient.capVersion])
  784. }
  785. }
  786. // set server options
  787. server.configurableStateMutex.Lock()
  788. lineLenConfig := LineLenLimits{
  789. Tags: config.Limits.LineLen.Tags,
  790. Rest: config.Limits.LineLen.Rest,
  791. }
  792. server.limits = Limits{
  793. AwayLen: int(config.Limits.AwayLen),
  794. ChannelLen: int(config.Limits.ChannelLen),
  795. KickLen: int(config.Limits.KickLen),
  796. MonitorEntries: int(config.Limits.MonitorEntries),
  797. NickLen: int(config.Limits.NickLen),
  798. TopicLen: int(config.Limits.TopicLen),
  799. ChanListModes: int(config.Limits.ChanListModes),
  800. LineLen: lineLenConfig,
  801. }
  802. server.operclasses = *operclasses
  803. server.operators = opers
  804. server.checkIdent = config.Server.CheckIdent
  805. // registration
  806. server.channelRegistrationEnabled = config.Channels.Registration.Enabled
  807. server.defaultChannelModes = ParseDefaultChannelModes(config)
  808. server.configurableStateMutex.Unlock()
  809. // set new sendqueue size
  810. server.SetMaxSendQBytes(config.Server.MaxSendQBytes)
  811. // set RPL_ISUPPORT
  812. var newISupportReplies [][]string
  813. oldISupportList := server.isupport
  814. server.setISupport()
  815. if oldISupportList != nil {
  816. newISupportReplies = oldISupportList.GetDifference(server.isupport)
  817. }
  818. server.loadMOTD(config.Server.MOTD, config.Server.MOTDFormatting)
  819. // reload logging config
  820. err = server.logger.ApplyConfig(config.Logging)
  821. if err != nil {
  822. return err
  823. }
  824. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  825. // notify clients if raw i/o logging was enabled by a rehash
  826. sendRawOutputNotice := !initial && !server.loggingRawIO && nowLoggingRawIO
  827. server.loggingRawIO = nowLoggingRawIO
  828. server.storeFilename = config.Datastore.Path
  829. server.logger.Info("rehash", "Using datastore", server.storeFilename)
  830. if initial {
  831. if err := server.loadDatastore(server.storeFilename); err != nil {
  832. return err
  833. }
  834. }
  835. server.setupPprofListener(config)
  836. // we are now open for business
  837. server.setupListeners(config)
  838. if !initial {
  839. // push new info to all of our clients
  840. for _, sClient := range server.clients.AllClients() {
  841. for _, tokenline := range newISupportReplies {
  842. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  843. }
  844. if sendRawOutputNotice {
  845. 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."))
  846. }
  847. }
  848. }
  849. return nil
  850. }
  851. func (server *Server) setupPprofListener(config *Config) {
  852. pprofListener := ""
  853. if config.Debug.PprofListener != nil {
  854. pprofListener = *config.Debug.PprofListener
  855. }
  856. if server.pprofServer != nil {
  857. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  858. server.logger.Info("rehash", "Stopping pprof listener", server.pprofServer.Addr)
  859. server.pprofServer.Close()
  860. server.pprofServer = nil
  861. }
  862. }
  863. if pprofListener != "" && server.pprofServer == nil {
  864. ps := http.Server{
  865. Addr: pprofListener,
  866. }
  867. go func() {
  868. if err := ps.ListenAndServe(); err != nil {
  869. server.logger.Error("rehash", fmt.Sprintf("pprof listener failed: %v", err))
  870. }
  871. }()
  872. server.pprofServer = &ps
  873. server.logger.Info("rehash", "Started pprof listener", server.pprofServer.Addr)
  874. }
  875. }
  876. func (server *Server) loadMOTD(motdPath string, useFormatting bool) error {
  877. server.logger.Info("rehash", "Using MOTD", motdPath)
  878. motdLines := make([]string, 0)
  879. if motdPath != "" {
  880. file, err := os.Open(motdPath)
  881. if err == nil {
  882. defer file.Close()
  883. reader := bufio.NewReader(file)
  884. for {
  885. line, err := reader.ReadString('\n')
  886. if err != nil {
  887. break
  888. }
  889. line = strings.TrimRight(line, "\r\n")
  890. if useFormatting {
  891. line = ircfmt.Unescape(line)
  892. }
  893. // "- " is the required prefix for MOTD, we just add it here to make
  894. // bursting it out to clients easier
  895. line = fmt.Sprintf("- %s", line)
  896. motdLines = append(motdLines, line)
  897. }
  898. } else {
  899. return err
  900. }
  901. }
  902. server.configurableStateMutex.Lock()
  903. server.motdLines = motdLines
  904. server.configurableStateMutex.Unlock()
  905. return nil
  906. }
  907. func (server *Server) loadDatastore(datastorePath string) error {
  908. // open the datastore and load server state for which it (rather than config)
  909. // is the source of truth
  910. db, err := OpenDatabase(datastorePath)
  911. if err == nil {
  912. server.store = db
  913. } else {
  914. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  915. }
  916. // load *lines (from the datastores)
  917. server.logger.Debug("startup", "Loading D/Klines")
  918. server.loadDLines()
  919. server.loadKLines()
  920. // load password manager
  921. server.logger.Debug("startup", "Loading passwords")
  922. err = server.store.View(func(tx *buntdb.Tx) error {
  923. saltString, err := tx.Get(keySalt)
  924. if err != nil {
  925. return fmt.Errorf("Could not retrieve salt string: %s", err.Error())
  926. }
  927. salt, err := base64.StdEncoding.DecodeString(saltString)
  928. if err != nil {
  929. return err
  930. }
  931. pwm := passwd.NewSaltedManager(salt)
  932. server.passwords = &pwm
  933. return nil
  934. })
  935. if err != nil {
  936. return fmt.Errorf("Could not load salt: %s", err.Error())
  937. }
  938. server.channelRegistry = NewChannelRegistry(server)
  939. server.accounts = NewAccountManager(server)
  940. return nil
  941. }
  942. func (server *Server) setupListeners(config *Config) {
  943. logListener := func(addr string, tlsconfig *tls.Config) {
  944. server.logger.Info("listeners",
  945. fmt.Sprintf("now listening on %s, tls=%t.", addr, (tlsconfig != nil)),
  946. )
  947. }
  948. // update or destroy all existing listeners
  949. tlsListeners := config.TLSListeners()
  950. for addr := range server.listeners {
  951. currentListener := server.listeners[addr]
  952. var stillConfigured bool
  953. for _, newaddr := range config.Server.Listen {
  954. if newaddr == addr {
  955. stillConfigured = true
  956. break
  957. }
  958. }
  959. // pass new config information to the listener, to be picked up after
  960. // its next Accept(). this is like sending over a buffered channel of
  961. // size 1, but where sending a second item overwrites the buffered item
  962. // instead of blocking.
  963. currentListener.configMutex.Lock()
  964. currentListener.shouldStop = !stillConfigured
  965. currentListener.tlsConfig = tlsListeners[addr]
  966. currentListener.configMutex.Unlock()
  967. if stillConfigured {
  968. logListener(addr, currentListener.tlsConfig)
  969. } else {
  970. // tell the listener it should stop by interrupting its Accept() call:
  971. currentListener.listener.Close()
  972. delete(server.listeners, addr)
  973. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  974. }
  975. }
  976. // create new listeners that were not previously configured
  977. for _, newaddr := range config.Server.Listen {
  978. _, exists := server.listeners[newaddr]
  979. if !exists {
  980. // make new listener
  981. tlsConfig := tlsListeners[newaddr]
  982. server.listeners[newaddr] = server.createListener(newaddr, tlsConfig)
  983. logListener(newaddr, tlsConfig)
  984. }
  985. }
  986. if len(tlsListeners) == 0 {
  987. server.logger.Warning("startup", "You are not exposing an SSL/TLS listening port. You should expose at least one port (typically 6697) to accept TLS connections")
  988. }
  989. var usesStandardTLSPort bool
  990. for addr := range config.TLSListeners() {
  991. if strings.Contains(addr, "6697") {
  992. usesStandardTLSPort = true
  993. break
  994. }
  995. }
  996. if 0 < len(tlsListeners) && !usesStandardTLSPort {
  997. server.logger.Warning("startup", "Port 6697 is the standard TLS port for IRC. You should (also) expose port 6697 as a TLS port to ensure clients can connect securely")
  998. }
  999. }
  1000. // elistMatcher takes and matches ELIST conditions
  1001. type elistMatcher struct {
  1002. MinClientsActive bool
  1003. MinClients int
  1004. MaxClientsActive bool
  1005. MaxClients int
  1006. }
  1007. // Matches checks whether the given channel matches our matches.
  1008. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  1009. if matcher.MinClientsActive {
  1010. if len(channel.Members()) < matcher.MinClients {
  1011. return false
  1012. }
  1013. }
  1014. if matcher.MaxClientsActive {
  1015. if len(channel.Members()) < len(channel.members) {
  1016. return false
  1017. }
  1018. }
  1019. return true
  1020. }
  1021. // RplList returns the RPL_LIST numeric for the given channel.
  1022. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  1023. // get the correct number of channel members
  1024. var memberCount int
  1025. if target.flags[modes.Operator] || channel.hasClient(target) {
  1026. memberCount = len(channel.Members())
  1027. } else {
  1028. for _, member := range channel.Members() {
  1029. if !member.HasMode(modes.Invisible) {
  1030. memberCount++
  1031. }
  1032. }
  1033. }
  1034. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  1035. }
  1036. // ResumeDetails are the details that we use to resume connections.
  1037. type ResumeDetails struct {
  1038. OldNick string
  1039. Timestamp *time.Time
  1040. SendFakeJoinsFor []string
  1041. }
  1042. var (
  1043. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  1044. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  1045. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  1046. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  1047. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  1048. https://oragono.io/
  1049. https://github.com/oragono/oragono
  1050. https://crowdin.com/project/oragono
  1051. `, "\n")
  1052. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  1053. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  1054. `, "\n")
  1055. infoString3 = strings.Split(` 3onyc
  1056. Edmund Huber
  1057. Euan Kemp (euank)
  1058. Jeremy Latt
  1059. Martin Lindhe (martinlindhe)
  1060. Roberto Besser (besser)
  1061. Robin Burchell (rburchell)
  1062. Sean Enck (enckse)
  1063. soul9
  1064. Vegax
  1065. `, "\n")
  1066. )