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

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