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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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. if c.preregNick == "" || !c.HasUsername() || c.capState == caps.NegotiatingState {
  338. return
  339. }
  340. // client MUST send PASS (or AUTHENTICATE, if skip-server-password is set)
  341. // before completing the other registration commands
  342. if !c.Authorized() {
  343. c.Quit(c.t("Bad password"))
  344. c.destroy(false)
  345. return
  346. }
  347. rb := NewResponseBuffer(c)
  348. nickAssigned := performNickChange(server, c, c, c.preregNick, rb)
  349. rb.Send(true)
  350. if !nickAssigned {
  351. c.preregNick = ""
  352. return
  353. }
  354. // check KLINEs
  355. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  356. if isBanned {
  357. reason := info.Reason
  358. if info.Time != nil {
  359. reason += fmt.Sprintf(" [%s]", info.Time.Duration.String())
  360. }
  361. c.Quit(fmt.Sprintf(c.t("You are banned from this server (%s)"), reason))
  362. c.destroy(false)
  363. return
  364. }
  365. // count new user in statistics
  366. server.stats.ChangeTotal(1)
  367. // continue registration
  368. server.logger.Debug("localconnect", fmt.Sprintf("Client connected [%s] [u:%s] [r:%s]", c.nick, c.username, c.realname))
  369. 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))
  370. // "register"; this includes the initial phase of session resumption
  371. c.Register()
  372. // send welcome text
  373. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  374. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  375. c.Send(nil, server.name, RPL_WELCOME, c.nick, fmt.Sprintf(c.t("Welcome to the Internet Relay Network %s"), c.nick))
  376. 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))
  377. c.Send(nil, server.name, RPL_CREATED, c.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  378. //TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
  379. c.Send(nil, server.name, RPL_MYINFO, c.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
  380. rb = NewResponseBuffer(c)
  381. c.RplISupport(rb)
  382. server.MOTD(c, rb)
  383. rb.Send(true)
  384. modestring := c.ModeString()
  385. if modestring != "+" {
  386. c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
  387. }
  388. if server.logger.IsLoggingRawIO() {
  389. 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."))
  390. }
  391. // if resumed, send fake channel joins
  392. c.tryResumeChannels()
  393. }
  394. // t returns the translated version of the given string, based on the languages configured by the client.
  395. func (client *Client) t(originalString string) string {
  396. // grab this mutex to protect client.languages
  397. client.stateMutex.RLock()
  398. defer client.stateMutex.RUnlock()
  399. return client.server.languages.Translate(client.languages, originalString)
  400. }
  401. // MOTD serves the Message of the Day.
  402. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  403. server.configurableStateMutex.RLock()
  404. motdLines := server.motdLines
  405. server.configurableStateMutex.RUnlock()
  406. if len(motdLines) < 1 {
  407. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  408. return
  409. }
  410. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  411. for _, line := range motdLines {
  412. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  413. }
  414. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  415. }
  416. // WhoisChannelsNames returns the common channel names between two users.
  417. func (client *Client) WhoisChannelsNames(target *Client) []string {
  418. isMultiPrefix := client.capabilities.Has(caps.MultiPrefix)
  419. var chstrs []string
  420. for _, channel := range target.Channels() {
  421. // channel is secret and the target can't see it
  422. if !client.HasMode(modes.Operator) {
  423. if (target.HasMode(modes.Invisible) || channel.flags.HasMode(modes.Secret)) && !channel.hasClient(client) {
  424. continue
  425. }
  426. }
  427. chstrs = append(chstrs, channel.ClientPrefixes(target, isMultiPrefix)+channel.name)
  428. }
  429. return chstrs
  430. }
  431. func (client *Client) getWhoisOf(target *Client, rb *ResponseBuffer) {
  432. cnick := client.Nick()
  433. targetInfo := target.Details()
  434. rb.Add(nil, client.server.name, RPL_WHOISUSER, cnick, targetInfo.nick, targetInfo.username, targetInfo.hostname, "*", targetInfo.realname)
  435. tnick := targetInfo.nick
  436. whoischannels := client.WhoisChannelsNames(target)
  437. if whoischannels != nil {
  438. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, cnick, tnick, strings.Join(whoischannels, " "))
  439. }
  440. tOper := target.Oper()
  441. if tOper != nil {
  442. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, cnick, tnick, tOper.WhoisLine)
  443. }
  444. if client.HasMode(modes.Operator) || client == target {
  445. 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"))
  446. }
  447. if target.HasMode(modes.TLS) {
  448. rb.Add(nil, client.server.name, RPL_WHOISSECURE, cnick, tnick, client.t("is using a secure connection"))
  449. }
  450. if targetInfo.accountName != "*" {
  451. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, cnick, tnick, targetInfo.accountName, client.t("is logged in as"))
  452. }
  453. if target.HasMode(modes.Bot) {
  454. 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)))
  455. }
  456. if 0 < len(target.languages) {
  457. params := []string{cnick, tnick}
  458. for _, str := range client.server.languages.Codes(target.languages) {
  459. params = append(params, str)
  460. }
  461. params = append(params, client.t("can speak these languages"))
  462. rb.Add(nil, client.server.name, RPL_WHOISLANGUAGE, params...)
  463. }
  464. if target.certfp != "" && (client.HasMode(modes.Operator) || client == target) {
  465. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, cnick, tnick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), target.certfp))
  466. }
  467. 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"))
  468. }
  469. // rplWhoReply returns the WHO reply between one user and another channel/user.
  470. // <channel> <user> <host> <server> <nick> ( "H" / "G" ) ["*"] [ ( "@" / "+" ) ]
  471. // :<hopcount> <real name>
  472. func (target *Client) rplWhoReply(channel *Channel, client *Client, rb *ResponseBuffer) {
  473. channelName := "*"
  474. flags := ""
  475. if client.HasMode(modes.Away) {
  476. flags = "G"
  477. } else {
  478. flags = "H"
  479. }
  480. if client.HasMode(modes.Operator) {
  481. flags += "*"
  482. }
  483. if channel != nil {
  484. flags += channel.ClientPrefixes(client, target.capabilities.Has(caps.MultiPrefix))
  485. channelName = channel.name
  486. }
  487. 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())
  488. }
  489. func whoChannel(client *Client, channel *Channel, friends ClientSet, rb *ResponseBuffer) {
  490. for _, member := range channel.Members() {
  491. if !client.HasMode(modes.Invisible) || friends[client] {
  492. client.rplWhoReply(channel, member, rb)
  493. }
  494. }
  495. }
  496. // rehash reloads the config and applies the changes from the config file.
  497. func (server *Server) rehash() error {
  498. server.logger.Debug("rehash", "Starting rehash")
  499. // only let one REHASH go on at a time
  500. server.rehashMutex.Lock()
  501. defer server.rehashMutex.Unlock()
  502. server.logger.Debug("rehash", "Got rehash lock")
  503. config, err := LoadConfig(server.configFilename)
  504. if err != nil {
  505. return fmt.Errorf("Error loading config file config: %s", err.Error())
  506. }
  507. err = server.applyConfig(config, false)
  508. if err != nil {
  509. return fmt.Errorf("Error applying config changes: %s", err.Error())
  510. }
  511. return nil
  512. }
  513. func (server *Server) applyConfig(config *Config, initial bool) (err error) {
  514. if initial {
  515. server.ctime = time.Now()
  516. server.configFilename = config.Filename
  517. server.name = config.Server.Name
  518. server.nameCasefolded = config.Server.nameCasefolded
  519. } else {
  520. // enforce configs that can't be changed after launch:
  521. currentLimits := server.Limits()
  522. if currentLimits.LineLen.Tags != config.Limits.LineLen.Tags || currentLimits.LineLen.Rest != config.Limits.LineLen.Rest {
  523. return fmt.Errorf("Maximum line length (linelen) cannot be changed after launching the server, rehash aborted")
  524. } else if server.name != config.Server.Name {
  525. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  526. } else if server.config.Datastore.Path != config.Datastore.Path {
  527. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  528. }
  529. }
  530. // sanity checks complete, start modifying server state
  531. server.logger.Info("rehash", "Using config file", server.configFilename)
  532. oldConfig := server.Config()
  533. // first, reload config sections for functionality implemented in subpackages:
  534. err = server.connectionLimiter.ApplyConfig(config.Server.ConnectionLimiter)
  535. if err != nil {
  536. return err
  537. }
  538. err = server.connectionThrottler.ApplyConfig(config.Server.ConnectionThrottler)
  539. if err != nil {
  540. return err
  541. }
  542. // reload logging config
  543. wasLoggingRawIO := !initial && server.logger.IsLoggingRawIO()
  544. err = server.logger.ApplyConfig(config.Logging)
  545. if err != nil {
  546. return err
  547. }
  548. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  549. // notify existing clients if raw i/o logging was enabled by a rehash
  550. sendRawOutputNotice := !wasLoggingRawIO && nowLoggingRawIO
  551. // setup new and removed caps
  552. addedCaps := caps.NewSet()
  553. removedCaps := caps.NewSet()
  554. updatedCaps := caps.NewSet()
  555. // Translations
  556. currentLanguageValue, _ := CapValues.Get(caps.Languages)
  557. langCodes := []string{strconv.Itoa(len(config.Languages.Data) + 1), "en"}
  558. for _, info := range config.Languages.Data {
  559. if info.Incomplete {
  560. langCodes = append(langCodes, "~"+info.Code)
  561. } else {
  562. langCodes = append(langCodes, info.Code)
  563. }
  564. }
  565. newLanguageValue := strings.Join(langCodes, ",")
  566. server.logger.Debug("rehash", "Languages:", newLanguageValue)
  567. if currentLanguageValue != newLanguageValue {
  568. updatedCaps.Add(caps.Languages)
  569. CapValues.Set(caps.Languages, newLanguageValue)
  570. }
  571. lm := languages.NewManager(config.Languages.Default, config.Languages.Data)
  572. server.logger.Debug("rehash", "Regenerating HELP indexes for new languages")
  573. GenerateHelpIndices(lm)
  574. server.languages = lm
  575. // SASL
  576. authPreviouslyEnabled := oldConfig != nil && oldConfig.Accounts.AuthenticationEnabled
  577. if config.Accounts.AuthenticationEnabled && !authPreviouslyEnabled {
  578. // enabling SASL
  579. SupportedCapabilities.Enable(caps.SASL)
  580. CapValues.Set(caps.SASL, "PLAIN,EXTERNAL")
  581. addedCaps.Add(caps.SASL)
  582. } else if !config.Accounts.AuthenticationEnabled && authPreviouslyEnabled {
  583. // disabling SASL
  584. SupportedCapabilities.Disable(caps.SASL)
  585. removedCaps.Add(caps.SASL)
  586. }
  587. nickReservationPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.NickReservation.Enabled
  588. nickReservationNowEnabled := config.Accounts.NickReservation.Enabled
  589. if nickReservationPreviouslyDisabled && nickReservationNowEnabled {
  590. server.accounts.buildNickToAccountIndex()
  591. }
  592. hsPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.VHosts.Enabled
  593. hsNowEnabled := config.Accounts.VHosts.Enabled
  594. if hsPreviouslyDisabled && hsNowEnabled {
  595. server.accounts.initVHostRequestQueue()
  596. }
  597. // STS
  598. stsPreviouslyEnabled := oldConfig != nil && oldConfig.Server.STS.Enabled
  599. stsValue := config.Server.STS.Value()
  600. stsDisabledByRehash := false
  601. stsCurrentCapValue, _ := CapValues.Get(caps.STS)
  602. server.logger.Debug("rehash", "STS Vals", stsCurrentCapValue, stsValue, fmt.Sprintf("server[%v] config[%v]", stsPreviouslyEnabled, config.Server.STS.Enabled))
  603. if config.Server.STS.Enabled && !stsPreviouslyEnabled {
  604. // enabling STS
  605. SupportedCapabilities.Enable(caps.STS)
  606. addedCaps.Add(caps.STS)
  607. CapValues.Set(caps.STS, stsValue)
  608. } else if !config.Server.STS.Enabled && stsPreviouslyEnabled {
  609. // disabling STS
  610. SupportedCapabilities.Disable(caps.STS)
  611. removedCaps.Add(caps.STS)
  612. stsDisabledByRehash = true
  613. } else if config.Server.STS.Enabled && stsPreviouslyEnabled && stsValue != stsCurrentCapValue {
  614. // STS policy updated
  615. CapValues.Set(caps.STS, stsValue)
  616. updatedCaps.Add(caps.STS)
  617. }
  618. // resize history buffers as needed
  619. if oldConfig != nil {
  620. if oldConfig.History.ChannelLength != config.History.ChannelLength {
  621. for _, channel := range server.channels.Channels() {
  622. channel.history.Resize(config.History.ChannelLength)
  623. }
  624. }
  625. if oldConfig.History.ClientLength != config.History.ClientLength {
  626. for _, client := range server.clients.AllClients() {
  627. client.history.Resize(config.History.ClientLength)
  628. }
  629. }
  630. }
  631. // burst new and removed caps
  632. var capBurstClients ClientSet
  633. added := make(map[caps.Version]string)
  634. var removed string
  635. // updated caps get DEL'd and then NEW'd
  636. // so, we can just add updated ones to both removed and added lists here and they'll be correctly handled
  637. server.logger.Debug("rehash", "Updated Caps", updatedCaps.String(caps.Cap301, CapValues))
  638. addedCaps.Union(updatedCaps)
  639. removedCaps.Union(updatedCaps)
  640. if !addedCaps.Empty() || !removedCaps.Empty() {
  641. capBurstClients = server.clients.AllWithCaps(caps.CapNotify)
  642. added[caps.Cap301] = addedCaps.String(caps.Cap301, CapValues)
  643. added[caps.Cap302] = addedCaps.String(caps.Cap302, CapValues)
  644. // removed never has values, so we leave it as Cap301
  645. removed = removedCaps.String(caps.Cap301, CapValues)
  646. }
  647. for sClient := range capBurstClients {
  648. if stsDisabledByRehash {
  649. // remove STS policy
  650. //TODO(dan): this is an ugly hack. we can write this better.
  651. stsPolicy := "sts=duration=0"
  652. if !addedCaps.Empty() {
  653. added[caps.Cap302] = added[caps.Cap302] + " " + stsPolicy
  654. } else {
  655. addedCaps.Enable(caps.STS)
  656. added[caps.Cap302] = stsPolicy
  657. }
  658. }
  659. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  660. if !removedCaps.Empty() {
  661. sClient.Send(nil, server.name, "CAP", sClient.nick, "DEL", removed)
  662. }
  663. if !addedCaps.Empty() {
  664. sClient.Send(nil, server.name, "CAP", sClient.nick, "NEW", added[sClient.capVersion])
  665. }
  666. }
  667. server.loadMOTD(config.Server.MOTD, config.Server.MOTDFormatting)
  668. // save a pointer to the new config
  669. server.configurableStateMutex.Lock()
  670. server.config = config
  671. server.configurableStateMutex.Unlock()
  672. server.logger.Info("rehash", "Using datastore", config.Datastore.Path)
  673. if initial {
  674. if err := server.loadDatastore(config); err != nil {
  675. return err
  676. }
  677. }
  678. server.setupPprofListener(config)
  679. // set RPL_ISUPPORT
  680. var newISupportReplies [][]string
  681. oldISupportList := server.ISupport()
  682. err = server.setISupport()
  683. if err != nil {
  684. return err
  685. }
  686. if oldISupportList != nil {
  687. newISupportReplies = oldISupportList.GetDifference(server.ISupport())
  688. }
  689. // we are now open for business
  690. err = server.setupListeners(config)
  691. if !initial {
  692. // push new info to all of our clients
  693. for _, sClient := range server.clients.AllClients() {
  694. for _, tokenline := range newISupportReplies {
  695. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  696. }
  697. if sendRawOutputNotice {
  698. 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."))
  699. }
  700. }
  701. }
  702. return err
  703. }
  704. func (server *Server) setupPprofListener(config *Config) {
  705. pprofListener := ""
  706. if config.Debug.PprofListener != nil {
  707. pprofListener = *config.Debug.PprofListener
  708. }
  709. if server.pprofServer != nil {
  710. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  711. server.logger.Info("rehash", "Stopping pprof listener", server.pprofServer.Addr)
  712. server.pprofServer.Close()
  713. server.pprofServer = nil
  714. }
  715. }
  716. if pprofListener != "" && server.pprofServer == nil {
  717. ps := http.Server{
  718. Addr: pprofListener,
  719. }
  720. go func() {
  721. if err := ps.ListenAndServe(); err != nil {
  722. server.logger.Error("rehash", "pprof listener failed", err.Error())
  723. }
  724. }()
  725. server.pprofServer = &ps
  726. server.logger.Info("rehash", "Started pprof listener", server.pprofServer.Addr)
  727. }
  728. }
  729. func (server *Server) loadMOTD(motdPath string, useFormatting bool) error {
  730. server.logger.Info("rehash", "Using MOTD", motdPath)
  731. motdLines := make([]string, 0)
  732. if motdPath != "" {
  733. file, err := os.Open(motdPath)
  734. if err == nil {
  735. defer file.Close()
  736. reader := bufio.NewReader(file)
  737. for {
  738. line, err := reader.ReadString('\n')
  739. if err != nil {
  740. break
  741. }
  742. line = strings.TrimRight(line, "\r\n")
  743. if useFormatting {
  744. line = ircfmt.Unescape(line)
  745. }
  746. // "- " is the required prefix for MOTD, we just add it here to make
  747. // bursting it out to clients easier
  748. line = fmt.Sprintf("- %s", line)
  749. motdLines = append(motdLines, line)
  750. }
  751. } else {
  752. return err
  753. }
  754. }
  755. server.configurableStateMutex.Lock()
  756. server.motdLines = motdLines
  757. server.configurableStateMutex.Unlock()
  758. return nil
  759. }
  760. func (server *Server) loadDatastore(config *Config) error {
  761. // open the datastore and load server state for which it (rather than config)
  762. // is the source of truth
  763. _, err := os.Stat(config.Datastore.Path)
  764. if os.IsNotExist(err) {
  765. server.logger.Warning("rehash", "database does not exist, creating it", config.Datastore.Path)
  766. err = initializeDB(config.Datastore.Path)
  767. if err != nil {
  768. return err
  769. }
  770. }
  771. db, err := OpenDatabase(config)
  772. if err == nil {
  773. server.store = db
  774. } else {
  775. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  776. }
  777. // load *lines (from the datastores)
  778. server.logger.Debug("rehash", "Loading D/Klines")
  779. server.loadDLines()
  780. server.loadKLines()
  781. server.channelRegistry = NewChannelRegistry(server)
  782. server.accounts = NewAccountManager(server)
  783. return nil
  784. }
  785. func (server *Server) setupListeners(config *Config) (err error) {
  786. logListener := func(addr string, tlsconfig *tls.Config) {
  787. server.logger.Info("listeners",
  788. fmt.Sprintf("now listening on %s, tls=%t.", addr, (tlsconfig != nil)),
  789. )
  790. }
  791. tlsListeners, err := config.TLSListeners()
  792. if err != nil {
  793. server.logger.Error("rehash", "failed to reload TLS certificates, aborting rehash", err.Error())
  794. return
  795. }
  796. // update or destroy all existing listeners
  797. for addr := range server.listeners {
  798. currentListener := server.listeners[addr]
  799. var stillConfigured bool
  800. for _, newaddr := range config.Server.Listen {
  801. if newaddr == addr {
  802. stillConfigured = true
  803. break
  804. }
  805. }
  806. // pass new config information to the listener, to be picked up after
  807. // its next Accept(). this is like sending over a buffered channel of
  808. // size 1, but where sending a second item overwrites the buffered item
  809. // instead of blocking.
  810. currentListener.configMutex.Lock()
  811. currentListener.shouldStop = !stillConfigured
  812. currentListener.tlsConfig = tlsListeners[addr]
  813. currentListener.configMutex.Unlock()
  814. if stillConfigured {
  815. logListener(addr, currentListener.tlsConfig)
  816. } else {
  817. // tell the listener it should stop by interrupting its Accept() call:
  818. currentListener.listener.Close()
  819. delete(server.listeners, addr)
  820. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  821. }
  822. }
  823. // create new listeners that were not previously configured
  824. for _, newaddr := range config.Server.Listen {
  825. _, exists := server.listeners[newaddr]
  826. if !exists {
  827. // make new listener
  828. tlsConfig := tlsListeners[newaddr]
  829. listener, listenerErr := server.createListener(newaddr, tlsConfig, config.Server.UnixBindMode)
  830. if listenerErr != nil {
  831. server.logger.Error("rehash", "couldn't listen on", newaddr, listenerErr.Error())
  832. err = listenerErr
  833. continue
  834. }
  835. server.listeners[newaddr] = listener
  836. logListener(newaddr, tlsConfig)
  837. }
  838. }
  839. if len(tlsListeners) == 0 {
  840. server.logger.Warning("rehash", "You are not exposing an SSL/TLS listening port. You should expose at least one port (typically 6697) to accept TLS connections")
  841. }
  842. var usesStandardTLSPort bool
  843. for addr := range tlsListeners {
  844. if strings.HasSuffix(addr, ":6697") {
  845. usesStandardTLSPort = true
  846. break
  847. }
  848. }
  849. if 0 < len(tlsListeners) && !usesStandardTLSPort {
  850. server.logger.Warning("rehash", "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")
  851. }
  852. return
  853. }
  854. // elistMatcher takes and matches ELIST conditions
  855. type elistMatcher struct {
  856. MinClientsActive bool
  857. MinClients int
  858. MaxClientsActive bool
  859. MaxClients int
  860. }
  861. // Matches checks whether the given channel matches our matches.
  862. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  863. if matcher.MinClientsActive {
  864. if len(channel.Members()) < matcher.MinClients {
  865. return false
  866. }
  867. }
  868. if matcher.MaxClientsActive {
  869. if len(channel.Members()) < len(channel.members) {
  870. return false
  871. }
  872. }
  873. return true
  874. }
  875. // RplList returns the RPL_LIST numeric for the given channel.
  876. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  877. // get the correct number of channel members
  878. var memberCount int
  879. if target.HasMode(modes.Operator) || channel.hasClient(target) {
  880. memberCount = len(channel.Members())
  881. } else {
  882. for _, member := range channel.Members() {
  883. if !member.HasMode(modes.Invisible) {
  884. memberCount++
  885. }
  886. }
  887. }
  888. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  889. }
  890. var (
  891. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  892. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  893. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  894. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  895. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  896. https://oragono.io/
  897. https://github.com/oragono/oragono
  898. https://crowdin.com/project/oragono
  899. `, "\n")
  900. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  901. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  902. `, "\n")
  903. infoString3 = strings.Split(` 3onyc
  904. Edmund Huber
  905. Euan Kemp (euank)
  906. Jeremy Latt
  907. Martin Lindhe (martinlindhe)
  908. Roberto Besser (besser)
  909. Robin Burchell (rburchell)
  910. Sean Enck (enckse)
  911. soul9
  912. Vegax
  913. `, "\n")
  914. )