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

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