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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. "fmt"
  10. "net"
  11. "net/http"
  12. _ "net/http/pprof"
  13. "os"
  14. "os/signal"
  15. "strconv"
  16. "strings"
  17. "sync"
  18. "syscall"
  19. "time"
  20. "github.com/goshuirc/irc-go/ircfmt"
  21. "github.com/goshuirc/irc-go/ircmsg"
  22. "github.com/oragono/oragono/irc/caps"
  23. "github.com/oragono/oragono/irc/connection_limits"
  24. "github.com/oragono/oragono/irc/isupport"
  25. "github.com/oragono/oragono/irc/languages"
  26. "github.com/oragono/oragono/irc/logger"
  27. "github.com/oragono/oragono/irc/modes"
  28. "github.com/oragono/oragono/irc/sno"
  29. "github.com/oragono/oragono/irc/utils"
  30. "github.com/tidwall/buntdb"
  31. )
  32. var (
  33. // common error line to sub values into
  34. errorMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "%s ")}[0]).Line()
  35. // common error responses
  36. couldNotParseIPMsg, _ = (&[]ircmsg.IrcMessage{ircmsg.MakeMessage(nil, "", "ERROR", "Unable to parse your IP address")}[0]).Line()
  37. // supportedUserModesString acts as a cache for when we introduce users
  38. supportedUserModesString = modes.SupportedUserModes.String()
  39. // supportedChannelModesString acts as a cache for when we introduce users
  40. supportedChannelModesString = modes.SupportedChannelModes.String()
  41. // SupportedCapabilities are the caps we advertise.
  42. // MaxLine, SASL and STS are set during server startup.
  43. 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)
  44. // CapValues are the actual values we advertise to v3.2 clients.
  45. // actual values are set during server startup.
  46. CapValues = caps.NewValues()
  47. )
  48. // ListenerWrapper wraps a listener so it can be safely reconfigured or stopped
  49. type ListenerWrapper struct {
  50. listener net.Listener
  51. tlsConfig *tls.Config
  52. shouldStop bool
  53. // protects atomic update of tlsConfig and shouldStop:
  54. configMutex sync.Mutex // tier 1
  55. }
  56. // Server is the main Oragono server.
  57. type Server struct {
  58. accounts *AccountManager
  59. channels *ChannelManager
  60. channelRegistry *ChannelRegistry
  61. clients *ClientManager
  62. config *Config
  63. configFilename string
  64. configurableStateMutex sync.RWMutex // tier 1; generic protection for server state modified by rehash()
  65. connectionLimiter *connection_limits.Limiter
  66. connectionThrottler *connection_limits.Throttler
  67. ctime time.Time
  68. dlines *DLineManager
  69. isupport *isupport.List
  70. klines *KLineManager
  71. languages *languages.Manager
  72. listeners map[string]*ListenerWrapper
  73. logger *logger.Manager
  74. monitorManager *MonitorManager
  75. motdLines []string
  76. name string
  77. nameCasefolded string
  78. rehashMutex sync.Mutex // tier 4
  79. rehashSignal chan os.Signal
  80. pprofServer *http.Server
  81. signals chan os.Signal
  82. snomasks *SnoManager
  83. store *buntdb.DB
  84. whoWas *WhoWasList
  85. stats *Stats
  86. semaphores *ServerSemaphores
  87. }
  88. var (
  89. // ServerExitSignals are the signals the server will exit on.
  90. ServerExitSignals = []os.Signal{
  91. syscall.SIGINT,
  92. syscall.SIGTERM,
  93. syscall.SIGQUIT,
  94. }
  95. )
  96. type clientConn struct {
  97. Conn net.Conn
  98. IsTLS bool
  99. }
  100. // NewServer returns a new Oragono server.
  101. func NewServer(config *Config, logger *logger.Manager) (*Server, error) {
  102. // initialize data structures
  103. server := &Server{
  104. channels: NewChannelManager(),
  105. clients: NewClientManager(),
  106. connectionLimiter: connection_limits.NewLimiter(),
  107. connectionThrottler: connection_limits.NewThrottler(),
  108. languages: languages.NewManager(config.Languages.Default, config.Languages.Data),
  109. listeners: make(map[string]*ListenerWrapper),
  110. logger: logger,
  111. monitorManager: NewMonitorManager(),
  112. rehashSignal: make(chan os.Signal, 1),
  113. signals: make(chan os.Signal, len(ServerExitSignals)),
  114. snomasks: NewSnoManager(),
  115. whoWas: NewWhoWasList(config.Limits.WhowasEntries),
  116. stats: NewStats(),
  117. semaphores: NewServerSemaphores(),
  118. }
  119. if err := server.applyConfig(config, true); err != nil {
  120. return nil, err
  121. }
  122. // generate help info
  123. if err := GenerateHelpIndices(server.languages); err != nil {
  124. return nil, err
  125. }
  126. // Attempt to clean up when receiving these signals.
  127. signal.Notify(server.signals, ServerExitSignals...)
  128. signal.Notify(server.rehashSignal, syscall.SIGHUP)
  129. return server, nil
  130. }
  131. // setISupport sets up our RPL_ISUPPORT reply.
  132. func (server *Server) setISupport() (err error) {
  133. maxTargetsString := strconv.Itoa(maxTargets)
  134. config := server.Config()
  135. // add RPL_ISUPPORT tokens
  136. isupport := isupport.NewList()
  137. isupport.Add("AWAYLEN", strconv.Itoa(config.Limits.AwayLen))
  138. isupport.Add("CASEMAPPING", "ascii")
  139. 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()}, ","))
  140. isupport.Add("CHANNELLEN", strconv.Itoa(config.Limits.ChannelLen))
  141. isupport.Add("CHANTYPES", "#")
  142. isupport.Add("ELIST", "U")
  143. isupport.Add("EXCEPTS", "")
  144. isupport.Add("INVEX", "")
  145. isupport.Add("KICKLEN", strconv.Itoa(config.Limits.KickLen))
  146. isupport.Add("MAXLIST", fmt.Sprintf("beI:%s", strconv.Itoa(config.Limits.ChanListModes)))
  147. isupport.Add("MAXTARGETS", maxTargetsString)
  148. isupport.Add("MODES", "")
  149. isupport.Add("MONITOR", strconv.Itoa(config.Limits.MonitorEntries))
  150. isupport.Add("NETWORK", config.Network.Name)
  151. isupport.Add("NICKLEN", strconv.Itoa(config.Limits.NickLen))
  152. isupport.Add("PREFIX", "(qaohv)~&@%+")
  153. isupport.Add("RPCHAN", "E")
  154. isupport.Add("RPUSER", "E")
  155. isupport.Add("STATUSMSG", "~&@%+")
  156. 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))
  157. isupport.Add("TOPICLEN", strconv.Itoa(config.Limits.TopicLen))
  158. isupport.Add("UTF8MAPPING", casemappingName)
  159. // account registration
  160. if config.Accounts.Registration.Enabled {
  161. // 'none' isn't shown in the REGCALLBACKS vars
  162. var enabledCallbacks []string
  163. for _, name := range server.config.Accounts.Registration.EnabledCallbacks {
  164. if name != "*" {
  165. enabledCallbacks = append(enabledCallbacks, name)
  166. }
  167. }
  168. isupport.Add("ACCCOMMANDS", "CREATE,VERIFY")
  169. isupport.Add("REGCALLBACKS", strings.Join(enabledCallbacks, ","))
  170. isupport.Add("REGCREDTYPES", "passphrase,certfp")
  171. }
  172. err = isupport.RegenerateCachedReply()
  173. if err != nil {
  174. return
  175. }
  176. server.configurableStateMutex.Lock()
  177. server.isupport = isupport
  178. server.configurableStateMutex.Unlock()
  179. return
  180. }
  181. func loadChannelList(channel *Channel, list string, maskMode modes.Mode) {
  182. if list == "" {
  183. return
  184. }
  185. channel.lists[maskMode].AddAll(strings.Split(list, " "))
  186. }
  187. // Shutdown shuts down the server.
  188. func (server *Server) Shutdown() {
  189. //TODO(dan): Make sure we disallow new nicks
  190. for _, client := range server.clients.AllClients() {
  191. client.Notice("Server is shutting down")
  192. }
  193. if err := server.store.Close(); err != nil {
  194. server.logger.Error("shutdown", fmt.Sprintln("Could not close datastore:", err))
  195. }
  196. }
  197. // Run starts the server.
  198. func (server *Server) Run() {
  199. // defer closing db/store
  200. defer server.store.Close()
  201. for {
  202. select {
  203. case <-server.signals:
  204. server.Shutdown()
  205. return
  206. case <-server.rehashSignal:
  207. go func() {
  208. server.logger.Info("rehash", "Rehashing due to SIGHUP")
  209. err := server.rehash()
  210. if err != nil {
  211. server.logger.Error("rehash", fmt.Sprintln("Failed to rehash:", err.Error()))
  212. }
  213. }()
  214. }
  215. }
  216. }
  217. func (server *Server) acceptClient(conn clientConn) {
  218. // check IP address
  219. ipaddr := utils.AddrToIP(conn.Conn.RemoteAddr())
  220. if ipaddr != nil {
  221. isBanned, banMsg := server.checkBans(ipaddr)
  222. if isBanned {
  223. // 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
  224. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  225. conn.Conn.Close()
  226. return
  227. }
  228. }
  229. server.logger.Debug("localconnect-ip", fmt.Sprintf("Client connecting from %v", ipaddr))
  230. // prolly don't need to alert snomasks on this, only on connection reg
  231. NewClient(server, conn.Conn, conn.IsTLS)
  232. }
  233. func (server *Server) checkBans(ipaddr net.IP) (banned bool, message string) {
  234. // check DLINEs
  235. isBanned, info := server.dlines.CheckIP(ipaddr)
  236. if isBanned {
  237. server.logger.Info("localconnect-ip", fmt.Sprintf("Client from %v rejected by d-line", ipaddr))
  238. return true, info.BanMessage("You are banned from this server (%s)")
  239. }
  240. // check connection limits
  241. err := server.connectionLimiter.AddClient(ipaddr, false)
  242. if err != nil {
  243. // too many connections from one client, tell the client and close the connection
  244. server.logger.Info("localconnect-ip", fmt.Sprintf("Client from %v rejected for connection limit", ipaddr))
  245. return true, "Too many clients from your network"
  246. }
  247. // check connection throttle
  248. err = server.connectionThrottler.AddClient(ipaddr)
  249. if err != nil {
  250. // too many connections too quickly from client, tell them and close the connection
  251. duration := server.connectionThrottler.BanDuration()
  252. length := &IPRestrictTime{
  253. Duration: duration,
  254. Expires: time.Now().Add(duration),
  255. }
  256. server.dlines.AddIP(ipaddr, length, server.connectionThrottler.BanMessage(), "Exceeded automated connection throttle", "auto.connection.throttler")
  257. // they're DLINE'd for 15 minutes or whatever, so we can reset the connection throttle now,
  258. // and once their temporary DLINE is finished they can fill up the throttler again
  259. server.connectionThrottler.ResetFor(ipaddr)
  260. // 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
  261. server.logger.Info(
  262. "localconnect-ip",
  263. fmt.Sprintf("Client from %v exceeded connection throttle, d-lining for %v", ipaddr, duration))
  264. return true, server.connectionThrottler.BanMessage()
  265. }
  266. return false, ""
  267. }
  268. //
  269. // IRC protocol listeners
  270. //
  271. // createListener starts a given listener.
  272. func (server *Server) createListener(addr string, tlsConfig *tls.Config, bindMode os.FileMode) (*ListenerWrapper, error) {
  273. // make listener
  274. var listener net.Listener
  275. var err error
  276. addr = strings.TrimPrefix(addr, "unix:")
  277. if strings.HasPrefix(addr, "/") {
  278. // https://stackoverflow.com/a/34881585
  279. os.Remove(addr)
  280. listener, err = net.Listen("unix", addr)
  281. if err == nil && bindMode != 0 {
  282. os.Chmod(addr, bindMode)
  283. }
  284. } else {
  285. listener, err = net.Listen("tcp", addr)
  286. }
  287. if err != nil {
  288. return nil, err
  289. }
  290. // throw our details to the server so we can be modified/killed later
  291. wrapper := ListenerWrapper{
  292. listener: listener,
  293. tlsConfig: tlsConfig,
  294. shouldStop: false,
  295. }
  296. var shouldStop bool
  297. // setup accept goroutine
  298. go func() {
  299. for {
  300. conn, err := listener.Accept()
  301. // synchronously access config data:
  302. // whether TLS is enabled and whether we should stop listening
  303. wrapper.configMutex.Lock()
  304. shouldStop = wrapper.shouldStop
  305. tlsConfig = wrapper.tlsConfig
  306. wrapper.configMutex.Unlock()
  307. if err == nil {
  308. if tlsConfig != nil {
  309. conn = tls.Server(conn, tlsConfig)
  310. }
  311. newConn := clientConn{
  312. Conn: conn,
  313. IsTLS: tlsConfig != nil,
  314. }
  315. // hand off the connection
  316. go server.acceptClient(newConn)
  317. }
  318. if shouldStop {
  319. listener.Close()
  320. return
  321. }
  322. }
  323. }()
  324. return &wrapper, nil
  325. }
  326. // generateMessageID returns a network-unique message ID.
  327. func (server *Server) generateMessageID() string {
  328. return utils.GenerateSecretToken()
  329. }
  330. //
  331. // server functionality
  332. //
  333. func (server *Server) tryRegister(c *Client) {
  334. if c.Registered() {
  335. return
  336. }
  337. preregNick := c.PreregNick()
  338. if preregNick == "" || !c.HasUsername() || c.capState == caps.NegotiatingState {
  339. return
  340. }
  341. // client MUST send PASS (or AUTHENTICATE, if skip-server-password is set)
  342. // before completing the other registration commands
  343. if !c.Authorized() {
  344. c.Quit(c.t("Bad password"))
  345. c.destroy(false)
  346. return
  347. }
  348. rb := NewResponseBuffer(c)
  349. nickAssigned := performNickChange(server, c, c, preregNick, rb)
  350. rb.Send(true)
  351. if !nickAssigned {
  352. c.SetPreregNick("")
  353. return
  354. }
  355. // check KLINEs
  356. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  357. if isBanned {
  358. reason := info.Reason
  359. if info.Time != nil {
  360. reason += fmt.Sprintf(" [%s]", info.Time.Duration.String())
  361. }
  362. c.Quit(fmt.Sprintf(c.t("You are banned from this server (%s)"), reason))
  363. c.destroy(false)
  364. return
  365. }
  366. // count new user in statistics
  367. server.stats.ChangeTotal(1)
  368. // continue registration
  369. server.logger.Debug("localconnect", fmt.Sprintf("Client connected [%s] [u:%s] [r:%s]", c.nick, c.username, c.realname))
  370. server.snomasks.Send(sno.LocalConnects, fmt.Sprintf("Client connected [%s] [u:%s] [h:%s] [ip:%s] [r:%s]", c.nick, c.username, c.rawHostname, c.IPString(), c.realname))
  371. // "register"; this includes the initial phase of session resumption
  372. c.Register()
  373. // send welcome text
  374. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  375. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  376. c.Send(nil, server.name, RPL_WELCOME, c.nick, fmt.Sprintf(c.t("Welcome to the Internet Relay Network %s"), c.nick))
  377. 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))
  378. c.Send(nil, server.name, RPL_CREATED, c.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  379. //TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
  380. c.Send(nil, server.name, RPL_MYINFO, c.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
  381. rb = NewResponseBuffer(c)
  382. c.RplISupport(rb)
  383. server.MOTD(c, rb)
  384. rb.Send(true)
  385. modestring := c.ModeString()
  386. if modestring != "+" {
  387. c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
  388. }
  389. if server.logger.IsLoggingRawIO() {
  390. 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."))
  391. }
  392. // if resumed, send fake channel joins
  393. c.tryResumeChannels()
  394. }
  395. // t returns the translated version of the given string, based on the languages configured by the client.
  396. func (client *Client) t(originalString string) string {
  397. // grab this mutex to protect client.languages
  398. client.stateMutex.RLock()
  399. defer client.stateMutex.RUnlock()
  400. return client.server.languages.Translate(client.languages, originalString)
  401. }
  402. // MOTD serves the Message of the Day.
  403. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  404. server.configurableStateMutex.RLock()
  405. motdLines := server.motdLines
  406. server.configurableStateMutex.RUnlock()
  407. if len(motdLines) < 1 {
  408. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  409. return
  410. }
  411. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  412. for _, line := range motdLines {
  413. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  414. }
  415. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  416. }
  417. // WhoisChannelsNames returns the common channel names between two users.
  418. func (client *Client) WhoisChannelsNames(target *Client) []string {
  419. isMultiPrefix := client.capabilities.Has(caps.MultiPrefix)
  420. var chstrs []string
  421. for _, channel := range target.Channels() {
  422. // channel is secret and the target can't see it
  423. if !client.HasMode(modes.Operator) {
  424. if (target.HasMode(modes.Invisible) || channel.flags.HasMode(modes.Secret)) && !channel.hasClient(client) {
  425. continue
  426. }
  427. }
  428. chstrs = append(chstrs, channel.ClientPrefixes(target, isMultiPrefix)+channel.name)
  429. }
  430. return chstrs
  431. }
  432. func (client *Client) getWhoisOf(target *Client, rb *ResponseBuffer) {
  433. cnick := client.Nick()
  434. targetInfo := target.WhoWas()
  435. rb.Add(nil, client.server.name, RPL_WHOISUSER, cnick, targetInfo.nickname, targetInfo.username, targetInfo.hostname, "*", targetInfo.realname)
  436. tnick := targetInfo.nickname
  437. whoischannels := client.WhoisChannelsNames(target)
  438. if whoischannels != nil {
  439. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, cnick, tnick, strings.Join(whoischannels, " "))
  440. }
  441. tOper := target.Oper()
  442. if tOper != nil {
  443. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, cnick, tnick, tOper.WhoisLine)
  444. }
  445. if client.HasMode(modes.Operator) || client == target {
  446. rb.Add(nil, client.server.name, RPL_WHOISACTUALLY, cnick, tnick, fmt.Sprintf("%s@%s", target.username, utils.LookupHostname(target.IPString())), target.IPString(), client.t("Actual user@host, Actual IP"))
  447. }
  448. if target.HasMode(modes.TLS) {
  449. rb.Add(nil, client.server.name, RPL_WHOISSECURE, cnick, tnick, client.t("is using a secure connection"))
  450. }
  451. taccount := target.AccountName()
  452. if taccount != "*" {
  453. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, cnick, tnick, taccount, client.t("is logged in as"))
  454. }
  455. if target.HasMode(modes.Bot) {
  456. rb.Add(nil, client.server.name, RPL_WHOISBOT, cnick, tnick, ircfmt.Unescape(fmt.Sprintf(client.t("is a $bBot$b on %s"), client.server.Config().Network.Name)))
  457. }
  458. if 0 < len(target.languages) {
  459. params := []string{cnick, tnick}
  460. for _, str := range client.server.languages.Codes(target.languages) {
  461. params = append(params, str)
  462. }
  463. params = append(params, client.t("can speak these languages"))
  464. rb.Add(nil, client.server.name, RPL_WHOISLANGUAGE, params...)
  465. }
  466. if target.certfp != "" && (client.HasMode(modes.Operator) || client == target) {
  467. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, cnick, tnick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), target.certfp))
  468. }
  469. rb.Add(nil, client.server.name, RPL_WHOISIDLE, cnick, tnick, strconv.FormatUint(target.IdleSeconds(), 10), strconv.FormatInt(target.SignonTime(), 10), client.t("seconds idle, signon time"))
  470. }
  471. // rplWhoReply returns the WHO reply between one user and another channel/user.
  472. // <channel> <user> <host> <server> <nick> ( "H" / "G" ) ["*"] [ ( "@" / "+" ) ]
  473. // :<hopcount> <real name>
  474. func (target *Client) rplWhoReply(channel *Channel, client *Client, rb *ResponseBuffer) {
  475. channelName := "*"
  476. flags := ""
  477. if client.HasMode(modes.Away) {
  478. flags = "G"
  479. } else {
  480. flags = "H"
  481. }
  482. if client.HasMode(modes.Operator) {
  483. flags += "*"
  484. }
  485. if channel != nil {
  486. flags += channel.ClientPrefixes(client, target.capabilities.Has(caps.MultiPrefix))
  487. channelName = channel.name
  488. }
  489. 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())
  490. }
  491. func whoChannel(client *Client, channel *Channel, friends ClientSet, rb *ResponseBuffer) {
  492. for _, member := range channel.Members() {
  493. if !client.HasMode(modes.Invisible) || friends[client] {
  494. client.rplWhoReply(channel, member, rb)
  495. }
  496. }
  497. }
  498. // rehash reloads the config and applies the changes from the config file.
  499. func (server *Server) rehash() error {
  500. server.logger.Debug("rehash", "Starting rehash")
  501. // only let one REHASH go on at a time
  502. server.rehashMutex.Lock()
  503. defer server.rehashMutex.Unlock()
  504. server.logger.Debug("rehash", "Got rehash lock")
  505. config, err := LoadConfig(server.configFilename)
  506. if err != nil {
  507. return fmt.Errorf("Error loading config file config: %s", err.Error())
  508. }
  509. err = server.applyConfig(config, false)
  510. if err != nil {
  511. return fmt.Errorf("Error applying config changes: %s", err.Error())
  512. }
  513. return nil
  514. }
  515. func (server *Server) applyConfig(config *Config, initial bool) (err error) {
  516. if initial {
  517. server.ctime = time.Now()
  518. server.configFilename = config.Filename
  519. server.name = config.Server.Name
  520. server.nameCasefolded = config.Server.nameCasefolded
  521. } else {
  522. // enforce configs that can't be changed after launch:
  523. currentLimits := server.Limits()
  524. if currentLimits.LineLen.Tags != config.Limits.LineLen.Tags || currentLimits.LineLen.Rest != config.Limits.LineLen.Rest {
  525. return fmt.Errorf("Maximum line length (linelen) cannot be changed after launching the server, rehash aborted")
  526. } else if server.name != config.Server.Name {
  527. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  528. } else if server.config.Datastore.Path != config.Datastore.Path {
  529. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  530. }
  531. }
  532. // sanity checks complete, start modifying server state
  533. server.logger.Info("rehash", "Using config file", server.configFilename)
  534. oldConfig := server.Config()
  535. // first, reload config sections for functionality implemented in subpackages:
  536. err = server.connectionLimiter.ApplyConfig(config.Server.ConnectionLimiter)
  537. if err != nil {
  538. return err
  539. }
  540. err = server.connectionThrottler.ApplyConfig(config.Server.ConnectionThrottler)
  541. if err != nil {
  542. return err
  543. }
  544. // reload logging config
  545. wasLoggingRawIO := !initial && server.logger.IsLoggingRawIO()
  546. err = server.logger.ApplyConfig(config.Logging)
  547. if err != nil {
  548. return err
  549. }
  550. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  551. // notify existing clients if raw i/o logging was enabled by a rehash
  552. sendRawOutputNotice := !wasLoggingRawIO && nowLoggingRawIO
  553. // setup new and removed caps
  554. addedCaps := caps.NewSet()
  555. removedCaps := caps.NewSet()
  556. updatedCaps := caps.NewSet()
  557. // Translations
  558. currentLanguageValue, _ := CapValues.Get(caps.Languages)
  559. langCodes := []string{strconv.Itoa(len(config.Languages.Data) + 1), "en"}
  560. for _, info := range config.Languages.Data {
  561. if info.Incomplete {
  562. langCodes = append(langCodes, "~"+info.Code)
  563. } else {
  564. langCodes = append(langCodes, info.Code)
  565. }
  566. }
  567. newLanguageValue := strings.Join(langCodes, ",")
  568. server.logger.Debug("rehash", "Languages:", newLanguageValue)
  569. if currentLanguageValue != newLanguageValue {
  570. updatedCaps.Add(caps.Languages)
  571. CapValues.Set(caps.Languages, newLanguageValue)
  572. }
  573. lm := languages.NewManager(config.Languages.Default, config.Languages.Data)
  574. server.logger.Debug("rehash", "Regenerating HELP indexes for new languages")
  575. GenerateHelpIndices(lm)
  576. server.languages = lm
  577. // SASL
  578. authPreviouslyEnabled := oldConfig != nil && oldConfig.Accounts.AuthenticationEnabled
  579. if config.Accounts.AuthenticationEnabled && !authPreviouslyEnabled {
  580. // enabling SASL
  581. SupportedCapabilities.Enable(caps.SASL)
  582. CapValues.Set(caps.SASL, "PLAIN,EXTERNAL")
  583. addedCaps.Add(caps.SASL)
  584. } else if !config.Accounts.AuthenticationEnabled && authPreviouslyEnabled {
  585. // disabling SASL
  586. SupportedCapabilities.Disable(caps.SASL)
  587. removedCaps.Add(caps.SASL)
  588. }
  589. nickReservationPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.NickReservation.Enabled
  590. nickReservationNowEnabled := config.Accounts.NickReservation.Enabled
  591. if nickReservationPreviouslyDisabled && nickReservationNowEnabled {
  592. server.accounts.buildNickToAccountIndex()
  593. }
  594. hsPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.VHosts.Enabled
  595. hsNowEnabled := config.Accounts.VHosts.Enabled
  596. if hsPreviouslyDisabled && hsNowEnabled {
  597. server.accounts.initVHostRequestQueue()
  598. }
  599. // STS
  600. stsPreviouslyEnabled := oldConfig != nil && oldConfig.Server.STS.Enabled
  601. stsValue := config.Server.STS.Value()
  602. stsDisabledByRehash := false
  603. stsCurrentCapValue, _ := CapValues.Get(caps.STS)
  604. server.logger.Debug("rehash", "STS Vals", stsCurrentCapValue, stsValue, fmt.Sprintf("server[%v] config[%v]", stsPreviouslyEnabled, config.Server.STS.Enabled))
  605. if config.Server.STS.Enabled && !stsPreviouslyEnabled {
  606. // enabling STS
  607. SupportedCapabilities.Enable(caps.STS)
  608. addedCaps.Add(caps.STS)
  609. CapValues.Set(caps.STS, stsValue)
  610. } else if !config.Server.STS.Enabled && stsPreviouslyEnabled {
  611. // disabling STS
  612. SupportedCapabilities.Disable(caps.STS)
  613. removedCaps.Add(caps.STS)
  614. stsDisabledByRehash = true
  615. } else if config.Server.STS.Enabled && stsPreviouslyEnabled && stsValue != stsCurrentCapValue {
  616. // STS policy updated
  617. CapValues.Set(caps.STS, stsValue)
  618. updatedCaps.Add(caps.STS)
  619. }
  620. // resize history buffers as needed
  621. if oldConfig != nil {
  622. if oldConfig.History.ChannelLength != config.History.ChannelLength {
  623. for _, channel := range server.channels.Channels() {
  624. channel.history.Resize(config.History.ChannelLength)
  625. }
  626. }
  627. if oldConfig.History.ClientLength != config.History.ClientLength {
  628. for _, client := range server.clients.AllClients() {
  629. client.history.Resize(config.History.ClientLength)
  630. }
  631. }
  632. }
  633. // burst new and removed caps
  634. var capBurstClients ClientSet
  635. added := make(map[caps.Version]string)
  636. var removed string
  637. // updated caps get DEL'd and then NEW'd
  638. // so, we can just add updated ones to both removed and added lists here and they'll be correctly handled
  639. server.logger.Debug("rehash", "Updated Caps", updatedCaps.String(caps.Cap301, CapValues))
  640. addedCaps.Union(updatedCaps)
  641. removedCaps.Union(updatedCaps)
  642. if !addedCaps.Empty() || !removedCaps.Empty() {
  643. capBurstClients = server.clients.AllWithCaps(caps.CapNotify)
  644. added[caps.Cap301] = addedCaps.String(caps.Cap301, CapValues)
  645. added[caps.Cap302] = addedCaps.String(caps.Cap302, CapValues)
  646. // removed never has values, so we leave it as Cap301
  647. removed = removedCaps.String(caps.Cap301, CapValues)
  648. }
  649. for sClient := range capBurstClients {
  650. if stsDisabledByRehash {
  651. // remove STS policy
  652. //TODO(dan): this is an ugly hack. we can write this better.
  653. stsPolicy := "sts=duration=0"
  654. if !addedCaps.Empty() {
  655. added[caps.Cap302] = added[caps.Cap302] + " " + stsPolicy
  656. } else {
  657. addedCaps.Enable(caps.STS)
  658. added[caps.Cap302] = stsPolicy
  659. }
  660. }
  661. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  662. if !removedCaps.Empty() {
  663. sClient.Send(nil, server.name, "CAP", sClient.nick, "DEL", removed)
  664. }
  665. if !addedCaps.Empty() {
  666. sClient.Send(nil, server.name, "CAP", sClient.nick, "NEW", added[sClient.capVersion])
  667. }
  668. }
  669. server.loadMOTD(config.Server.MOTD, config.Server.MOTDFormatting)
  670. // save a pointer to the new config
  671. server.configurableStateMutex.Lock()
  672. server.config = config
  673. server.configurableStateMutex.Unlock()
  674. server.logger.Info("rehash", "Using datastore", config.Datastore.Path)
  675. if initial {
  676. if err := server.loadDatastore(config); err != nil {
  677. return err
  678. }
  679. }
  680. server.setupPprofListener(config)
  681. // set RPL_ISUPPORT
  682. var newISupportReplies [][]string
  683. oldISupportList := server.ISupport()
  684. err = server.setISupport()
  685. if err != nil {
  686. return err
  687. }
  688. if oldISupportList != nil {
  689. newISupportReplies = oldISupportList.GetDifference(server.ISupport())
  690. }
  691. // we are now open for business
  692. err = server.setupListeners(config)
  693. if !initial {
  694. // push new info to all of our clients
  695. for _, sClient := range server.clients.AllClients() {
  696. for _, tokenline := range newISupportReplies {
  697. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  698. }
  699. if sendRawOutputNotice {
  700. 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."))
  701. }
  702. }
  703. }
  704. return err
  705. }
  706. func (server *Server) setupPprofListener(config *Config) {
  707. pprofListener := ""
  708. if config.Debug.PprofListener != nil {
  709. pprofListener = *config.Debug.PprofListener
  710. }
  711. if server.pprofServer != nil {
  712. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  713. server.logger.Info("rehash", "Stopping pprof listener", server.pprofServer.Addr)
  714. server.pprofServer.Close()
  715. server.pprofServer = nil
  716. }
  717. }
  718. if pprofListener != "" && server.pprofServer == nil {
  719. ps := http.Server{
  720. Addr: pprofListener,
  721. }
  722. go func() {
  723. if err := ps.ListenAndServe(); err != nil {
  724. server.logger.Error("rehash", fmt.Sprintf("pprof listener failed: %v", err))
  725. }
  726. }()
  727. server.pprofServer = &ps
  728. server.logger.Info("rehash", "Started pprof listener", server.pprofServer.Addr)
  729. }
  730. }
  731. func (server *Server) loadMOTD(motdPath string, useFormatting bool) error {
  732. server.logger.Info("rehash", "Using MOTD", motdPath)
  733. motdLines := make([]string, 0)
  734. if motdPath != "" {
  735. file, err := os.Open(motdPath)
  736. if err == nil {
  737. defer file.Close()
  738. reader := bufio.NewReader(file)
  739. for {
  740. line, err := reader.ReadString('\n')
  741. if err != nil {
  742. break
  743. }
  744. line = strings.TrimRight(line, "\r\n")
  745. if useFormatting {
  746. line = ircfmt.Unescape(line)
  747. }
  748. // "- " is the required prefix for MOTD, we just add it here to make
  749. // bursting it out to clients easier
  750. line = fmt.Sprintf("- %s", line)
  751. motdLines = append(motdLines, line)
  752. }
  753. } else {
  754. return err
  755. }
  756. }
  757. server.configurableStateMutex.Lock()
  758. server.motdLines = motdLines
  759. server.configurableStateMutex.Unlock()
  760. return nil
  761. }
  762. func (server *Server) loadDatastore(config *Config) error {
  763. // open the datastore and load server state for which it (rather than config)
  764. // is the source of truth
  765. db, err := OpenDatabase(config)
  766. if err == nil {
  767. server.store = db
  768. } else {
  769. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  770. }
  771. // load *lines (from the datastores)
  772. server.logger.Debug("startup", "Loading D/Klines")
  773. server.loadDLines()
  774. server.loadKLines()
  775. server.channelRegistry = NewChannelRegistry(server)
  776. server.accounts = NewAccountManager(server)
  777. return nil
  778. }
  779. func (server *Server) setupListeners(config *Config) (err error) {
  780. logListener := func(addr string, tlsconfig *tls.Config) {
  781. server.logger.Info("listeners",
  782. fmt.Sprintf("now listening on %s, tls=%t.", addr, (tlsconfig != nil)),
  783. )
  784. }
  785. tlsListeners, err := config.TLSListeners()
  786. if err != nil {
  787. server.logger.Error("rehash", "failed to reload TLS certificates, aborting rehash", err.Error())
  788. return
  789. }
  790. // update or destroy all existing listeners
  791. for addr := range server.listeners {
  792. currentListener := server.listeners[addr]
  793. var stillConfigured bool
  794. for _, newaddr := range config.Server.Listen {
  795. if newaddr == addr {
  796. stillConfigured = true
  797. break
  798. }
  799. }
  800. // pass new config information to the listener, to be picked up after
  801. // its next Accept(). this is like sending over a buffered channel of
  802. // size 1, but where sending a second item overwrites the buffered item
  803. // instead of blocking.
  804. currentListener.configMutex.Lock()
  805. currentListener.shouldStop = !stillConfigured
  806. currentListener.tlsConfig = tlsListeners[addr]
  807. currentListener.configMutex.Unlock()
  808. if stillConfigured {
  809. logListener(addr, currentListener.tlsConfig)
  810. } else {
  811. // tell the listener it should stop by interrupting its Accept() call:
  812. currentListener.listener.Close()
  813. delete(server.listeners, addr)
  814. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  815. }
  816. }
  817. // create new listeners that were not previously configured
  818. for _, newaddr := range config.Server.Listen {
  819. _, exists := server.listeners[newaddr]
  820. if !exists {
  821. // make new listener
  822. tlsConfig := tlsListeners[newaddr]
  823. listener, listenerErr := server.createListener(newaddr, tlsConfig, config.Server.UnixBindMode)
  824. if listenerErr != nil {
  825. server.logger.Error("rehash", "couldn't listen on", newaddr, listenerErr.Error())
  826. err = listenerErr
  827. continue
  828. }
  829. server.listeners[newaddr] = listener
  830. logListener(newaddr, tlsConfig)
  831. }
  832. }
  833. if len(tlsListeners) == 0 {
  834. 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")
  835. }
  836. var usesStandardTLSPort bool
  837. for addr := range tlsListeners {
  838. if strings.HasSuffix(addr, ":6697") {
  839. usesStandardTLSPort = true
  840. break
  841. }
  842. }
  843. if 0 < len(tlsListeners) && !usesStandardTLSPort {
  844. 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")
  845. }
  846. return
  847. }
  848. // elistMatcher takes and matches ELIST conditions
  849. type elistMatcher struct {
  850. MinClientsActive bool
  851. MinClients int
  852. MaxClientsActive bool
  853. MaxClients int
  854. }
  855. // Matches checks whether the given channel matches our matches.
  856. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  857. if matcher.MinClientsActive {
  858. if len(channel.Members()) < matcher.MinClients {
  859. return false
  860. }
  861. }
  862. if matcher.MaxClientsActive {
  863. if len(channel.Members()) < len(channel.members) {
  864. return false
  865. }
  866. }
  867. return true
  868. }
  869. // RplList returns the RPL_LIST numeric for the given channel.
  870. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  871. // get the correct number of channel members
  872. var memberCount int
  873. if target.HasMode(modes.Operator) || channel.hasClient(target) {
  874. memberCount = len(channel.Members())
  875. } else {
  876. for _, member := range channel.Members() {
  877. if !member.HasMode(modes.Invisible) {
  878. memberCount++
  879. }
  880. }
  881. }
  882. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  883. }
  884. var (
  885. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  886. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  887. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  888. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  889. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  890. https://oragono.io/
  891. https://github.com/oragono/oragono
  892. https://crowdin.com/project/oragono
  893. `, "\n")
  894. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  895. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  896. `, "\n")
  897. infoString3 = strings.Split(` 3onyc
  898. Edmund Huber
  899. Euan Kemp (euank)
  900. Jeremy Latt
  901. Martin Lindhe (martinlindhe)
  902. Roberto Besser (besser)
  903. Robin Burchell (rburchell)
  904. Sean Enck (enckse)
  905. soul9
  906. Vegax
  907. `, "\n")
  908. )