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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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. //
  341. // server functionality
  342. //
  343. func (server *Server) tryRegister(c *Client) {
  344. resumed := false
  345. // try to complete registration, either via RESUME token or normally
  346. if c.resumeDetails != nil {
  347. if !c.tryResume() {
  348. return
  349. }
  350. resumed = true
  351. } else {
  352. if c.preregNick == "" || !c.HasUsername() || c.capState == caps.NegotiatingState {
  353. return
  354. }
  355. // client MUST send PASS if necessary, or authenticate with SASL if necessary,
  356. // before completing the other registration commands
  357. config := server.Config()
  358. if !c.isAuthorized(config) {
  359. c.Quit(c.t("Bad password"))
  360. c.destroy(false)
  361. return
  362. }
  363. rb := NewResponseBuffer(c)
  364. nickAssigned := performNickChange(server, c, c, c.preregNick, rb)
  365. rb.Send(true)
  366. if !nickAssigned {
  367. c.preregNick = ""
  368. return
  369. }
  370. // check KLINEs
  371. isBanned, info := server.klines.CheckMasks(c.AllNickmasks()...)
  372. if isBanned {
  373. c.Quit(info.BanMessage(c.t("You are banned from this server (%s)")))
  374. c.destroy(false)
  375. return
  376. }
  377. }
  378. // registration has succeeded:
  379. c.SetRegistered()
  380. // count new user in statistics
  381. server.stats.ChangeTotal(1)
  382. if !resumed {
  383. server.monitorManager.AlertAbout(c, true)
  384. }
  385. // continue registration
  386. server.logger.Info("localconnect", fmt.Sprintf("Client connected [%s] [u:%s] [r:%s]", c.nick, c.username, c.realname))
  387. 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))
  388. // send welcome text
  389. //NOTE(dan): we specifically use the NICK here instead of the nickmask
  390. // see http://modern.ircdocs.horse/#rplwelcome-001 for details on why we avoid using the nickmask
  391. c.Send(nil, server.name, RPL_WELCOME, c.nick, fmt.Sprintf(c.t("Welcome to the Internet Relay Network %s"), c.nick))
  392. 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))
  393. c.Send(nil, server.name, RPL_CREATED, c.nick, fmt.Sprintf(c.t("This server was created %s"), server.ctime.Format(time.RFC1123)))
  394. //TODO(dan): Look at adding last optional [<channel modes with a parameter>] parameter
  395. c.Send(nil, server.name, RPL_MYINFO, c.nick, server.name, Ver, supportedUserModesString, supportedChannelModesString)
  396. rb := NewResponseBuffer(c)
  397. c.RplISupport(rb)
  398. server.MOTD(c, rb)
  399. rb.Send(true)
  400. modestring := c.ModeString()
  401. if modestring != "+" {
  402. c.Send(nil, c.nickMaskString, RPL_UMODEIS, c.nick, c.ModeString())
  403. }
  404. if server.logger.IsLoggingRawIO() {
  405. 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."))
  406. }
  407. if resumed {
  408. c.tryResumeChannels()
  409. }
  410. }
  411. // t returns the translated version of the given string, based on the languages configured by the client.
  412. func (client *Client) t(originalString string) string {
  413. // TODO(slingamn) investigate a fast path for this, using an atomic load to see if translation is disabled
  414. languages := client.Languages()
  415. return client.server.Languages().Translate(languages, originalString)
  416. }
  417. // MOTD serves the Message of the Day.
  418. func (server *Server) MOTD(client *Client, rb *ResponseBuffer) {
  419. server.configurableStateMutex.RLock()
  420. motdLines := server.motdLines
  421. server.configurableStateMutex.RUnlock()
  422. if len(motdLines) < 1 {
  423. rb.Add(nil, server.name, ERR_NOMOTD, client.nick, client.t("MOTD File is missing"))
  424. return
  425. }
  426. rb.Add(nil, server.name, RPL_MOTDSTART, client.nick, fmt.Sprintf(client.t("- %s Message of the day - "), server.name))
  427. for _, line := range motdLines {
  428. rb.Add(nil, server.name, RPL_MOTD, client.nick, line)
  429. }
  430. rb.Add(nil, server.name, RPL_ENDOFMOTD, client.nick, client.t("End of MOTD command"))
  431. }
  432. // WhoisChannelsNames returns the common channel names between two users.
  433. func (client *Client) WhoisChannelsNames(target *Client) []string {
  434. isMultiPrefix := client.capabilities.Has(caps.MultiPrefix)
  435. var chstrs []string
  436. for _, channel := range target.Channels() {
  437. // channel is secret and the target can't see it
  438. if !client.HasMode(modes.Operator) {
  439. if (target.HasMode(modes.Invisible) || channel.flags.HasMode(modes.Secret)) && !channel.hasClient(client) {
  440. continue
  441. }
  442. }
  443. chstrs = append(chstrs, channel.ClientPrefixes(target, isMultiPrefix)+channel.name)
  444. }
  445. return chstrs
  446. }
  447. func (client *Client) getWhoisOf(target *Client, rb *ResponseBuffer) {
  448. cnick := client.Nick()
  449. targetInfo := target.Details()
  450. rb.Add(nil, client.server.name, RPL_WHOISUSER, cnick, targetInfo.nick, targetInfo.username, targetInfo.hostname, "*", targetInfo.realname)
  451. tnick := targetInfo.nick
  452. whoischannels := client.WhoisChannelsNames(target)
  453. if whoischannels != nil {
  454. rb.Add(nil, client.server.name, RPL_WHOISCHANNELS, cnick, tnick, strings.Join(whoischannels, " "))
  455. }
  456. tOper := target.Oper()
  457. if tOper != nil {
  458. rb.Add(nil, client.server.name, RPL_WHOISOPERATOR, cnick, tnick, tOper.WhoisLine)
  459. }
  460. if client.HasMode(modes.Operator) || client == target {
  461. 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"))
  462. }
  463. if target.HasMode(modes.TLS) {
  464. rb.Add(nil, client.server.name, RPL_WHOISSECURE, cnick, tnick, client.t("is using a secure connection"))
  465. }
  466. if targetInfo.accountName != "*" {
  467. rb.Add(nil, client.server.name, RPL_WHOISACCOUNT, cnick, tnick, targetInfo.accountName, client.t("is logged in as"))
  468. }
  469. if target.HasMode(modes.Bot) {
  470. 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)))
  471. }
  472. tLanguages := target.Languages()
  473. if 0 < len(tLanguages) {
  474. params := []string{cnick, tnick}
  475. for _, str := range client.server.Languages().Codes(tLanguages) {
  476. params = append(params, str)
  477. }
  478. params = append(params, client.t("can speak these languages"))
  479. rb.Add(nil, client.server.name, RPL_WHOISLANGUAGE, params...)
  480. }
  481. if target.certfp != "" && (client.HasMode(modes.Operator) || client == target) {
  482. rb.Add(nil, client.server.name, RPL_WHOISCERTFP, cnick, tnick, fmt.Sprintf(client.t("has client certificate fingerprint %s"), target.certfp))
  483. }
  484. 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"))
  485. }
  486. // rplWhoReply returns the WHO reply between one user and another channel/user.
  487. // <channel> <user> <host> <server> <nick> ( "H" / "G" ) ["*"] [ ( "@" / "+" ) ]
  488. // :<hopcount> <real name>
  489. func (target *Client) rplWhoReply(channel *Channel, client *Client, rb *ResponseBuffer) {
  490. channelName := "*"
  491. flags := ""
  492. if client.HasMode(modes.Away) {
  493. flags = "G"
  494. } else {
  495. flags = "H"
  496. }
  497. if client.HasMode(modes.Operator) {
  498. flags += "*"
  499. }
  500. if channel != nil {
  501. flags += channel.ClientPrefixes(client, target.capabilities.Has(caps.MultiPrefix))
  502. channelName = channel.name
  503. }
  504. 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())
  505. }
  506. func whoChannel(client *Client, channel *Channel, friends ClientSet, rb *ResponseBuffer) {
  507. for _, member := range channel.Members() {
  508. if !client.HasMode(modes.Invisible) || friends[client] {
  509. client.rplWhoReply(channel, member, rb)
  510. }
  511. }
  512. }
  513. // rehash reloads the config and applies the changes from the config file.
  514. func (server *Server) rehash() error {
  515. server.logger.Debug("server", "Starting rehash")
  516. // only let one REHASH go on at a time
  517. server.rehashMutex.Lock()
  518. defer server.rehashMutex.Unlock()
  519. server.logger.Debug("server", "Got rehash lock")
  520. config, err := LoadConfig(server.configFilename)
  521. if err != nil {
  522. return fmt.Errorf("Error loading config file config: %s", err.Error())
  523. }
  524. err = server.applyConfig(config, false)
  525. if err != nil {
  526. return fmt.Errorf("Error applying config changes: %s", err.Error())
  527. }
  528. return nil
  529. }
  530. func (server *Server) applyConfig(config *Config, initial bool) (err error) {
  531. if initial {
  532. server.ctime = time.Now()
  533. server.configFilename = config.Filename
  534. server.name = config.Server.Name
  535. server.nameCasefolded = config.Server.nameCasefolded
  536. } else {
  537. // enforce configs that can't be changed after launch:
  538. currentLimits := server.Limits()
  539. if currentLimits.LineLen.Rest != config.Limits.LineLen.Rest {
  540. return fmt.Errorf("Maximum line length (linelen) cannot be changed after launching the server, rehash aborted")
  541. } else if server.name != config.Server.Name {
  542. return fmt.Errorf("Server name cannot be changed after launching the server, rehash aborted")
  543. } else if server.config.Datastore.Path != config.Datastore.Path {
  544. return fmt.Errorf("Datastore path cannot be changed after launching the server, rehash aborted")
  545. }
  546. }
  547. // sanity checks complete, start modifying server state
  548. server.logger.Info("server", "Using config file", server.configFilename)
  549. oldConfig := server.Config()
  550. // first, reload config sections for functionality implemented in subpackages:
  551. err = server.connectionLimiter.ApplyConfig(config.Server.ConnectionLimiter)
  552. if err != nil {
  553. return err
  554. }
  555. err = server.connectionThrottler.ApplyConfig(config.Server.ConnectionThrottler)
  556. if err != nil {
  557. return err
  558. }
  559. tlConf := &config.Server.TorListeners
  560. server.torLimiter.Configure(tlConf.MaxConnections, tlConf.ThrottleDuration, tlConf.MaxConnectionsPerDuration)
  561. // reload logging config
  562. wasLoggingRawIO := !initial && server.logger.IsLoggingRawIO()
  563. err = server.logger.ApplyConfig(config.Logging)
  564. if err != nil {
  565. return err
  566. }
  567. nowLoggingRawIO := server.logger.IsLoggingRawIO()
  568. // notify existing clients if raw i/o logging was enabled by a rehash
  569. sendRawOutputNotice := !wasLoggingRawIO && nowLoggingRawIO
  570. // setup new and removed caps
  571. addedCaps := caps.NewSet()
  572. removedCaps := caps.NewSet()
  573. updatedCaps := caps.NewSet()
  574. // Translations
  575. server.logger.Debug("server", "Regenerating HELP indexes for new languages")
  576. server.helpIndexManager.GenerateIndices(config.languageManager)
  577. currentLanguageValue, _ := CapValues.Get(caps.Languages)
  578. newLanguageValue := config.languageManager.CapValue()
  579. if currentLanguageValue != newLanguageValue {
  580. updatedCaps.Add(caps.Languages)
  581. CapValues.Set(caps.Languages, newLanguageValue)
  582. }
  583. // SASL
  584. authPreviouslyEnabled := oldConfig != nil && oldConfig.Accounts.AuthenticationEnabled
  585. if config.Accounts.AuthenticationEnabled && !authPreviouslyEnabled {
  586. // enabling SASL
  587. SupportedCapabilities.Enable(caps.SASL)
  588. CapValues.Set(caps.SASL, "PLAIN,EXTERNAL")
  589. addedCaps.Add(caps.SASL)
  590. } else if !config.Accounts.AuthenticationEnabled && authPreviouslyEnabled {
  591. // disabling SASL
  592. SupportedCapabilities.Disable(caps.SASL)
  593. removedCaps.Add(caps.SASL)
  594. }
  595. nickReservationPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.NickReservation.Enabled
  596. nickReservationNowEnabled := config.Accounts.NickReservation.Enabled
  597. if nickReservationPreviouslyDisabled && nickReservationNowEnabled {
  598. server.accounts.buildNickToAccountIndex()
  599. }
  600. hsPreviouslyDisabled := oldConfig != nil && !oldConfig.Accounts.VHosts.Enabled
  601. hsNowEnabled := config.Accounts.VHosts.Enabled
  602. if hsPreviouslyDisabled && hsNowEnabled {
  603. server.accounts.initVHostRequestQueue()
  604. }
  605. // MaxLine
  606. if config.Limits.LineLen.Rest != 512 {
  607. SupportedCapabilities.Enable(caps.MaxLine)
  608. value := fmt.Sprintf("%d", config.Limits.LineLen.Rest)
  609. CapValues.Set(caps.MaxLine, value)
  610. }
  611. // STS
  612. stsPreviouslyEnabled := oldConfig != nil && oldConfig.Server.STS.Enabled
  613. stsValue := config.Server.STS.Value()
  614. stsDisabledByRehash := false
  615. stsCurrentCapValue, _ := CapValues.Get(caps.STS)
  616. server.logger.Debug("server", "STS Vals", stsCurrentCapValue, stsValue, fmt.Sprintf("server[%v] config[%v]", stsPreviouslyEnabled, config.Server.STS.Enabled))
  617. if config.Server.STS.Enabled && !stsPreviouslyEnabled {
  618. // enabling STS
  619. SupportedCapabilities.Enable(caps.STS)
  620. addedCaps.Add(caps.STS)
  621. CapValues.Set(caps.STS, stsValue)
  622. } else if !config.Server.STS.Enabled && stsPreviouslyEnabled {
  623. // disabling STS
  624. SupportedCapabilities.Disable(caps.STS)
  625. removedCaps.Add(caps.STS)
  626. stsDisabledByRehash = true
  627. } else if config.Server.STS.Enabled && stsPreviouslyEnabled && stsValue != stsCurrentCapValue {
  628. // STS policy updated
  629. CapValues.Set(caps.STS, stsValue)
  630. updatedCaps.Add(caps.STS)
  631. }
  632. // resize history buffers as needed
  633. if oldConfig != nil {
  634. if oldConfig.History.ChannelLength != config.History.ChannelLength {
  635. for _, channel := range server.channels.Channels() {
  636. channel.history.Resize(config.History.ChannelLength)
  637. }
  638. }
  639. if oldConfig.History.ClientLength != config.History.ClientLength {
  640. for _, client := range server.clients.AllClients() {
  641. client.history.Resize(config.History.ClientLength)
  642. }
  643. }
  644. }
  645. // burst new and removed caps
  646. var capBurstClients ClientSet
  647. added := make(map[caps.Version]string)
  648. var removed string
  649. // updated caps get DEL'd and then NEW'd
  650. // so, we can just add updated ones to both removed and added lists here and they'll be correctly handled
  651. server.logger.Debug("server", "Updated Caps", updatedCaps.String(caps.Cap301, CapValues))
  652. addedCaps.Union(updatedCaps)
  653. removedCaps.Union(updatedCaps)
  654. if !addedCaps.Empty() || !removedCaps.Empty() {
  655. capBurstClients = server.clients.AllWithCaps(caps.CapNotify)
  656. added[caps.Cap301] = addedCaps.String(caps.Cap301, CapValues)
  657. added[caps.Cap302] = addedCaps.String(caps.Cap302, CapValues)
  658. // removed never has values, so we leave it as Cap301
  659. removed = removedCaps.String(caps.Cap301, CapValues)
  660. }
  661. for sClient := range capBurstClients {
  662. if stsDisabledByRehash {
  663. // remove STS policy
  664. //TODO(dan): this is an ugly hack. we can write this better.
  665. stsPolicy := "sts=duration=0"
  666. if !addedCaps.Empty() {
  667. added[caps.Cap302] = added[caps.Cap302] + " " + stsPolicy
  668. } else {
  669. addedCaps.Enable(caps.STS)
  670. added[caps.Cap302] = stsPolicy
  671. }
  672. }
  673. // DEL caps and then send NEW ones so that updated caps get removed/added correctly
  674. if !removedCaps.Empty() {
  675. sClient.Send(nil, server.name, "CAP", sClient.nick, "DEL", removed)
  676. }
  677. if !addedCaps.Empty() {
  678. sClient.Send(nil, server.name, "CAP", sClient.nick, "NEW", added[sClient.capVersion])
  679. }
  680. }
  681. server.loadMOTD(config.Server.MOTD, config.Server.MOTDFormatting)
  682. // save a pointer to the new config
  683. server.configurableStateMutex.Lock()
  684. server.config = config
  685. server.configurableStateMutex.Unlock()
  686. server.logger.Info("server", "Using datastore", config.Datastore.Path)
  687. if initial {
  688. if err := server.loadDatastore(config); err != nil {
  689. return err
  690. }
  691. }
  692. server.setupPprofListener(config)
  693. // set RPL_ISUPPORT
  694. var newISupportReplies [][]string
  695. oldISupportList := server.ISupport()
  696. err = server.setISupport()
  697. if err != nil {
  698. return err
  699. }
  700. if oldISupportList != nil {
  701. newISupportReplies = oldISupportList.GetDifference(server.ISupport())
  702. }
  703. // we are now open for business
  704. err = server.setupListeners(config)
  705. if !initial {
  706. // push new info to all of our clients
  707. for _, sClient := range server.clients.AllClients() {
  708. for _, tokenline := range newISupportReplies {
  709. sClient.Send(nil, server.name, RPL_ISUPPORT, append([]string{sClient.nick}, tokenline...)...)
  710. }
  711. if sendRawOutputNotice {
  712. 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."))
  713. }
  714. if !oldConfig.Accounts.NickReservation.Enabled && config.Accounts.NickReservation.Enabled {
  715. sClient.nickTimer.Initialize(sClient)
  716. sClient.nickTimer.Touch()
  717. } else if oldConfig.Accounts.NickReservation.Enabled && !config.Accounts.NickReservation.Enabled {
  718. sClient.nickTimer.Stop()
  719. }
  720. }
  721. }
  722. return err
  723. }
  724. func (server *Server) setupPprofListener(config *Config) {
  725. pprofListener := ""
  726. if config.Debug.PprofListener != nil {
  727. pprofListener = *config.Debug.PprofListener
  728. }
  729. if server.pprofServer != nil {
  730. if pprofListener == "" || (pprofListener != server.pprofServer.Addr) {
  731. server.logger.Info("server", "Stopping pprof listener", server.pprofServer.Addr)
  732. server.pprofServer.Close()
  733. server.pprofServer = nil
  734. }
  735. }
  736. if pprofListener != "" && server.pprofServer == nil {
  737. ps := http.Server{
  738. Addr: pprofListener,
  739. }
  740. go func() {
  741. if err := ps.ListenAndServe(); err != nil {
  742. server.logger.Error("server", "pprof listener failed", err.Error())
  743. }
  744. }()
  745. server.pprofServer = &ps
  746. server.logger.Info("server", "Started pprof listener", server.pprofServer.Addr)
  747. }
  748. }
  749. func (server *Server) loadMOTD(motdPath string, useFormatting bool) error {
  750. server.logger.Info("server", "Using MOTD", motdPath)
  751. motdLines := make([]string, 0)
  752. if motdPath != "" {
  753. file, err := os.Open(motdPath)
  754. if err == nil {
  755. defer file.Close()
  756. reader := bufio.NewReader(file)
  757. for {
  758. line, err := reader.ReadString('\n')
  759. if err != nil {
  760. break
  761. }
  762. line = strings.TrimRight(line, "\r\n")
  763. if useFormatting {
  764. line = ircfmt.Unescape(line)
  765. }
  766. // "- " is the required prefix for MOTD, we just add it here to make
  767. // bursting it out to clients easier
  768. line = fmt.Sprintf("- %s", line)
  769. motdLines = append(motdLines, line)
  770. }
  771. } else {
  772. return err
  773. }
  774. }
  775. server.configurableStateMutex.Lock()
  776. server.motdLines = motdLines
  777. server.configurableStateMutex.Unlock()
  778. return nil
  779. }
  780. func (server *Server) loadDatastore(config *Config) error {
  781. // open the datastore and load server state for which it (rather than config)
  782. // is the source of truth
  783. _, err := os.Stat(config.Datastore.Path)
  784. if os.IsNotExist(err) {
  785. server.logger.Warning("server", "database does not exist, creating it", config.Datastore.Path)
  786. err = initializeDB(config.Datastore.Path)
  787. if err != nil {
  788. return err
  789. }
  790. }
  791. db, err := OpenDatabase(config)
  792. if err == nil {
  793. server.store = db
  794. } else {
  795. return fmt.Errorf("Failed to open datastore: %s", err.Error())
  796. }
  797. // load *lines (from the datastores)
  798. server.logger.Debug("server", "Loading D/Klines")
  799. server.loadDLines()
  800. server.loadKLines()
  801. server.channelRegistry = NewChannelRegistry(server)
  802. server.accounts = NewAccountManager(server)
  803. return nil
  804. }
  805. func (server *Server) setupListeners(config *Config) (err error) {
  806. logListener := func(addr string, tlsconfig *tls.Config, isTor bool) {
  807. server.logger.Info("listeners",
  808. fmt.Sprintf("now listening on %s, tls=%t, tor=%t.", addr, (tlsconfig != nil), isTor),
  809. )
  810. }
  811. tlsListeners, err := config.TLSListeners()
  812. if err != nil {
  813. server.logger.Error("server", "failed to reload TLS certificates, aborting rehash", err.Error())
  814. return
  815. }
  816. isTorListener := func(listener string) bool {
  817. for _, torListener := range config.Server.TorListeners.Listeners {
  818. if listener == torListener {
  819. return true
  820. }
  821. }
  822. return false
  823. }
  824. // update or destroy all existing listeners
  825. for addr := range server.listeners {
  826. currentListener := server.listeners[addr]
  827. var stillConfigured bool
  828. for _, newaddr := range config.Server.Listen {
  829. if newaddr == addr {
  830. stillConfigured = true
  831. break
  832. }
  833. }
  834. // pass new config information to the listener, to be picked up after
  835. // its next Accept(). this is like sending over a buffered channel of
  836. // size 1, but where sending a second item overwrites the buffered item
  837. // instead of blocking.
  838. tlsConfig := tlsListeners[addr]
  839. isTor := isTorListener(addr)
  840. currentListener.configMutex.Lock()
  841. currentListener.shouldStop = !stillConfigured
  842. currentListener.tlsConfig = tlsConfig
  843. currentListener.isTor = isTor
  844. currentListener.configMutex.Unlock()
  845. if stillConfigured {
  846. logListener(addr, tlsConfig, isTor)
  847. } else {
  848. // tell the listener it should stop by interrupting its Accept() call:
  849. currentListener.listener.Close()
  850. delete(server.listeners, addr)
  851. server.logger.Info("listeners", fmt.Sprintf("stopped listening on %s.", addr))
  852. }
  853. }
  854. // create new listeners that were not previously configured
  855. for _, newaddr := range config.Server.Listen {
  856. _, exists := server.listeners[newaddr]
  857. if !exists {
  858. // make new listener
  859. isTor := isTorListener(newaddr)
  860. tlsConfig := tlsListeners[newaddr]
  861. listener, listenerErr := server.createListener(newaddr, tlsConfig, isTor, config.Server.UnixBindMode)
  862. if listenerErr != nil {
  863. server.logger.Error("server", "couldn't listen on", newaddr, listenerErr.Error())
  864. err = listenerErr
  865. continue
  866. }
  867. server.listeners[newaddr] = listener
  868. logListener(newaddr, tlsConfig, isTor)
  869. }
  870. }
  871. if len(tlsListeners) == 0 {
  872. 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")
  873. }
  874. var usesStandardTLSPort bool
  875. for addr := range tlsListeners {
  876. if strings.HasSuffix(addr, ":6697") {
  877. usesStandardTLSPort = true
  878. break
  879. }
  880. }
  881. if 0 < len(tlsListeners) && !usesStandardTLSPort {
  882. 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")
  883. }
  884. return
  885. }
  886. // elistMatcher takes and matches ELIST conditions
  887. type elistMatcher struct {
  888. MinClientsActive bool
  889. MinClients int
  890. MaxClientsActive bool
  891. MaxClients int
  892. }
  893. // Matches checks whether the given channel matches our matches.
  894. func (matcher *elistMatcher) Matches(channel *Channel) bool {
  895. if matcher.MinClientsActive {
  896. if len(channel.Members()) < matcher.MinClients {
  897. return false
  898. }
  899. }
  900. if matcher.MaxClientsActive {
  901. if len(channel.Members()) < len(channel.members) {
  902. return false
  903. }
  904. }
  905. return true
  906. }
  907. // RplList returns the RPL_LIST numeric for the given channel.
  908. func (target *Client) RplList(channel *Channel, rb *ResponseBuffer) {
  909. // get the correct number of channel members
  910. var memberCount int
  911. if target.HasMode(modes.Operator) || channel.hasClient(target) {
  912. memberCount = len(channel.Members())
  913. } else {
  914. for _, member := range channel.Members() {
  915. if !member.HasMode(modes.Invisible) {
  916. memberCount++
  917. }
  918. }
  919. }
  920. rb.Add(nil, target.server.name, RPL_LIST, target.nick, channel.name, strconv.Itoa(memberCount), channel.topic)
  921. }
  922. var (
  923. infoString1 = strings.Split(` ▄▄▄ ▄▄▄· ▄▄ • ▐ ▄
  924. ▪ ▀▄ █·▐█ ▀█ ▐█ ▀ ▪▪ •█▌▐█▪
  925. ▄█▀▄ ▐▀▀▄ ▄█▀▀█ ▄█ ▀█▄ ▄█▀▄▪▐█▐▐▌ ▄█▀▄
  926. ▐█▌.▐▌▐█•█▌▐█ ▪▐▌▐█▄▪▐█▐█▌ ▐▌██▐█▌▐█▌.▐▌
  927. ▀█▄▀▪.▀ ▀ ▀ ▀ ·▀▀▀▀ ▀█▄▀ ▀▀ █▪ ▀█▄▀▪
  928. https://oragono.io/
  929. https://github.com/oragono/oragono
  930. https://crowdin.com/project/oragono
  931. `, "\n")
  932. infoString2 = strings.Split(` Daniel Oakley, DanielOaks, <daniel@danieloaks.net>
  933. Shivaram Lingamneni, slingamn, <slingamn@cs.stanford.edu>
  934. `, "\n")
  935. infoString3 = strings.Split(` 3onyc
  936. Edmund Huber
  937. Euan Kemp (euank)
  938. Jeremy Latt
  939. Martin Lindhe (martinlindhe)
  940. Roberto Besser (besser)
  941. Robin Burchell (rburchell)
  942. Sean Enck (enckse)
  943. soul9
  944. Vegax
  945. `, "\n")
  946. )