您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

server.go 34KB

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