Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

server.go 40KB

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