Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

client.go 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  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. "fmt"
  8. "net"
  9. "runtime/debug"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/goshuirc/irc-go/ircfmt"
  16. "github.com/goshuirc/irc-go/ircmsg"
  17. ident "github.com/oragono/go-ident"
  18. "github.com/oragono/oragono/irc/caps"
  19. "github.com/oragono/oragono/irc/connection_limits"
  20. "github.com/oragono/oragono/irc/history"
  21. "github.com/oragono/oragono/irc/modes"
  22. "github.com/oragono/oragono/irc/sno"
  23. "github.com/oragono/oragono/irc/utils"
  24. )
  25. const (
  26. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  27. IdentTimeoutSeconds = 1.5
  28. IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
  29. )
  30. // ResumeDetails is a place to stash data at various stages of
  31. // the resume process: when handling the RESUME command itself,
  32. // when completing the registration, and when rejoining channels.
  33. type ResumeDetails struct {
  34. PresentedToken string
  35. Timestamp time.Time
  36. HistoryIncomplete bool
  37. }
  38. // Client is an IRC client.
  39. type Client struct {
  40. account string
  41. accountName string // display name of the account: uncasefolded, '*' if not logged in
  42. accountSettings AccountSettings
  43. atime time.Time
  44. away bool
  45. awayMessage string
  46. brbTimer BrbTimer
  47. certfp string
  48. channels ChannelSet
  49. ctime time.Time
  50. destroyed bool
  51. exitedSnomaskSent bool
  52. flags modes.ModeSet
  53. hostname string
  54. invitedTo map[string]bool
  55. isTor bool
  56. languages []string
  57. loginThrottle connection_limits.GenericThrottle
  58. nick string
  59. nickCasefolded string
  60. nickMaskCasefolded string
  61. nickMaskString string // cache for nickmask string since it's used with lots of replies
  62. nickTimer NickTimer
  63. oper *Oper
  64. preregNick string
  65. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  66. rawHostname string
  67. cloakedHostname string
  68. realname string
  69. realIP net.IP
  70. registered bool
  71. resumeID string
  72. saslInProgress bool
  73. saslMechanism string
  74. saslValue string
  75. sentPassCommand bool
  76. server *Server
  77. skeleton string
  78. sessions []*Session
  79. stateMutex sync.RWMutex // tier 1
  80. username string
  81. vhost string
  82. history history.Buffer
  83. }
  84. // Session is an individual client connection to the server (TCP connection
  85. // and associated per-connection data, such as capabilities). There is a
  86. // many-one relationship between sessions and clients.
  87. type Session struct {
  88. client *Client
  89. ctime time.Time
  90. atime time.Time
  91. socket *Socket
  92. realIP net.IP
  93. proxiedIP net.IP
  94. rawHostname string
  95. idletimer IdleTimer
  96. fakelag Fakelag
  97. destroyed uint32
  98. quitMessage string
  99. capabilities caps.Set
  100. maxlenRest uint32
  101. capState caps.State
  102. capVersion caps.Version
  103. registrationMessages int
  104. resumeID string
  105. resumeDetails *ResumeDetails
  106. zncPlaybackTimes *zncPlaybackTimes
  107. }
  108. // sets the session quit message, if there isn't one already
  109. func (sd *Session) SetQuitMessage(message string) (set bool) {
  110. if message == "" {
  111. message = "Connection closed"
  112. }
  113. if sd.quitMessage == "" {
  114. sd.quitMessage = message
  115. return true
  116. } else {
  117. return false
  118. }
  119. }
  120. // set the negotiated message length based on session capabilities
  121. func (session *Session) SetMaxlenRest() {
  122. maxlenRest := 512
  123. if session.capabilities.Has(caps.MaxLine) {
  124. maxlenRest = session.client.server.Config().Limits.LineLen.Rest
  125. }
  126. atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
  127. }
  128. // allow the negotiated message length limit to be read without locks; this is a convenience
  129. // so that Session.SendRawMessage doesn't have to acquire any Client locks
  130. func (session *Session) MaxlenRest() int {
  131. return int(atomic.LoadUint32(&session.maxlenRest))
  132. }
  133. // returns whether the session was actively destroyed (for example, by ping
  134. // timeout or NS GHOST).
  135. // avoids a race condition between asynchronous idle-timing-out of sessions,
  136. // and a condition that allows implicit BRB on connection errors (since
  137. // destroy()'s socket.Close() appears to socket.Read() as a connection error)
  138. func (session *Session) Destroyed() bool {
  139. return atomic.LoadUint32(&session.destroyed) == 1
  140. }
  141. // sets the timed-out flag
  142. func (session *Session) SetDestroyed() {
  143. atomic.StoreUint32(&session.destroyed, 1)
  144. }
  145. // returns whether the client supports a smart history replay cap,
  146. // and therefore autoreplay-on-join and similar should be suppressed
  147. func (session *Session) HasHistoryCaps() bool {
  148. // TODO the chathistory cap will go here as well
  149. return session.capabilities.Has(caps.ZNCPlayback)
  150. }
  151. // WhoWas is the subset of client details needed to answer a WHOWAS query
  152. type WhoWas struct {
  153. nick string
  154. nickCasefolded string
  155. username string
  156. hostname string
  157. realname string
  158. }
  159. // ClientDetails is a standard set of details about a client
  160. type ClientDetails struct {
  161. WhoWas
  162. nickMask string
  163. nickMaskCasefolded string
  164. account string
  165. accountName string
  166. }
  167. // RunClient sets up a new client and runs its goroutine.
  168. func (server *Server) RunClient(conn clientConn) {
  169. var isBanned bool
  170. var banMsg string
  171. var realIP net.IP
  172. if conn.Config.IsTor {
  173. realIP = utils.IPv4LoopbackAddress
  174. isBanned, banMsg = server.checkTorLimits()
  175. } else {
  176. realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
  177. isBanned, banMsg = server.checkBans(realIP)
  178. }
  179. if isBanned {
  180. // this might not show up properly on some clients,
  181. // but our objective here is just to close the connection out before it has a load impact on us
  182. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  183. conn.Conn.Close()
  184. return
  185. }
  186. server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
  187. now := time.Now().UTC()
  188. config := server.Config()
  189. fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
  190. // give them 1k of grace over the limit:
  191. socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
  192. client := &Client{
  193. atime: now,
  194. channels: make(ChannelSet),
  195. ctime: now,
  196. isTor: conn.Config.IsTor,
  197. languages: server.Languages().Default(),
  198. loginThrottle: connection_limits.GenericThrottle{
  199. Duration: config.Accounts.LoginThrottling.Duration,
  200. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  201. },
  202. server: server,
  203. accountName: "*",
  204. nick: "*", // * is used until actual nick is given
  205. nickCasefolded: "*",
  206. nickMaskString: "*", // * is used until actual nick is given
  207. }
  208. client.history.Initialize(config.History.ClientLength, config.History.AutoresizeWindow)
  209. client.brbTimer.Initialize(client)
  210. session := &Session{
  211. client: client,
  212. socket: socket,
  213. capVersion: caps.Cap301,
  214. capState: caps.NoneState,
  215. ctime: now,
  216. atime: now,
  217. realIP: realIP,
  218. }
  219. session.SetMaxlenRest()
  220. client.sessions = []*Session{session}
  221. if conn.Config.TLSConfig != nil {
  222. client.SetMode(modes.TLS, true)
  223. // error is not useful to us here anyways so we can ignore it
  224. client.certfp, _ = socket.CertFP()
  225. }
  226. if conn.Config.IsTor {
  227. client.SetMode(modes.TLS, true)
  228. // cover up details of the tor proxying infrastructure (not a user privacy concern,
  229. // but a hardening measure):
  230. session.proxiedIP = utils.IPv4LoopbackAddress
  231. session.rawHostname = config.Server.TorListeners.Vhost
  232. } else {
  233. // set the hostname for this client (may be overridden later by PROXY or WEBIRC)
  234. session.rawHostname = utils.LookupHostname(session.realIP.String())
  235. client.cloakedHostname = config.Server.Cloaks.ComputeCloak(session.realIP)
  236. remoteAddr := conn.Conn.RemoteAddr()
  237. if utils.AddrIsLocal(remoteAddr) {
  238. // treat local connections as secure (may be overridden later by WEBIRC)
  239. client.SetMode(modes.TLS, true)
  240. }
  241. if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
  242. client.doIdentLookup(conn.Conn)
  243. }
  244. }
  245. client.realIP = session.realIP
  246. client.rawHostname = session.rawHostname
  247. client.proxiedIP = session.proxiedIP
  248. server.stats.Add()
  249. client.run(session)
  250. }
  251. func (client *Client) doIdentLookup(conn net.Conn) {
  252. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  253. if err != nil {
  254. client.server.logger.Error("internal", "bad server address", err.Error())
  255. return
  256. }
  257. serverPort, _ := strconv.Atoi(serverPortString)
  258. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  259. if err != nil {
  260. client.server.logger.Error("internal", "bad client address", err.Error())
  261. return
  262. }
  263. clientPort, _ := strconv.Atoi(clientPortString)
  264. client.Notice(client.t("*** Looking up your username"))
  265. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  266. if err == nil {
  267. err := client.SetNames(resp.Identifier, "", true)
  268. if err == nil {
  269. client.Notice(client.t("*** Found your username"))
  270. // we don't need to updateNickMask here since nickMask is not used for anything yet
  271. } else {
  272. client.Notice(client.t("*** Got a malformed username, ignoring"))
  273. }
  274. } else {
  275. client.Notice(client.t("*** Could not find your username"))
  276. }
  277. }
  278. type AuthOutcome uint
  279. const (
  280. authSuccess AuthOutcome = iota
  281. authFailPass
  282. authFailTorSaslRequired
  283. authFailSaslRequired
  284. )
  285. func (client *Client) isAuthorized(config *Config) AuthOutcome {
  286. saslSent := client.account != ""
  287. // PASS requirement
  288. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  289. return authFailPass
  290. }
  291. // Tor connections may be required to authenticate with SASL
  292. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  293. return authFailTorSaslRequired
  294. }
  295. // finally, enforce require-sasl
  296. if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets) {
  297. return authFailSaslRequired
  298. }
  299. return authSuccess
  300. }
  301. func (session *Session) resetFakelag() {
  302. var flc FakelagConfig = session.client.server.Config().Fakelag
  303. flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
  304. session.fakelag.Initialize(flc)
  305. }
  306. // IP returns the IP address of this client.
  307. func (client *Client) IP() net.IP {
  308. client.stateMutex.RLock()
  309. defer client.stateMutex.RUnlock()
  310. if client.proxiedIP != nil {
  311. return client.proxiedIP
  312. }
  313. return client.realIP
  314. }
  315. // IPString returns the IP address of this client as a string.
  316. func (client *Client) IPString() string {
  317. ip := client.IP().String()
  318. if 0 < len(ip) && ip[0] == ':' {
  319. ip = "0" + ip
  320. }
  321. return ip
  322. }
  323. // t returns the translated version of the given string, based on the languages configured by the client.
  324. func (client *Client) t(originalString string) string {
  325. languageManager := client.server.Config().languageManager
  326. if !languageManager.Enabled() {
  327. return originalString
  328. }
  329. return languageManager.Translate(client.Languages(), originalString)
  330. }
  331. //
  332. // command goroutine
  333. //
  334. func (client *Client) run(session *Session) {
  335. defer func() {
  336. if r := recover(); r != nil {
  337. client.server.logger.Error("internal",
  338. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  339. if client.server.Config().Debug.recoverFromErrors {
  340. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  341. } else {
  342. panic(r)
  343. }
  344. }
  345. // ensure client connection gets closed
  346. client.destroy(session)
  347. }()
  348. session.idletimer.Initialize(session)
  349. session.resetFakelag()
  350. isReattach := client.Registered()
  351. if isReattach {
  352. if session.resumeDetails != nil {
  353. session.playResume()
  354. session.resumeDetails = nil
  355. client.brbTimer.Disable()
  356. client.SetAway(false, "") // clear BRB message if any
  357. } else {
  358. client.playReattachMessages(session)
  359. }
  360. } else {
  361. // don't reset the nick timer during a reattach
  362. client.nickTimer.Initialize(client)
  363. }
  364. firstLine := !isReattach
  365. for {
  366. maxlenRest := session.MaxlenRest()
  367. line, err := session.socket.Read()
  368. if err != nil {
  369. quitMessage := "connection closed"
  370. if err == errReadQ {
  371. quitMessage = "readQ exceeded"
  372. }
  373. client.Quit(quitMessage, session)
  374. // since the client did not actually send us a QUIT,
  375. // give them a chance to resume if applicable:
  376. if !session.Destroyed() {
  377. client.brbTimer.Enable()
  378. }
  379. break
  380. }
  381. if client.server.logger.IsLoggingRawIO() {
  382. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  383. }
  384. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  385. if firstLine {
  386. firstLine = false
  387. if strings.HasPrefix(line, "PROXY") {
  388. err = handleProxyCommand(client.server, client, session, line)
  389. if err != nil {
  390. break
  391. } else {
  392. continue
  393. }
  394. }
  395. }
  396. if client.registered {
  397. session.fakelag.Touch()
  398. } else {
  399. // DoS hardening, #505
  400. session.registrationMessages++
  401. if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
  402. client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
  403. break
  404. }
  405. }
  406. msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
  407. if err == ircmsg.ErrorLineIsEmpty {
  408. continue
  409. } else if err == ircmsg.ErrorLineTooLong {
  410. session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
  411. continue
  412. } else if err != nil {
  413. client.Quit(client.t("Received malformed line"), session)
  414. break
  415. }
  416. cmd, exists := Commands[msg.Command]
  417. if !exists {
  418. if len(msg.Command) > 0 {
  419. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
  420. } else {
  421. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
  422. }
  423. continue
  424. }
  425. isExiting := cmd.Run(client.server, client, session, msg)
  426. if isExiting {
  427. break
  428. } else if session.client != client {
  429. // bouncer reattach
  430. go session.client.run(session)
  431. break
  432. }
  433. }
  434. }
  435. func (client *Client) playReattachMessages(session *Session) {
  436. client.server.playRegistrationBurst(session)
  437. for _, channel := range session.client.Channels() {
  438. channel.playJoinForSession(session)
  439. // clients should receive autoreplay-on-join lines, if applicable;
  440. // if they negotiated znc.in/playback or chathistory, they will receive nothing,
  441. // because those caps disable autoreplay-on-join and they haven't sent the relevant
  442. // *playback PRIVMSG or CHATHISTORY command yet
  443. rb := NewResponseBuffer(session)
  444. channel.autoReplayHistory(client, rb, "")
  445. rb.Send(true)
  446. }
  447. }
  448. //
  449. // idle, quit, timers and timeouts
  450. //
  451. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  452. func (client *Client) Active(session *Session) {
  453. now := time.Now().UTC()
  454. client.stateMutex.Lock()
  455. defer client.stateMutex.Unlock()
  456. session.atime = now
  457. client.atime = now
  458. }
  459. // Ping sends the client a PING message.
  460. func (session *Session) Ping() {
  461. session.Send(nil, "", "PING", session.client.Nick())
  462. }
  463. // tryResume tries to resume if the client asked us to.
  464. func (session *Session) tryResume() (success bool) {
  465. var oldResumeID string
  466. defer func() {
  467. if success {
  468. // "On a successful request, the server [...] terminates the old client's connection"
  469. oldSession := session.client.GetSessionByResumeID(oldResumeID)
  470. if oldSession != nil {
  471. session.client.destroy(oldSession)
  472. }
  473. } else {
  474. session.resumeDetails = nil
  475. }
  476. }()
  477. client := session.client
  478. server := client.server
  479. config := server.Config()
  480. oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
  481. if oldClient == nil {
  482. session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
  483. return
  484. }
  485. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  486. if !resumeAllowed {
  487. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
  488. return
  489. }
  490. if oldClient.isTor != client.isTor {
  491. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  492. return
  493. }
  494. err := server.clients.Resume(oldClient, session)
  495. if err != nil {
  496. session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
  497. return
  498. }
  499. success = true
  500. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
  501. return
  502. }
  503. // playResume is called from the session's fresh goroutine after a resume;
  504. // it sends notifications to friends, then plays the registration burst and replays
  505. // stored history to the session
  506. func (session *Session) playResume() {
  507. client := session.client
  508. server := client.server
  509. friends := make(ClientSet)
  510. oldestLostMessage := time.Now().UTC()
  511. // work out how much time, if any, is not covered by history buffers
  512. for _, channel := range client.Channels() {
  513. for _, member := range channel.Members() {
  514. friends.Add(member)
  515. lastDiscarded := channel.history.LastDiscarded()
  516. if lastDiscarded.Before(oldestLostMessage) {
  517. oldestLostMessage = lastDiscarded
  518. }
  519. }
  520. }
  521. privmsgMatcher := func(item history.Item) bool {
  522. return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
  523. }
  524. privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
  525. lastDiscarded := client.history.LastDiscarded()
  526. if lastDiscarded.Before(oldestLostMessage) {
  527. oldestLostMessage = lastDiscarded
  528. }
  529. for _, item := range privmsgHistory {
  530. sender := server.clients.Get(stripMaskFromNick(item.Nick))
  531. if sender != nil {
  532. friends.Add(sender)
  533. }
  534. }
  535. timestamp := session.resumeDetails.Timestamp
  536. gap := lastDiscarded.Sub(timestamp)
  537. session.resumeDetails.HistoryIncomplete = gap > 0 || timestamp.IsZero()
  538. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  539. details := client.Details()
  540. oldNickmask := details.nickMask
  541. client.SetRawHostname(session.rawHostname)
  542. hostname := client.Hostname() // may be a vhost
  543. timestampString := timestamp.Format(IRCv3TimestampFormat)
  544. // send quit/resume messages to friends
  545. for friend := range friends {
  546. if friend == client {
  547. continue
  548. }
  549. for _, fSession := range friend.Sessions() {
  550. if fSession.capabilities.Has(caps.Resume) {
  551. if !session.resumeDetails.HistoryIncomplete {
  552. fSession.Send(nil, oldNickmask, "RESUMED", hostname, "ok")
  553. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  554. fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
  555. } else {
  556. fSession.Send(nil, oldNickmask, "RESUMED", hostname)
  557. }
  558. } else {
  559. if !session.resumeDetails.HistoryIncomplete {
  560. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  561. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  562. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of message history lost)"), gapSeconds))
  563. } else {
  564. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (message history may have been lost)")))
  565. }
  566. }
  567. }
  568. }
  569. if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  570. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
  571. } else {
  572. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Resume may have lost some message history"))
  573. }
  574. session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
  575. server.playRegistrationBurst(session)
  576. for _, channel := range client.Channels() {
  577. channel.Resume(session, timestamp)
  578. }
  579. // replay direct PRIVSMG history
  580. if !timestamp.IsZero() {
  581. now := time.Now().UTC()
  582. items, complete := client.history.Between(timestamp, now, false, 0)
  583. rb := NewResponseBuffer(client.Sessions()[0])
  584. client.replayPrivmsgHistory(rb, items, complete)
  585. rb.Send(true)
  586. }
  587. session.resumeDetails = nil
  588. }
  589. func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
  590. var batchID string
  591. details := client.Details()
  592. nick := details.nick
  593. if 0 < len(items) {
  594. batchID = rb.StartNestedHistoryBatch(nick)
  595. }
  596. allowTags := rb.session.capabilities.Has(caps.MessageTags)
  597. for _, item := range items {
  598. var command string
  599. switch item.Type {
  600. case history.Privmsg:
  601. command = "PRIVMSG"
  602. case history.Notice:
  603. command = "NOTICE"
  604. case history.Tagmsg:
  605. if allowTags {
  606. command = "TAGMSG"
  607. } else {
  608. continue
  609. }
  610. default:
  611. continue
  612. }
  613. var tags map[string]string
  614. if allowTags {
  615. tags = item.Tags
  616. }
  617. if item.Params[0] == "" {
  618. // this message was sent *to* the client from another nick
  619. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
  620. } else {
  621. // this message was sent *from* the client to another nick; the target is item.Params[0]
  622. // substitute the client's current nickmask in case they changed nick
  623. rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
  624. }
  625. }
  626. rb.EndNestedBatch(batchID)
  627. if !complete {
  628. rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  629. }
  630. }
  631. // IdleTime returns how long this client's been idle.
  632. func (client *Client) IdleTime() time.Duration {
  633. client.stateMutex.RLock()
  634. defer client.stateMutex.RUnlock()
  635. return time.Since(client.atime)
  636. }
  637. // SignonTime returns this client's signon time as a unix timestamp.
  638. func (client *Client) SignonTime() int64 {
  639. return client.ctime.Unix()
  640. }
  641. // IdleSeconds returns the number of seconds this client's been idle.
  642. func (client *Client) IdleSeconds() uint64 {
  643. return uint64(client.IdleTime().Seconds())
  644. }
  645. // HasNick returns true if the client's nickname is set (used in registration).
  646. func (client *Client) HasNick() bool {
  647. client.stateMutex.RLock()
  648. defer client.stateMutex.RUnlock()
  649. return client.nick != "" && client.nick != "*"
  650. }
  651. // HasUsername returns true if the client's username is set (used in registration).
  652. func (client *Client) HasUsername() bool {
  653. client.stateMutex.RLock()
  654. defer client.stateMutex.RUnlock()
  655. return client.username != "" && client.username != "*"
  656. }
  657. // SetNames sets the client's ident and realname.
  658. func (client *Client) SetNames(username, realname string, fromIdent bool) error {
  659. limit := client.server.Config().Limits.IdentLen
  660. if !fromIdent {
  661. limit -= 1 // leave room for the prepended ~
  662. }
  663. if limit < len(username) {
  664. username = username[:limit]
  665. }
  666. if !isIdent(username) {
  667. return errInvalidUsername
  668. }
  669. if !fromIdent {
  670. username = "~" + username
  671. }
  672. client.stateMutex.Lock()
  673. defer client.stateMutex.Unlock()
  674. if client.username == "" {
  675. client.username = username
  676. }
  677. if client.realname == "" {
  678. client.realname = realname
  679. }
  680. return nil
  681. }
  682. // HasRoleCapabs returns true if client has the given (role) capabilities.
  683. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  684. oper := client.Oper()
  685. if oper == nil {
  686. return false
  687. }
  688. for _, capab := range capabs {
  689. if !oper.Class.Capabilities[capab] {
  690. return false
  691. }
  692. }
  693. return true
  694. }
  695. // ModeString returns the mode string for this client.
  696. func (client *Client) ModeString() (str string) {
  697. return "+" + client.flags.String()
  698. }
  699. // Friends refers to clients that share a channel with this client.
  700. func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
  701. result = make(map[*Session]bool)
  702. // look at the client's own sessions
  703. for _, session := range client.Sessions() {
  704. if session.capabilities.HasAll(capabs...) {
  705. result[session] = true
  706. }
  707. }
  708. for _, channel := range client.Channels() {
  709. for _, member := range channel.Members() {
  710. for _, session := range member.Sessions() {
  711. if session.capabilities.HasAll(capabs...) {
  712. result[session] = true
  713. }
  714. }
  715. }
  716. }
  717. return
  718. }
  719. func (client *Client) SetOper(oper *Oper) {
  720. client.stateMutex.Lock()
  721. defer client.stateMutex.Unlock()
  722. client.oper = oper
  723. // operators typically get a vhost, update the nickmask
  724. client.updateNickMaskNoMutex()
  725. }
  726. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  727. // this is annoying to do correctly
  728. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  729. username := client.Username()
  730. for fClient := range client.Friends(caps.ChgHost) {
  731. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  732. }
  733. }
  734. // choose the correct vhost to display
  735. func (client *Client) getVHostNoMutex() string {
  736. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  737. if client.vhost != "" {
  738. return client.vhost
  739. } else if client.oper != nil {
  740. return client.oper.Vhost
  741. } else {
  742. return ""
  743. }
  744. }
  745. // SetVHost updates the client's hostserv-based vhost
  746. func (client *Client) SetVHost(vhost string) (updated bool) {
  747. client.stateMutex.Lock()
  748. defer client.stateMutex.Unlock()
  749. updated = (client.vhost != vhost)
  750. client.vhost = vhost
  751. if updated {
  752. client.updateNickMaskNoMutex()
  753. }
  754. return
  755. }
  756. // updateNick updates `nick` and `nickCasefolded`.
  757. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  758. client.stateMutex.Lock()
  759. defer client.stateMutex.Unlock()
  760. client.nick = nick
  761. client.nickCasefolded = nickCasefolded
  762. client.skeleton = skeleton
  763. client.updateNickMaskNoMutex()
  764. }
  765. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  766. func (client *Client) updateNickMaskNoMutex() {
  767. client.hostname = client.getVHostNoMutex()
  768. if client.hostname == "" {
  769. client.hostname = client.cloakedHostname
  770. if client.hostname == "" {
  771. client.hostname = client.rawHostname
  772. }
  773. }
  774. cfhostname, err := Casefold(client.hostname)
  775. if err != nil {
  776. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  777. cfhostname = client.hostname // YOLO
  778. }
  779. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  780. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  781. }
  782. // AllNickmasks returns all the possible nickmasks for the client.
  783. func (client *Client) AllNickmasks() (masks []string) {
  784. client.stateMutex.RLock()
  785. nick := client.nickCasefolded
  786. username := client.username
  787. rawHostname := client.rawHostname
  788. cloakedHostname := client.cloakedHostname
  789. vhost := client.getVHostNoMutex()
  790. client.stateMutex.RUnlock()
  791. username = strings.ToLower(username)
  792. if len(vhost) > 0 {
  793. cfvhost, err := Casefold(vhost)
  794. if err == nil {
  795. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  796. }
  797. }
  798. var rawhostmask string
  799. cfrawhost, err := Casefold(rawHostname)
  800. if err == nil {
  801. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  802. masks = append(masks, rawhostmask)
  803. }
  804. if cloakedHostname != "" {
  805. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
  806. }
  807. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  808. if ipmask != rawhostmask {
  809. masks = append(masks, ipmask)
  810. }
  811. return
  812. }
  813. // LoggedIntoAccount returns true if this client is logged into an account.
  814. func (client *Client) LoggedIntoAccount() bool {
  815. return client.Account() != ""
  816. }
  817. // Quit sets the given quit message for the client.
  818. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  819. // the command handler or calling it yourself.)
  820. func (client *Client) Quit(message string, session *Session) {
  821. setFinalData := func(sess *Session) {
  822. message := sess.quitMessage
  823. var finalData []byte
  824. // #364: don't send QUIT lines to unregistered clients
  825. if client.registered {
  826. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  827. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  828. }
  829. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  830. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  831. finalData = append(finalData, errorMsgBytes...)
  832. sess.socket.SetFinalData(finalData)
  833. }
  834. client.stateMutex.Lock()
  835. defer client.stateMutex.Unlock()
  836. var sessions []*Session
  837. if session != nil {
  838. sessions = []*Session{session}
  839. } else {
  840. sessions = client.sessions
  841. }
  842. for _, session := range sessions {
  843. if session.SetQuitMessage(message) {
  844. setFinalData(session)
  845. }
  846. }
  847. }
  848. // destroy gets rid of a client, removes them from server lists etc.
  849. // if `session` is nil, destroys the client unconditionally, removing all sessions;
  850. // otherwise, destroys one specific session, only destroying the client if it
  851. // has no more sessions.
  852. func (client *Client) destroy(session *Session) {
  853. var sessionsToDestroy []*Session
  854. client.stateMutex.Lock()
  855. details := client.detailsNoMutex()
  856. brbState := client.brbTimer.state
  857. brbAt := client.brbTimer.brbAt
  858. wasReattach := session != nil && session.client != client
  859. sessionRemoved := false
  860. var remainingSessions int
  861. if session == nil {
  862. sessionsToDestroy = client.sessions
  863. client.sessions = nil
  864. remainingSessions = 0
  865. } else {
  866. sessionRemoved, remainingSessions = client.removeSession(session)
  867. if sessionRemoved {
  868. sessionsToDestroy = []*Session{session}
  869. }
  870. }
  871. // should we destroy the whole client this time?
  872. // BRB is not respected if this is a destroy of the whole client (i.e., session == nil)
  873. brbEligible := session != nil && (brbState == BrbEnabled || brbState == BrbSticky)
  874. shouldDestroy := !client.destroyed && remainingSessions == 0 && !brbEligible
  875. if shouldDestroy {
  876. // if it's our job to destroy it, don't let anyone else try
  877. client.destroyed = true
  878. }
  879. exitedSnomaskSent := client.exitedSnomaskSent
  880. client.stateMutex.Unlock()
  881. // destroy all applicable sessions:
  882. var quitMessage string
  883. for _, session := range sessionsToDestroy {
  884. if session.client != client {
  885. // session has been attached to a new client; do not destroy it
  886. continue
  887. }
  888. session.idletimer.Stop()
  889. // send quit/error message to client if they haven't been sent already
  890. client.Quit("", session)
  891. quitMessage = session.quitMessage
  892. session.SetDestroyed()
  893. session.socket.Close()
  894. // remove from connection limits
  895. var source string
  896. if client.isTor {
  897. client.server.torLimiter.RemoveClient()
  898. source = "tor"
  899. } else {
  900. ip := session.realIP
  901. if session.proxiedIP != nil {
  902. ip = session.proxiedIP
  903. }
  904. client.server.connectionLimiter.RemoveClient(ip)
  905. source = ip.String()
  906. }
  907. client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
  908. }
  909. // do not destroy the client if it has either remaining sessions, or is BRB'ed
  910. if !shouldDestroy {
  911. return
  912. }
  913. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  914. // a lot of RAM, so limit concurrency to avoid thrashing
  915. client.server.semaphores.ClientDestroy.Acquire()
  916. defer client.server.semaphores.ClientDestroy.Release()
  917. if !wasReattach {
  918. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
  919. }
  920. registered := client.Registered()
  921. if registered {
  922. client.server.whoWas.Append(client.WhoWas())
  923. }
  924. client.server.resumeManager.Delete(client)
  925. // alert monitors
  926. if registered {
  927. client.server.monitorManager.AlertAbout(client, false)
  928. }
  929. // clean up monitor state
  930. client.server.monitorManager.RemoveAll(client)
  931. splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
  932. // clean up channels
  933. // (note that if this is a reattach, client has no channels and therefore no friends)
  934. friends := make(ClientSet)
  935. for _, channel := range client.Channels() {
  936. channel.Quit(client)
  937. channel.history.Add(history.Item{
  938. Type: history.Quit,
  939. Nick: details.nickMask,
  940. AccountName: details.accountName,
  941. Message: splitQuitMessage,
  942. })
  943. for _, member := range channel.Members() {
  944. friends.Add(member)
  945. }
  946. }
  947. friends.Remove(client)
  948. // clean up server
  949. client.server.clients.Remove(client)
  950. // clean up self
  951. client.nickTimer.Stop()
  952. client.brbTimer.Disable()
  953. client.server.accounts.Logout(client)
  954. client.server.stats.Remove(registered, client.HasMode(modes.Invisible),
  955. client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator))
  956. // this happens under failure to return from BRB
  957. if quitMessage == "" {
  958. if !brbAt.IsZero() {
  959. awayMessage := client.AwayMessage()
  960. if awayMessage == "" {
  961. awayMessage = "Disconnected" // auto-BRB
  962. }
  963. quitMessage = fmt.Sprintf("%s [%s ago]", awayMessage, time.Since(brbAt).Truncate(time.Second).String())
  964. }
  965. }
  966. if quitMessage == "" {
  967. quitMessage = "Exited"
  968. }
  969. for friend := range friends {
  970. friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
  971. }
  972. if !exitedSnomaskSent && registered {
  973. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
  974. }
  975. }
  976. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  977. // Adds account-tag to the line as well.
  978. func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  979. if session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  980. session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  981. } else {
  982. for _, messagePair := range message.Wrapped {
  983. session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  984. }
  985. }
  986. }
  987. // Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
  988. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  989. for _, session := range client.Sessions() {
  990. err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
  991. if err_ != nil {
  992. err = err_
  993. }
  994. }
  995. return
  996. }
  997. func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  998. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  999. // attach account-tag
  1000. if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
  1001. msg.SetTag("account", accountName)
  1002. }
  1003. // attach message-id
  1004. if msgid != "" && session.capabilities.Has(caps.MessageTags) {
  1005. msg.SetTag("msgid", msgid)
  1006. }
  1007. // attach server-time
  1008. session.setTimeTag(&msg, serverTime)
  1009. return session.SendRawMessage(msg, blocking)
  1010. }
  1011. var (
  1012. // these are all the output commands that MUST have their last param be a trailing.
  1013. // this is needed because dumb clients like to treat trailing params separately from the
  1014. // other params in messages.
  1015. commandsThatMustUseTrailing = map[string]bool{
  1016. "PRIVMSG": true,
  1017. "NOTICE": true,
  1018. RPL_WHOISCHANNELS: true,
  1019. RPL_USERHOST: true,
  1020. }
  1021. )
  1022. // SendRawMessage sends a raw message to the client.
  1023. func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  1024. // use dumb hack to force the last param to be a trailing param if required
  1025. var usedTrailingHack bool
  1026. config := session.client.server.Config()
  1027. if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
  1028. lastParam := message.Params[len(message.Params)-1]
  1029. // to force trailing, we ensure the final param contains a space
  1030. if strings.IndexByte(lastParam, ' ') == -1 {
  1031. message.Params[len(message.Params)-1] = lastParam + " "
  1032. usedTrailingHack = true
  1033. }
  1034. }
  1035. // assemble message
  1036. maxlenRest := session.MaxlenRest()
  1037. line, err := message.LineBytesStrict(false, maxlenRest)
  1038. if err != nil {
  1039. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  1040. session.client.server.logger.Error("internal", logline)
  1041. message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  1042. line, _ := message.LineBytesStrict(false, 0)
  1043. if blocking {
  1044. session.socket.BlockingWrite(line)
  1045. } else {
  1046. session.socket.Write(line)
  1047. }
  1048. return err
  1049. }
  1050. // if we used the trailing hack, we need to strip the final space we appended earlier on
  1051. if usedTrailingHack {
  1052. copy(line[len(line)-3:], "\r\n")
  1053. line = line[:len(line)-1]
  1054. }
  1055. if session.client.server.logger.IsLoggingRawIO() {
  1056. logline := string(line[:len(line)-2]) // strip "\r\n"
  1057. session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
  1058. }
  1059. if blocking {
  1060. return session.socket.BlockingWrite(line)
  1061. } else {
  1062. return session.socket.Write(line)
  1063. }
  1064. }
  1065. // Send sends an IRC line to the client.
  1066. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1067. for _, session := range client.Sessions() {
  1068. err_ := session.Send(tags, prefix, command, params...)
  1069. if err_ != nil {
  1070. err = err_
  1071. }
  1072. }
  1073. return
  1074. }
  1075. func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1076. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  1077. session.setTimeTag(&msg, time.Time{})
  1078. return session.SendRawMessage(msg, false)
  1079. }
  1080. func (session *Session) setTimeTag(msg *ircmsg.IrcMessage, serverTime time.Time) {
  1081. if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  1082. if serverTime.IsZero() {
  1083. serverTime = time.Now()
  1084. }
  1085. msg.SetTag("time", serverTime.UTC().Format(IRCv3TimestampFormat))
  1086. }
  1087. }
  1088. // Notice sends the client a notice from the server.
  1089. func (client *Client) Notice(text string) {
  1090. client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
  1091. }
  1092. func (client *Client) addChannel(channel *Channel) {
  1093. client.stateMutex.Lock()
  1094. client.channels[channel] = true
  1095. client.stateMutex.Unlock()
  1096. }
  1097. func (client *Client) removeChannel(channel *Channel) {
  1098. client.stateMutex.Lock()
  1099. delete(client.channels, channel)
  1100. client.stateMutex.Unlock()
  1101. }
  1102. // Records that the client has been invited to join an invite-only channel
  1103. func (client *Client) Invite(casefoldedChannel string) {
  1104. client.stateMutex.Lock()
  1105. defer client.stateMutex.Unlock()
  1106. if client.invitedTo == nil {
  1107. client.invitedTo = make(map[string]bool)
  1108. }
  1109. client.invitedTo[casefoldedChannel] = true
  1110. }
  1111. // Checks that the client was invited to join a given channel
  1112. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  1113. client.stateMutex.Lock()
  1114. defer client.stateMutex.Unlock()
  1115. invited = client.invitedTo[casefoldedChannel]
  1116. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  1117. delete(client.invitedTo, casefoldedChannel)
  1118. return
  1119. }