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

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