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 40KB

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