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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. "fmt"
  9. "net"
  10. "net/http"
  11. _ "net/http/pprof"
  12. "os"
  13. "os/signal"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "syscall"
  18. "time"
  19. "unsafe"
  20. "github.com/goshuirc/irc-go/ircfmt"
  21. "github.com/oragono/oragono/irc/caps"
  22. "github.com/oragono/oragono/irc/connection_limits"
  23. "github.com/oragono/oragono/irc/history"
  24. "github.com/oragono/oragono/irc/logger"
  25. "github.com/oragono/oragono/irc/modes"
  26. "github.com/oragono/oragono/irc/mysql"
  27. "github.com/oragono/oragono/irc/sno"
  28. "github.com/oragono/oragono/irc/utils"
  29. "github.com/tidwall/buntdb"
  30. )
  31. var (
  32. // common error line to sub values into
  33. errorMsg = "ERROR :%s\r\n"
  34. // supportedUserModesString acts as a cache for when we introduce users
  35. supportedUserModesString = modes.SupportedUserModes.String()
  36. // supportedChannelModesString acts as a cache for when we introduce users
  37. supportedChannelModesString = modes.SupportedChannelModes.String()
  38. // whitelist of caps to serve on the STS-only listener. In particular,
  39. // never advertise SASL, to discourage people from sending their passwords:
  40. stsOnlyCaps = caps.NewSet(caps.STS, caps.MessageTags, caps.ServerTime, caps.LabeledResponse, caps.Nope)
  41. // we only have standard channels for now. TODO: any updates to this
  42. // will also need to be reflected in CasefoldChannel
  43. chanTypes = "#"
  44. throttleMessage = "You have attempted to connect too many times within a short duration. Wait a while, and you will be able to connect."
  45. )
  46. // Server is the main Oragono server.
  47. type Server struct {
  48. accounts AccountManager
  49. channels ChannelManager
  50. channelRegistry ChannelRegistry
  51. clients ClientManager
  52. config unsafe.Pointer
  53. configFilename string
  54. connectionLimiter connection_limits.Limiter
  55. ctime time.Time
  56. dlines *DLineManager
  57. helpIndexManager HelpIndexManager
  58. klines *KLineManager
  59. listeners map[string]IRCListener
  60. logger *logger.Manager
  61. monitorManager MonitorManager
  62. name string
  63. nameCasefolded string
  64. rehashMutex sync.Mutex // tier 4
  65. rehashSignal chan os.Signal
  66. pprofServer *http.Server
  67. resumeManager ResumeManager
  68. signals chan os.Signal
  69. snomasks SnoManager
  70. store *buntdb.DB
  71. historyDB mysql.MySQL
  72. torLimiter connection_limits.TorLimiter
  73. whoWas WhoWasList
  74. stats Stats
  75. semaphores ServerSemaphores
  76. }
  77. var (
  78. // ServerExitSignals are the signals the server will exit on.
  79. ServerExitSignals = []os.Signal{
  80. syscall.SIGINT,
  81. syscall.SIGTERM,
  82. syscall.SIGQUIT,
  83. }
  84. )
  85. // NewServer returns a new Oragono server.
  86. func NewServer(config *Config, logger *logger.Manager) (*Server, error) {
  87. // initialize data structures
  88. server := &Server{
  89. ctime: time.Now().UTC(),
  90. listeners: make(map[string]IRCListener),
  91. logger: logger,
  92. rehashSignal: make(chan os.Signal, 1),
  93. signals: make(chan os.Signal, len(ServerExitSignals)),
  94. }
  95. server.clients.Initialize()
  96. server.semaphores.Initialize()
  97. server.resumeManager.Initialize(server)
  98. server.whoWas.Initialize(config.Limits.WhowasEntries)
  99. server.monitorManager.Initialize()
  100. server.snomasks.Initialize()
  101. if err := server.applyConfig(config); err != nil {
  102. return nil, err
  103. }
  104. // Attempt to clean up when receiving these signals.
  105. signal.Notify(server.signals, ServerExitSignals...)
  106. signal.Notify(server.rehashSignal, syscall.SIGHUP)
  107. return server, nil
  108. }
  109. // Shutdown shuts down the server.
  110. func (server *Server) Shutdown() {
  111. //TODO(dan): Make sure we disallow new nicks
  112. for _, client := range server.clients.AllClients() {
  113. client.Notice("Server is shutting down")
  114. }
  115. if err := server.store.Close(); err != nil {
  116. server.logger.Error("shutdown", fmt.Sprintln("Could not close datastore:", err))
  117. }
  118. server.historyDB.Close()
  119. }
  120. // Run starts the server.
  121. func (server *Server) Run() {
  122. // defer closing db/store
  123. defer server.store.Close()
  124. for {
  125. select {
  126. case <-server.signals:
  127. server.Shutdown()
  128. return
  129. case <-server.rehashSignal:
  130. go func() {
  131. server.logger.Info("server", "Rehashing due to SIGHUP")
  132. err := server.rehash()
  133. if err != nil {
  134. server.logger.Error("server", fmt.Sprintln("Failed to rehash:", err.Error()))
  135. }
  136. }()
  137. }
  138. }
  139. }
  140. func (server *Server) checkBans(ipaddr net.IP) (banned bool, message string) {
  141. // check DLINEs
  142. isBanned, info := server.dlines.CheckIP(ipaddr)
  143. if isBanned {
  144. server.logger.Info("connect-ip", fmt.Sprintf("Client from %v rejected by d-line", ipaddr))
  145. return true, info.BanMessage("You are banned from this server (%s)")
  146. }
  147. // check connection limits
  148. err := server.connectionLimiter.AddClient(ipaddr)
  149. if err == connection_limits.ErrLimitExceeded {
  150. // too many connections from one client, tell the client and close the connection
  151. server.logger.Info("connect-ip", fmt.Sprintf("Client from %v rejected for connection limit", ipaddr))
  152. return true, "Too many clients from your network"
  153. } else if err == connection_limits.ErrThrottleExceeded {
  154. duration := server.Config().Server.IPLimits.BanDuration
  155. if duration == 0 {
  156. return false, ""
  157. }
  158. server.dlines.AddIP(ipaddr, duration, throttleMessage, "Exceeded automated connection throttle", "auto.connection.throttler")
  159. // they're DLINE'd for 15 minutes or whatever, so we can reset the connection throttle now,
  160. // and once their temporary DLINE is finished they can fill up the throttler again
  161. server.connectionLimiter.ResetThrottle(ipaddr)
  162. // 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
  163. server.logger.Info(
  164. "connect-ip",
  165. fmt.Sprintf("Client from %v exceeded connection throttle, d-lining for %v", ipaddr, duration))
  166. return true, throttleMessage
  167. } else if err != nil {
  168. server.logger.Warning("internal", "unexpected ban result", err.Error())
  169. }
  170. return false, ""
  171. }
  172. func (server *Server) checkTorLimits() (banned bool, message string) {
  173. switch server.torLimiter.AddClient() {
  174. case connection_limits.ErrLimitExceeded:
  175. return true, "Too many clients from the Tor network"
  176. case connection_limits.ErrThrottleExceeded:
  177. return true, "Exceeded connection throttle for the Tor network"
  178. default:
  179. return false, ""
  180. }
  181. }
  182. //
  183. // server functionality
  184. //
  185. func (server *Server) tryRegister(c *Client, session *Session) (exiting bool) {
  186. // if the session just sent us a RESUME line, try to resume
  187. if session.resumeDetails != nil {
  188. session.tryResume()
  189. return // whether we succeeded or failed, either way `c` is not getting registered
  190. }
  191. // try to complete registration normally
  192. if c.preregNick == "" || !c.HasUsername() || session.capState == caps.NegotiatingState {
  193. return
  194. }
  195. if c.isSTSOnly {
  196. server.playRegistrationBurst(session)
  197. return true
  198. }
  199. // client MUST send PASS if necessary, or authenticate with SASL if necessary,
  200. // before completing the other registration commands
  201. authOutcome := c.isAuthorized(server.Config(), session)
  202. var quitMessage string
  203. switch authOutcome {
  204. case authFailPass:
  205. quitMessage = c.t("Password incorrect")
  206. c.Send(nil, server.name, ERR_PASSWDMISMATCH, "*", quitMessage)
  207. case authFailSaslRequired, authFailTorSaslRequired:
  208. quitMessage = c.t("You must log in with SASL to join this server")
  209. c.Send(nil, c.server.name, "FAIL", "*", "ACCOUNT_REQUIRED", quitMessage)
  210. }
  211. if authOutcome != authSuccess {
  212. c.Quit(quitMessage, nil)
  213. return true
  214. }
  215. // we have the final value of the IP address: do the hostname lookup
  216. // (nickmask will be set below once nickname assignment succeeds)
  217. if session.rawHostname == "" {
  218. session.client.lookupHostname(session, false)
  219. }
  220. rb := NewResponseBuffer(session)
  221. nickError := performNickChange(server, c, c, session, c.preregNick, rb)
  222. rb.Send(true)
  223. if nickError == errInsecureReattach {
  224. c.Quit(c.t("You can't mix secure and insecure connections to this account"), nil)
  225. return true
  226. } else if nickError != nil {
  227. c.preregNick = ""
  228. return false
  229. }
  230. if session.client != c {
  231. // reattached, bail out.
  232. // we'll play the reg burst later, on the new goroutine associated with
  233. // (thisSession, otherClient). This is to avoid having to transfer state
  234. // like nickname, hostname, etc. to show the correct values in the reg burst.
  235. return false
  236. }
  237. // check KLINEs
  238. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  239. if isBanned {
  240. c.Quit(info.BanMessage(c.t("You are banned from this server (%s)")), nil)
  241. return true
  242. }
  243. // registration has succeeded:
  244. c.SetRegistered()
  245. // count new user in statistics
  246. server.stats.Register()
  247. server.monitorManager.AlertAbout(c, true)
  248. server.playRegistrationBurst(session)
  249. return false
  250. }
  251. func (server *Server) playRegistrationBurst(session *Session) {
  252. c := session.client
  253. // continue registration
  254. d := c.Details()
  255. server.logger.Info("connect", fmt.Sprintf("Client connected [%s] [u:%s] [r:%s]", d.nick, d.username, d.realname))
  256. server.snomasks.Send(sno.LocalConnects, fmt.Sprintf("Client connected [%s] [u:%s] [h:%s] [ip:%s] [r:%s]", d.nick, d.username, session.rawHostname, session.IP().String(), d.realname))
  257. // send welcome text
  258. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  259. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  260. session.Send(nil, server.name, RPL_WELCOME, d.nick, fmt.Sprintf(c.t("Welcome to the Internet Relay Network %s"), d.nick))
  261. session.Send(nil, server.name, RPL_YOURHOST, d.nick, fmt.Sprintf(c.t("Your host is %[1]s, running version %[2]s"), server.name, Ver))
  262. session.Send(nil, server.name, RPL_CREATED, d.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  263. //TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
  264. session.Send(nil, server.name, RPL_MYINFO, d.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
  265. if c.isSTSOnly {
  266. for _, line := range server.Config().Server.STS.bannerLines {
  267. c.Notice(line)
  268. }
  269. return
  270. }
  271. rb := NewResponseBuffer(session)
  272. server.RplISupport(c, rb)
  273. server.Lusers(c, rb)
  274. server.MOTD(c, rb)
  275. rb.Send(true)
  276. modestring := c.ModeString()
  277. if modestring != "+" {
  278. session.Send(nil, server.name, RPL_UMODEIS, d.nick, modestring)
  279. }
  280. c.attemptAutoOper(session)
  281. if server.logger.IsLoggingRawIO() {
  282. session.Send(nil, c.server.name, "NOTICE", d.nick, 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."))
  283. }
  284. // #572: defer nick warnings to the end of the registration burst
  285. session.client.nickTimer.Touch(nil)
  286. }
  287. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  288. func (server *Server) RplISupport(client *Client, rb *ResponseBuffer) {
  289. translatedISupport := client.t("are supported by this server")
  290. nick := client.Nick()
  291. config := server.Config()
  292. for _, cachedTokenLine := range config.Server.isupport.CachedReply {
  293. length := len(cachedTokenLine) + 2
  294. tokenline := make([]string, length)
  295. tokenline[0] = nick
  296. copy(tokenline[1:], cachedTokenLine)
  297. tokenline[length-1] = translatedISupport
  298. rb.Add(nil, server.name, RPL_ISUPPORT, tokenline...)
  299. }
  300. }
  301. func (server *Server) Lusers(client *Client, rb *ResponseBuffer) {
  302. nick := client.Nick()
  303. stats := server.stats.GetValues()
  304. rb.Add(nil, server.name, RPL_LUSERCLIENT, nick, fmt.Sprintf(client.t("There are %[1]d users and %[2]d invisible on %[3]d server(s)"), stats.Total-stats.Invisible, stats.Invisible, 1))
  305. rb.Add(nil, server.name, RPL_LUSEROP, nick, strconv.Itoa(stats.Operators), client.t("IRC Operators online"))
  306. rb.Add(nil, server.name, RPL_LUSERUNKNOWN, nick, strconv.Itoa(stats.Unknown), client.t("unregistered connections"))
  307. rb.Add(nil, server.name, RPL_LUSERCHANNELS, nick, strconv.Itoa(server.channels.Len()), client.t("channels formed"))
  308. rb.Add(nil, server.name, RPL_LUSERME, nick, fmt.Sprintf(client.t("I have %[1]d clients and %[2]d servers"), stats.Total, 0))
  309. total := strconv.Itoa(stats.Total)
  310. max := strconv.Itoa(stats.Max)
  311. rb.Add(nil, server.name, RPL_LOCALUSERS, nick, total, max, fmt.Sprintf(client.t("Current local users %[1]s, max %[2]s"), total, max))
  312. rb.Add(nil, server.name, RPL_GLOBALUSERS, nick, total, max, fmt.Sprintf(client.t("Current global users %[1]s, max %[2]s"), total, max))
  313. }
  314. // MOTD serves the Message of the Day.
  315. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  316. motdLines := server.Config().Server.motdLines
  317. if len(motdLines) < 1 {
  318. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  319. return
  320. }
  321. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  322. for _, line := range motdLines {
  323. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  324. }
  325. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  326. }
  327. // WhoisChannelsNames returns the common channel names between two users.
  328. func (client *Client) WhoisChannelsNames(target *Client, multiPrefix bool) []string {
  329. var chstrs []string
  330. for _, channel := range target.Channels() {
  331. // channel is secret and the target can't see it
  332. if !client.HasMode(modes.Operator) {
  333. if (target.HasMode(modes.Invisible) || channel.flags.HasMode(modes.Secret)) && !channel.hasClient(client) {
  334. continue
  335. }
  336. }
  337. chstrs = append(chstrs, channel.ClientPrefixes(target, multiPrefix)+channel.name)
  338. }
  339. return chstrs
  340. }
  341. func (client *Client) getWhoisOf(target *Client, rb *ResponseBuffer) {
  342. cnick := client.Nick()
  343. targetInfo := target.Details()
  344. rb.Add(nil, client.server.name, RPL_WHOISUSER, cnick, targetInfo.nick, targetInfo.username, targetInfo.hostname, "*", targetInfo.realname)
  345. tnick := targetInfo.nick
  346. whoischannels := client.WhoisChannelsNames(target, rb.session.capabilities.Has(caps.MultiPrefix))
  347. if whoischannels != nil {
  348. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, cnick, tnick, strings.Join(whoischannels, " "))
  349. }
  350. tOper := target.Oper()
  351. if tOper != nil {
  352. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, cnick, tnick, tOper.WhoisLine)
  353. }
  354. if client.HasMode(modes.Operator) || client == target {
  355. rb.Add(nil, client.server.name, RPL_WHOISACTUALLY, cnick, tnick, fmt.Sprintf("%s@%s", targetInfo.username, target.RawHostname()), target.IPString(), client.t("Actual user@host, Actual IP"))
  356. }
  357. if target.HasMode(modes.TLS) {
  358. rb.Add(nil, client.server.name, RPL_WHOISSECURE, cnick, tnick, client.t("is using a secure connection"))
  359. }
  360. if targetInfo.accountName != "*" {
  361. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, cnick, tnick, targetInfo.accountName, client.t("is logged in as"))
  362. }
  363. if target.HasMode(modes.Bot) {
  364. 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)))
  365. }
  366. if client == target || client.HasMode(modes.Operator) {
  367. for _, session := range target.Sessions() {
  368. if session.certfp != "" {
  369. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, cnick, tnick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), session.certfp))
  370. }
  371. }
  372. }
  373. 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"))
  374. if target.Away() {
  375. rb.Add(nil, client.server.name, RPL_AWAY, cnick, tnick, target.AwayMessage())
  376. }
  377. }
  378. // rplWhoReply returns the WHO reply between one user and another channel/user.
  379. // <channel> <user> <host> <server> <nick> ( "H" / "G" ) ["*"] [ ( "@" / "+" ) ]
  380. // :<hopcount> <real name>
  381. func (client *Client) rplWhoReply(channel *Channel, target *Client, rb *ResponseBuffer) {
  382. channelName := "*"
  383. flags := ""
  384. if target.Away() {
  385. flags = "G"
  386. } else {
  387. flags = "H"
  388. }
  389. if target.HasMode(modes.Operator) {
  390. flags += "*"
  391. }
  392. if channel != nil {
  393. // TODO is this right?
  394. flags += channel.ClientPrefixes(target, rb.session.capabilities.Has(caps.MultiPrefix))
  395. channelName = channel.name
  396. }
  397. details := target.Details()
  398. // hardcode a hopcount of 0 for now
  399. rb.Add(nil, client.server.name, RPL_WHOREPLY, client.Nick(), channelName, details.username, details.hostname, client.server.name, details.nick, flags, "0 "+details.realname)
  400. }
  401. // rehash reloads the config and applies the changes from the config file.
  402. func (server *Server) rehash() error {
  403. server.logger.Debug("server", "Starting rehash")
  404. // only let one REHASH go on at a time
  405. server.rehashMutex.Lock()
  406. defer server.rehashMutex.Unlock()
  407. server.logger.Debug("server", "Got rehash lock")
  408. config, err := LoadConfig(server.configFilename)
  409. if err != nil {
  410. return fmt.Errorf("Error loading config file config: %s", err.Error())
  411. }
  412. err = server.applyConfig(config)
  413. if err != nil {
  414. return fmt.Errorf("Error applying config changes: %s", err.Error())
  415. }
  416. return nil
  417. }
  418. func (server *Server) applyConfig(config *Config) (err error) {
  419. oldConfig := server.Config()
  420. initial := oldConfig == nil
  421. if initial {
  422. server.configFilename = config.Filename
  423. server.name = config.Server.Name
  424. server.nameCasefolded = config.Server.nameCasefolded
  425. globalCasemappingSetting = config.Server.Casemapping
  426. } else {
  427. // enforce configs that can't be changed after launch:
  428. if server.name != config.Server.Name {
  429. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  430. } else if oldConfig.Datastore.Path != config.Datastore.Path {
  431. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  432. } else if globalCasemappingSetting != config.Server.Casemapping {
  433. return fmt.Errorf("Casemapping cannot be changed after launching the server, rehash aborted")
  434. } else if oldConfig.Accounts.Multiclient.AlwaysOn != config.Accounts.Multiclient.AlwaysOn {
  435. return fmt.Errorf("Default always-on setting cannot be changed after launching the server, rehash aborted")
  436. }
  437. }
  438. server.logger.Info("server", "Using config file", server.configFilename)
  439. // first, reload config sections for functionality implemented in subpackages:
  440. wasLoggingRawIO := !initial && server.logger.IsLoggingRawIO()
  441. err = server.logger.ApplyConfig(config.Logging)
  442. if err != nil {
  443. return err
  444. }
  445. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  446. // notify existing clients if raw i/o logging was enabled by a rehash
  447. sendRawOutputNotice := !wasLoggingRawIO && nowLoggingRawIO
  448. server.connectionLimiter.ApplyConfig(&config.Server.IPLimits)
  449. tlConf := &config.Server.TorListeners
  450. server.torLimiter.Configure(tlConf.MaxConnections, tlConf.ThrottleDuration, tlConf.MaxConnectionsPerDuration)
  451. // Translations
  452. server.logger.Debug("server", "Regenerating HELP indexes for new languages")
  453. server.helpIndexManager.GenerateIndices(config.languageManager)
  454. if oldConfig != nil {
  455. // if certain features were enabled by rehash, we need to load the corresponding data
  456. // from the store
  457. if !oldConfig.Accounts.NickReservation.Enabled {
  458. server.accounts.buildNickToAccountIndex(config)
  459. }
  460. if !oldConfig.Accounts.VHosts.Enabled {
  461. server.accounts.initVHostRequestQueue(config)
  462. }
  463. if !oldConfig.Channels.Registration.Enabled {
  464. server.channels.loadRegisteredChannels(config)
  465. }
  466. // resize history buffers as needed
  467. if oldConfig.History != config.History {
  468. for _, channel := range server.channels.Channels() {
  469. channel.resizeHistory(config)
  470. }
  471. for _, client := range server.clients.AllClients() {
  472. client.resizeHistory(config)
  473. }
  474. }
  475. if oldConfig.Accounts.Registration.Throttling != config.Accounts.Registration.Throttling {
  476. server.accounts.resetRegisterThrottle(config)
  477. }
  478. }
  479. server.logger.Info("server", "Using datastore", config.Datastore.Path)
  480. if initial {
  481. if err := server.loadDatastore(config); err != nil {
  482. return err
  483. }
  484. } else {
  485. if config.Datastore.MySQL.Enabled && config.Datastore.MySQL != oldConfig.Datastore.MySQL {
  486. server.historyDB.SetConfig(config.Datastore.MySQL)
  487. }
  488. }
  489. // now that the datastore is initialized, we can load the cloak secret from it
  490. // XXX this modifies config after the initial load, which is naughty,
  491. // but there's no data race because we haven't done SetConfig yet
  492. if config.Server.Cloaks.Enabled {
  493. config.Server.Cloaks.SetSecret(LoadCloakSecret(server.store))
  494. }
  495. // activate the new config
  496. server.SetConfig(config)
  497. // load [dk]-lines, registered users and channels, etc.
  498. if initial {
  499. if err := server.loadFromDatastore(config); err != nil {
  500. return err
  501. }
  502. }
  503. // burst new and removed caps
  504. addedCaps, removedCaps := config.Diff(oldConfig)
  505. var capBurstSessions []*Session
  506. added := make(map[caps.Version][]string)
  507. var removed []string
  508. if !addedCaps.Empty() || !removedCaps.Empty() {
  509. capBurstSessions = server.clients.AllWithCapsNotify()
  510. added[caps.Cap301] = addedCaps.Strings(caps.Cap301, config.Server.capValues, 0)
  511. added[caps.Cap302] = addedCaps.Strings(caps.Cap302, config.Server.capValues, 0)
  512. // removed never has values, so we leave it as Cap301
  513. removed = removedCaps.Strings(caps.Cap301, config.Server.capValues, 0)
  514. }
  515. for _, sSession := range capBurstSessions {
  516. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  517. if !removedCaps.Empty() {
  518. for _, capStr := range removed {
  519. sSession.Send(nil, server.name, "CAP", sSession.client.Nick(), "DEL", capStr)
  520. }
  521. }
  522. if !addedCaps.Empty() {
  523. for _, capStr := range added[sSession.capVersion] {
  524. sSession.Send(nil, server.name, "CAP", sSession.client.Nick(), "NEW", capStr)
  525. }
  526. }
  527. }
  528. server.setupPprofListener(config)
  529. // set RPL_ISUPPORT
  530. var newISupportReplies [][]string
  531. if oldConfig != nil {
  532. newISupportReplies = oldConfig.Server.isupport.GetDifference(&config.Server.isupport)
  533. }
  534. if len(config.Server.ProxyAllowedFrom) != 0 {
  535. server.logger.Info("server", "Proxied IPs will be accepted from", strings.Join(config.Server.ProxyAllowedFrom, ", "))
  536. }
  537. // we are now open for business
  538. err = server.setupListeners(config)
  539. if !initial {
  540. // push new info to all of our clients
  541. for _, sClient := range server.clients.AllClients() {
  542. for _, tokenline := range newISupportReplies {
  543. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  544. }
  545. if sendRawOutputNotice {
  546. 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."))
  547. }
  548. if !oldConfig.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.Enabled {
  549. sClient.nickTimer.Initialize(sClient)
  550. sClient.nickTimer.Touch(nil)
  551. } else if oldConfig.Accounts.NickReservation.Enabled && !config.Accounts.NickReservation.Enabled {
  552. sClient.nickTimer.Stop()
  553. }
  554. }
  555. }
  556. return err
  557. }
  558. func (server *Server) setupPprofListener(config *Config) {
  559. pprofListener := ""
  560. if config.Debug.PprofListener != nil {
  561. pprofListener = *config.Debug.PprofListener
  562. }
  563. if server.pprofServer != nil {
  564. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  565. server.logger.Info("server", "Stopping pprof listener", server.pprofServer.Addr)
  566. server.pprofServer.Close()
  567. server.pprofServer = nil
  568. }
  569. }
  570. if pprofListener != "" && server.pprofServer == nil {
  571. ps := http.Server{
  572. Addr: pprofListener,
  573. }
  574. go func() {
  575. if err := ps.ListenAndServe(); err != nil {
  576. server.logger.Error("server", "pprof listener failed", err.Error())
  577. }
  578. }()
  579. server.pprofServer = &ps
  580. server.logger.Info("server", "Started pprof listener", server.pprofServer.Addr)
  581. }
  582. }
  583. func (config *Config) loadMOTD() (err error) {
  584. if config.Server.MOTD != "" {
  585. file, err := os.Open(config.Server.MOTD)
  586. if err == nil {
  587. defer file.Close()
  588. reader := bufio.NewReader(file)
  589. for {
  590. line, err := reader.ReadString('\n')
  591. if err != nil {
  592. break
  593. }
  594. line = strings.TrimRight(line, "\r\n")
  595. if config.Server.MOTDFormatting {
  596. line = ircfmt.Unescape(line)
  597. }
  598. // "- " is the required prefix for MOTD, we just add it here to make
  599. // bursting it out to clients easier
  600. line = fmt.Sprintf("- %s", line)
  601. config.Server.motdLines = append(config.Server.motdLines, line)
  602. }
  603. }
  604. }
  605. return
  606. }
  607. func (server *Server) loadDatastore(config *Config) error {
  608. // open the datastore and load server state for which it (rather than config)
  609. // is the source of truth
  610. _, err := os.Stat(config.Datastore.Path)
  611. if os.IsNotExist(err) {
  612. server.logger.Warning("server", "database does not exist, creating it", config.Datastore.Path)
  613. err = initializeDB(config.Datastore.Path)
  614. if err != nil {
  615. return err
  616. }
  617. }
  618. db, err := OpenDatabase(config)
  619. if err == nil {
  620. server.store = db
  621. return nil
  622. } else {
  623. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  624. }
  625. }
  626. func (server *Server) loadFromDatastore(config *Config) (err error) {
  627. // load *lines (from the datastores)
  628. server.logger.Debug("server", "Loading D/Klines")
  629. server.loadDLines()
  630. server.loadKLines()
  631. server.channelRegistry.Initialize(server)
  632. server.channels.Initialize(server)
  633. server.accounts.Initialize(server)
  634. if config.Datastore.MySQL.Enabled {
  635. server.historyDB.Initialize(server.logger, config.Datastore.MySQL)
  636. err = server.historyDB.Open()
  637. if err != nil {
  638. server.logger.Error("internal", "could not connect to mysql", err.Error())
  639. return err
  640. }
  641. }
  642. return nil
  643. }
  644. func (server *Server) setupListeners(config *Config) (err error) {
  645. logListener := func(addr string, config utils.ListenerConfig) {
  646. server.logger.Info("listeners",
  647. fmt.Sprintf("now listening on %s, tls=%t, tlsproxy=%t, tor=%t, websocket=%t.", addr, (config.TLSConfig != nil), config.RequireProxy, config.Tor, config.WebSocket),
  648. )
  649. }
  650. // update or destroy all existing listeners
  651. for addr := range server.listeners {
  652. currentListener := server.listeners[addr]
  653. newConfig, stillConfigured := config.Server.trueListeners[addr]
  654. if stillConfigured {
  655. if reloadErr := currentListener.Reload(newConfig); reloadErr == nil {
  656. logListener(addr, newConfig)
  657. } else {
  658. // stop the listener; we will attempt to replace it below
  659. currentListener.Stop()
  660. delete(server.listeners, addr)
  661. }
  662. } else {
  663. currentListener.Stop()
  664. delete(server.listeners, addr)
  665. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  666. }
  667. }
  668. publicPlaintextListener := ""
  669. // create new listeners that were not previously configured,
  670. // or that couldn't be reloaded above:
  671. for newAddr, newConfig := range config.Server.trueListeners {
  672. if strings.HasPrefix(newAddr, ":") && !newConfig.Tor && !newConfig.STSOnly && newConfig.TLSConfig == nil {
  673. publicPlaintextListener = newAddr
  674. }
  675. _, exists := server.listeners[newAddr]
  676. if !exists {
  677. // make a new listener
  678. newListener, newErr := NewListener(server, newAddr, newConfig, config.Server.UnixBindMode)
  679. if newErr == nil {
  680. server.listeners[newAddr] = newListener
  681. logListener(newAddr, newConfig)
  682. } else {
  683. server.logger.Error("server", "couldn't listen on", newAddr, newErr.Error())
  684. err = newErr
  685. }
  686. }
  687. }
  688. if publicPlaintextListener != "" {
  689. server.logger.Warning("listeners", fmt.Sprintf("Your server is configured with public plaintext listener %s. Consider disabling it for improved security and privacy.", publicPlaintextListener))
  690. }
  691. return
  692. }
  693. // Gets the abstract sequence from which we're going to query history;
  694. // we may already know the channel we're querying, or we may have
  695. // to look it up via a string query. This function is responsible for
  696. // privilege checking.
  697. func (server *Server) GetHistorySequence(providedChannel *Channel, client *Client, query string) (channel *Channel, sequence history.Sequence, err error) {
  698. config := server.Config()
  699. // 4 cases: {persistent, ephemeral} x {normal, conversation}
  700. // with ephemeral history, target is implicit in the choice of `hist`,
  701. // and correspondent is "" if we're retrieving a channel or *, and the correspondent's name
  702. // if we're retrieving a DM conversation ("query buffer"). with persistent history,
  703. // target is always nonempty, and correspondent is either empty or nonempty as before.
  704. var status HistoryStatus
  705. var target, correspondent string
  706. var hist *history.Buffer
  707. channel = providedChannel
  708. if channel == nil {
  709. if strings.HasPrefix(query, "#") {
  710. channel = server.channels.Get(query)
  711. if channel == nil {
  712. return
  713. }
  714. }
  715. }
  716. if channel != nil {
  717. if !channel.hasClient(client) {
  718. err = errInsufficientPrivs
  719. return
  720. }
  721. status, target = channel.historyStatus(config)
  722. switch status {
  723. case HistoryEphemeral:
  724. hist = &channel.history
  725. case HistoryPersistent:
  726. // already set `target`
  727. default:
  728. return
  729. }
  730. } else {
  731. status, target = client.historyStatus(config)
  732. if query != "*" {
  733. correspondent, err = CasefoldName(query)
  734. if err != nil {
  735. return
  736. }
  737. }
  738. switch status {
  739. case HistoryEphemeral:
  740. hist = &client.history
  741. case HistoryPersistent:
  742. // already set `target`, and `correspondent` if necessary
  743. default:
  744. return
  745. }
  746. }
  747. var cutoff time.Time
  748. if config.History.Restrictions.ExpireTime != 0 {
  749. cutoff = time.Now().UTC().Add(-time.Duration(config.History.Restrictions.ExpireTime))
  750. }
  751. // #836: registration date cutoff is always enforced for DMs
  752. if config.History.Restrictions.EnforceRegistrationDate || channel == nil {
  753. regCutoff := client.historyCutoff()
  754. // take the later of the two cutoffs
  755. if regCutoff.After(cutoff) {
  756. cutoff = regCutoff
  757. }
  758. }
  759. // #836 again: grace period is never applied to DMs
  760. if !cutoff.IsZero() && channel != nil {
  761. cutoff = cutoff.Add(-time.Duration(config.History.Restrictions.GracePeriod))
  762. }
  763. if hist != nil {
  764. sequence = hist.MakeSequence(correspondent, cutoff)
  765. } else if target != "" {
  766. sequence = server.historyDB.MakeSequence(target, correspondent, cutoff)
  767. }
  768. return
  769. }
  770. // elistMatcher takes and matches ELIST conditions
  771. type elistMatcher struct {
  772. MinClientsActive bool
  773. MinClients int
  774. MaxClientsActive bool
  775. MaxClients int
  776. }
  777. // Matches checks whether the given channel matches our matches.
  778. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  779. if matcher.MinClientsActive {
  780. if len(channel.Members()) < matcher.MinClients {
  781. return false
  782. }
  783. }
  784. if matcher.MaxClientsActive {
  785. if len(channel.Members()) < len(channel.members) {
  786. return false
  787. }
  788. }
  789. return true
  790. }
  791. // RplList returns the RPL_LIST numeric for the given channel.
  792. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  793. // get the correct number of channel members
  794. var memberCount int
  795. if target.HasMode(modes.Operator) || channel.hasClient(target) {
  796. memberCount = len(channel.Members())
  797. } else {
  798. for _, member := range channel.Members() {
  799. if !member.HasMode(modes.Invisible) {
  800. memberCount++
  801. }
  802. }
  803. }
  804. // #704: some channels are kept around even with no members
  805. if memberCount != 0 {
  806. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  807. }
  808. }
  809. var (
  810. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  811. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  812. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  813. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  814. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  815. https://oragono.io/
  816. https://github.com/oragono/oragono
  817. https://crowdin.com/project/oragono
  818. `, "\n")
  819. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  820. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  821. `, "\n")
  822. infoString3 = strings.Split(` Jeremy Latt, jlatt
  823. Edmund Huber, edmund-huber
  824. `, "\n")
  825. )