您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

server.go 40KB

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