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

server.go 40KB

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