Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

server.go 40KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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. 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. // SASL
  724. oldAccountConfig := server.AccountConfig()
  725. authPreviouslyEnabled := oldAccountConfig != nil && oldAccountConfig.AuthenticationEnabled
  726. if config.Accounts.AuthenticationEnabled && !authPreviouslyEnabled {
  727. // enabling SASL
  728. SupportedCapabilities.Enable(caps.SASL)
  729. CapValues.Set(caps.SASL, "PLAIN,EXTERNAL")
  730. addedCaps.Add(caps.SASL)
  731. } else if !config.Accounts.AuthenticationEnabled && authPreviouslyEnabled {
  732. // disabling SASL
  733. SupportedCapabilities.Disable(caps.SASL)
  734. removedCaps.Add(caps.SASL)
  735. }
  736. nickReservationPreviouslyDisabled := oldAccountConfig != nil && !oldAccountConfig.NickReservation.Enabled
  737. nickReservationNowEnabled := config.Accounts.NickReservation.Enabled
  738. if nickReservationPreviouslyDisabled && nickReservationNowEnabled {
  739. server.accounts.buildNickToAccountIndex()
  740. }
  741. // STS
  742. stsValue := config.Server.STS.Value()
  743. var stsDisabled bool
  744. stsCurrentCapValue, _ := CapValues.Get(caps.STS)
  745. server.logger.Debug("rehash", "STS Vals", stsCurrentCapValue, stsValue, fmt.Sprintf("server[%v] config[%v]", server.stsEnabled, config.Server.STS.Enabled))
  746. if config.Server.STS.Enabled && !server.stsEnabled {
  747. // enabling STS
  748. SupportedCapabilities.Enable(caps.STS)
  749. addedCaps.Add(caps.STS)
  750. CapValues.Set(caps.STS, stsValue)
  751. } else if !config.Server.STS.Enabled && server.stsEnabled {
  752. // disabling STS
  753. SupportedCapabilities.Disable(caps.STS)
  754. removedCaps.Add(caps.STS)
  755. stsDisabled = true
  756. } else if config.Server.STS.Enabled && server.stsEnabled && stsValue != stsCurrentCapValue {
  757. // STS policy updated
  758. CapValues.Set(caps.STS, stsValue)
  759. updatedCaps.Add(caps.STS)
  760. }
  761. server.stsEnabled = config.Server.STS.Enabled
  762. // burst new and removed caps
  763. var capBurstClients ClientSet
  764. added := make(map[caps.Version]string)
  765. var removed string
  766. // updated caps get DEL'd and then NEW'd
  767. // so, we can just add updated ones to both removed and added lists here and they'll be correctly handled
  768. server.logger.Debug("rehash", "Updated Caps", updatedCaps.String(caps.Cap301, CapValues), strconv.Itoa(updatedCaps.Count()))
  769. for _, capab := range updatedCaps.List() {
  770. addedCaps.Enable(capab)
  771. removedCaps.Enable(capab)
  772. }
  773. if 0 < addedCaps.Count() || 0 < removedCaps.Count() {
  774. capBurstClients = server.clients.AllWithCaps(caps.CapNotify)
  775. added[caps.Cap301] = addedCaps.String(caps.Cap301, CapValues)
  776. added[caps.Cap302] = addedCaps.String(caps.Cap302, CapValues)
  777. // removed never has values, so we leave it as Cap301
  778. removed = removedCaps.String(caps.Cap301, CapValues)
  779. }
  780. for sClient := range capBurstClients {
  781. if stsDisabled {
  782. // remove STS policy
  783. //TODO(dan): this is an ugly hack. we can write this better.
  784. stsPolicy := "sts=duration=0"
  785. if 0 < addedCaps.Count() {
  786. added[caps.Cap302] = added[caps.Cap302] + " " + stsPolicy
  787. } else {
  788. addedCaps.Enable(caps.STS)
  789. added[caps.Cap302] = stsPolicy
  790. }
  791. }
  792. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  793. if 0 < removedCaps.Count() {
  794. sClient.Send(nil, server.name, "CAP", sClient.nick, "DEL", removed)
  795. }
  796. if 0 < addedCaps.Count() {
  797. sClient.Send(nil, server.name, "CAP", sClient.nick, "NEW", added[sClient.capVersion])
  798. }
  799. }
  800. // set server options
  801. server.configurableStateMutex.Lock()
  802. lineLenConfig := LineLenLimits{
  803. Tags: config.Limits.LineLen.Tags,
  804. Rest: config.Limits.LineLen.Rest,
  805. }
  806. server.limits = Limits{
  807. AwayLen: int(config.Limits.AwayLen),
  808. ChannelLen: int(config.Limits.ChannelLen),
  809. KickLen: int(config.Limits.KickLen),
  810. MonitorEntries: int(config.Limits.MonitorEntries),
  811. NickLen: int(config.Limits.NickLen),
  812. TopicLen: int(config.Limits.TopicLen),
  813. ChanListModes: int(config.Limits.ChanListModes),
  814. LineLen: lineLenConfig,
  815. }
  816. server.operclasses = *operclasses
  817. server.operators = opers
  818. server.checkIdent = config.Server.CheckIdent
  819. // registration
  820. server.channelRegistrationEnabled = config.Channels.Registration.Enabled
  821. server.defaultChannelModes = ParseDefaultChannelModes(config)
  822. server.configurableStateMutex.Unlock()
  823. // set new sendqueue size
  824. server.SetMaxSendQBytes(config.Server.MaxSendQBytes)
  825. server.loadMOTD(config.Server.MOTD, config.Server.MOTDFormatting)
  826. // reload logging config
  827. err = server.logger.ApplyConfig(config.Logging)
  828. if err != nil {
  829. return err
  830. }
  831. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  832. // notify clients if raw i/o logging was enabled by a rehash
  833. sendRawOutputNotice := !initial && !server.loggingRawIO && nowLoggingRawIO
  834. server.loggingRawIO = nowLoggingRawIO
  835. // save a pointer to the new config
  836. server.configurableStateMutex.Lock()
  837. server.config = config
  838. server.configurableStateMutex.Unlock()
  839. server.storeFilename = config.Datastore.Path
  840. server.logger.Info("rehash", "Using datastore", server.storeFilename)
  841. if initial {
  842. if err := server.loadDatastore(server.storeFilename); err != nil {
  843. return err
  844. }
  845. }
  846. server.setupPprofListener(config)
  847. // set RPL_ISUPPORT
  848. var newISupportReplies [][]string
  849. oldISupportList := server.ISupport()
  850. server.setISupport()
  851. if oldISupportList != nil {
  852. newISupportReplies = oldISupportList.GetDifference(server.ISupport())
  853. }
  854. // we are now open for business
  855. server.setupListeners(config)
  856. if !initial {
  857. // push new info to all of our clients
  858. for _, sClient := range server.clients.AllClients() {
  859. for _, tokenline := range newISupportReplies {
  860. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  861. }
  862. if sendRawOutputNotice {
  863. 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."))
  864. }
  865. }
  866. }
  867. return nil
  868. }
  869. func (server *Server) setupPprofListener(config *Config) {
  870. pprofListener := ""
  871. if config.Debug.PprofListener != nil {
  872. pprofListener = *config.Debug.PprofListener
  873. }
  874. if server.pprofServer != nil {
  875. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  876. server.logger.Info("rehash", "Stopping pprof listener", server.pprofServer.Addr)
  877. server.pprofServer.Close()
  878. server.pprofServer = nil
  879. }
  880. }
  881. if pprofListener != "" && server.pprofServer == nil {
  882. ps := http.Server{
  883. Addr: pprofListener,
  884. }
  885. go func() {
  886. if err := ps.ListenAndServe(); err != nil {
  887. server.logger.Error("rehash", fmt.Sprintf("pprof listener failed: %v", err))
  888. }
  889. }()
  890. server.pprofServer = &ps
  891. server.logger.Info("rehash", "Started pprof listener", server.pprofServer.Addr)
  892. }
  893. }
  894. func (server *Server) loadMOTD(motdPath string, useFormatting bool) error {
  895. server.logger.Info("rehash", "Using MOTD", motdPath)
  896. motdLines := make([]string, 0)
  897. if motdPath != "" {
  898. file, err := os.Open(motdPath)
  899. if err == nil {
  900. defer file.Close()
  901. reader := bufio.NewReader(file)
  902. for {
  903. line, err := reader.ReadString('\n')
  904. if err != nil {
  905. break
  906. }
  907. line = strings.TrimRight(line, "\r\n")
  908. if useFormatting {
  909. line = ircfmt.Unescape(line)
  910. }
  911. // "- " is the required prefix for MOTD, we just add it here to make
  912. // bursting it out to clients easier
  913. line = fmt.Sprintf("- %s", line)
  914. motdLines = append(motdLines, line)
  915. }
  916. } else {
  917. return err
  918. }
  919. }
  920. server.configurableStateMutex.Lock()
  921. server.motdLines = motdLines
  922. server.configurableStateMutex.Unlock()
  923. return nil
  924. }
  925. func (server *Server) loadDatastore(datastorePath string) error {
  926. // open the datastore and load server state for which it (rather than config)
  927. // is the source of truth
  928. db, err := OpenDatabase(datastorePath)
  929. if err == nil {
  930. server.store = db
  931. } else {
  932. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  933. }
  934. // load *lines (from the datastores)
  935. server.logger.Debug("startup", "Loading D/Klines")
  936. server.loadDLines()
  937. server.loadKLines()
  938. // load password manager
  939. server.logger.Debug("startup", "Loading passwords")
  940. err = server.store.View(func(tx *buntdb.Tx) error {
  941. saltString, err := tx.Get(keySalt)
  942. if err != nil {
  943. return fmt.Errorf("Could not retrieve salt string: %s", err.Error())
  944. }
  945. salt, err := base64.StdEncoding.DecodeString(saltString)
  946. if err != nil {
  947. return err
  948. }
  949. pwm := passwd.NewSaltedManager(salt)
  950. server.passwords = &pwm
  951. return nil
  952. })
  953. if err != nil {
  954. return fmt.Errorf("Could not load salt: %s", err.Error())
  955. }
  956. server.channelRegistry = NewChannelRegistry(server)
  957. server.accounts = NewAccountManager(server)
  958. return nil
  959. }
  960. func (server *Server) setupListeners(config *Config) {
  961. logListener := func(addr string, tlsconfig *tls.Config) {
  962. server.logger.Info("listeners",
  963. fmt.Sprintf("now listening on %s, tls=%t.", addr, (tlsconfig != nil)),
  964. )
  965. }
  966. // update or destroy all existing listeners
  967. tlsListeners := config.TLSListeners()
  968. for addr := range server.listeners {
  969. currentListener := server.listeners[addr]
  970. var stillConfigured bool
  971. for _, newaddr := range config.Server.Listen {
  972. if newaddr == addr {
  973. stillConfigured = true
  974. break
  975. }
  976. }
  977. // pass new config information to the listener, to be picked up after
  978. // its next Accept(). this is like sending over a buffered channel of
  979. // size 1, but where sending a second item overwrites the buffered item
  980. // instead of blocking.
  981. currentListener.configMutex.Lock()
  982. currentListener.shouldStop = !stillConfigured
  983. currentListener.tlsConfig = tlsListeners[addr]
  984. currentListener.configMutex.Unlock()
  985. if stillConfigured {
  986. logListener(addr, currentListener.tlsConfig)
  987. } else {
  988. // tell the listener it should stop by interrupting its Accept() call:
  989. currentListener.listener.Close()
  990. delete(server.listeners, addr)
  991. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  992. }
  993. }
  994. // create new listeners that were not previously configured
  995. for _, newaddr := range config.Server.Listen {
  996. _, exists := server.listeners[newaddr]
  997. if !exists {
  998. // make new listener
  999. tlsConfig := tlsListeners[newaddr]
  1000. server.listeners[newaddr] = server.createListener(newaddr, tlsConfig)
  1001. logListener(newaddr, tlsConfig)
  1002. }
  1003. }
  1004. if len(tlsListeners) == 0 {
  1005. 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")
  1006. }
  1007. var usesStandardTLSPort bool
  1008. for addr := range config.TLSListeners() {
  1009. if strings.Contains(addr, "6697") {
  1010. usesStandardTLSPort = true
  1011. break
  1012. }
  1013. }
  1014. if 0 < len(tlsListeners) && !usesStandardTLSPort {
  1015. 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")
  1016. }
  1017. }
  1018. // elistMatcher takes and matches ELIST conditions
  1019. type elistMatcher struct {
  1020. MinClientsActive bool
  1021. MinClients int
  1022. MaxClientsActive bool
  1023. MaxClients int
  1024. }
  1025. // Matches checks whether the given channel matches our matches.
  1026. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  1027. if matcher.MinClientsActive {
  1028. if len(channel.Members()) < matcher.MinClients {
  1029. return false
  1030. }
  1031. }
  1032. if matcher.MaxClientsActive {
  1033. if len(channel.Members()) < len(channel.members) {
  1034. return false
  1035. }
  1036. }
  1037. return true
  1038. }
  1039. // RplList returns the RPL_LIST numeric for the given channel.
  1040. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  1041. // get the correct number of channel members
  1042. var memberCount int
  1043. if target.flags[modes.Operator] || channel.hasClient(target) {
  1044. memberCount = len(channel.Members())
  1045. } else {
  1046. for _, member := range channel.Members() {
  1047. if !member.HasMode(modes.Invisible) {
  1048. memberCount++
  1049. }
  1050. }
  1051. }
  1052. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  1053. }
  1054. // ResumeDetails are the details that we use to resume connections.
  1055. type ResumeDetails struct {
  1056. OldNick string
  1057. Timestamp *time.Time
  1058. SendFakeJoinsFor []string
  1059. }
  1060. var (
  1061. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  1062. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  1063. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  1064. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  1065. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  1066. https://oragono.io/
  1067. https://github.com/oragono/oragono
  1068. https://crowdin.com/project/oragono
  1069. `, "\n")
  1070. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  1071. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  1072. `, "\n")
  1073. infoString3 = strings.Split(` 3onyc
  1074. Edmund Huber
  1075. Euan Kemp (euank)
  1076. Jeremy Latt
  1077. Martin Lindhe (martinlindhe)
  1078. Roberto Besser (besser)
  1079. Robin Burchell (rburchell)
  1080. Sean Enck (enckse)
  1081. soul9
  1082. Vegax
  1083. `, "\n")
  1084. )