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.

client.go 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  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.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.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)
  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.IsTLS {
  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.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. client.run(session)
  249. }
  250. func (client *Client) doIdentLookup(conn net.Conn) {
  251. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  252. if err != nil {
  253. client.server.logger.Error("internal", "bad server address", err.Error())
  254. return
  255. }
  256. serverPort, _ := strconv.Atoi(serverPortString)
  257. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  258. if err != nil {
  259. client.server.logger.Error("internal", "bad client address", err.Error())
  260. return
  261. }
  262. clientPort, _ := strconv.Atoi(clientPortString)
  263. client.Notice(client.t("*** Looking up your username"))
  264. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  265. if err == nil {
  266. err := client.SetNames(resp.Identifier, "", true)
  267. if err == nil {
  268. client.Notice(client.t("*** Found your username"))
  269. // we don't need to updateNickMask here since nickMask is not used for anything yet
  270. } else {
  271. client.Notice(client.t("*** Got a malformed username, ignoring"))
  272. }
  273. } else {
  274. client.Notice(client.t("*** Could not find your username"))
  275. }
  276. }
  277. type AuthOutcome uint
  278. const (
  279. authSuccess AuthOutcome = iota
  280. authFailPass
  281. authFailTorSaslRequired
  282. authFailSaslRequired
  283. )
  284. func (client *Client) isAuthorized(config *Config) AuthOutcome {
  285. saslSent := client.account != ""
  286. // PASS requirement
  287. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  288. return authFailPass
  289. }
  290. // Tor connections may be required to authenticate with SASL
  291. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  292. return authFailTorSaslRequired
  293. }
  294. // finally, enforce require-sasl
  295. if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets) {
  296. return authFailSaslRequired
  297. }
  298. return authSuccess
  299. }
  300. func (session *Session) resetFakelag() {
  301. var flc FakelagConfig = session.client.server.Config().Fakelag
  302. flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
  303. session.fakelag.Initialize(flc)
  304. }
  305. // IP returns the IP address of this client.
  306. func (client *Client) IP() net.IP {
  307. client.stateMutex.RLock()
  308. defer client.stateMutex.RUnlock()
  309. if client.proxiedIP != nil {
  310. return client.proxiedIP
  311. }
  312. return client.realIP
  313. }
  314. // IPString returns the IP address of this client as a string.
  315. func (client *Client) IPString() string {
  316. ip := client.IP().String()
  317. if 0 < len(ip) && ip[0] == ':' {
  318. ip = "0" + ip
  319. }
  320. return ip
  321. }
  322. //
  323. // command goroutine
  324. //
  325. func (client *Client) run(session *Session) {
  326. defer func() {
  327. if r := recover(); r != nil {
  328. client.server.logger.Error("internal",
  329. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  330. if client.server.Config().Debug.recoverFromErrors {
  331. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  332. } else {
  333. panic(r)
  334. }
  335. }
  336. // ensure client connection gets closed
  337. client.destroy(session)
  338. }()
  339. session.idletimer.Initialize(session)
  340. session.resetFakelag()
  341. isReattach := client.Registered()
  342. if isReattach {
  343. if session.resumeDetails != nil {
  344. session.playResume()
  345. session.resumeDetails = nil
  346. client.brbTimer.Disable()
  347. } else {
  348. client.playReattachMessages(session)
  349. }
  350. } else {
  351. // don't reset the nick timer during a reattach
  352. client.nickTimer.Initialize(client)
  353. }
  354. firstLine := !isReattach
  355. for {
  356. maxlenRest := session.MaxlenRest()
  357. line, err := session.socket.Read()
  358. if err != nil {
  359. quitMessage := "connection closed"
  360. if err == errReadQ {
  361. quitMessage = "readQ exceeded"
  362. }
  363. client.Quit(quitMessage, session)
  364. // since the client did not actually send us a QUIT,
  365. // give them a chance to resume if applicable:
  366. if !session.Destroyed() {
  367. client.brbTimer.Enable()
  368. }
  369. break
  370. }
  371. if client.server.logger.IsLoggingRawIO() {
  372. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  373. }
  374. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  375. if firstLine {
  376. firstLine = false
  377. if strings.HasPrefix(line, "PROXY") {
  378. err = handleProxyCommand(client.server, client, session, line)
  379. if err != nil {
  380. break
  381. } else {
  382. continue
  383. }
  384. }
  385. }
  386. if client.registered {
  387. session.fakelag.Touch()
  388. } else {
  389. // DoS hardening, #505
  390. session.registrationMessages++
  391. if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
  392. client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
  393. break
  394. }
  395. }
  396. msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
  397. if err == ircmsg.ErrorLineIsEmpty {
  398. continue
  399. } else if err == ircmsg.ErrorLineTooLong {
  400. session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
  401. continue
  402. } else if err != nil {
  403. client.Quit(client.t("Received malformed line"), session)
  404. break
  405. }
  406. cmd, exists := Commands[msg.Command]
  407. if !exists {
  408. if len(msg.Command) > 0 {
  409. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
  410. } else {
  411. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
  412. }
  413. continue
  414. }
  415. isExiting := cmd.Run(client.server, client, session, msg)
  416. if isExiting {
  417. break
  418. } else if session.client != client {
  419. // bouncer reattach
  420. go session.client.run(session)
  421. break
  422. }
  423. }
  424. }
  425. func (client *Client) playReattachMessages(session *Session) {
  426. client.server.playRegistrationBurst(session)
  427. for _, channel := range session.client.Channels() {
  428. channel.playJoinForSession(session)
  429. // clients should receive autoreplay-on-join lines, if applicable;
  430. // if they negotiated znc.in/playback or chathistory, they will receive nothing,
  431. // because those caps disable autoreplay-on-join and they haven't sent the relevant
  432. // *playback PRIVMSG or CHATHISTORY command yet
  433. rb := NewResponseBuffer(session)
  434. channel.autoReplayHistory(client, rb, "")
  435. rb.Send(true)
  436. }
  437. }
  438. //
  439. // idle, quit, timers and timeouts
  440. //
  441. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  442. func (client *Client) Active(session *Session) {
  443. now := time.Now().UTC()
  444. client.stateMutex.Lock()
  445. defer client.stateMutex.Unlock()
  446. session.atime = now
  447. client.atime = now
  448. }
  449. // Ping sends the client a PING message.
  450. func (session *Session) Ping() {
  451. session.Send(nil, "", "PING", session.client.Nick())
  452. }
  453. // tryResume tries to resume if the client asked us to.
  454. func (session *Session) tryResume() (success bool) {
  455. var oldResumeID string
  456. defer func() {
  457. if success {
  458. // "On a successful request, the server [...] terminates the old client's connection"
  459. oldSession := session.client.GetSessionByResumeID(oldResumeID)
  460. if oldSession != nil {
  461. session.client.destroy(oldSession)
  462. }
  463. } else {
  464. session.resumeDetails = nil
  465. }
  466. }()
  467. client := session.client
  468. server := client.server
  469. config := server.Config()
  470. oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
  471. if oldClient == nil {
  472. session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
  473. return
  474. }
  475. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  476. if !resumeAllowed {
  477. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
  478. return
  479. }
  480. if oldClient.isTor != client.isTor {
  481. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  482. return
  483. }
  484. err := server.clients.Resume(oldClient, session)
  485. if err != nil {
  486. session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
  487. return
  488. }
  489. success = true
  490. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
  491. return
  492. }
  493. // playResume is called from the session's fresh goroutine after a resume;
  494. // it sends notifications to friends, then plays the registration burst and replays
  495. // stored history to the session
  496. func (session *Session) playResume() {
  497. client := session.client
  498. server := client.server
  499. friends := make(ClientSet)
  500. oldestLostMessage := time.Now().UTC()
  501. // work out how much time, if any, is not covered by history buffers
  502. for _, channel := range client.Channels() {
  503. for _, member := range channel.Members() {
  504. friends.Add(member)
  505. lastDiscarded := channel.history.LastDiscarded()
  506. if lastDiscarded.Before(oldestLostMessage) {
  507. oldestLostMessage = lastDiscarded
  508. }
  509. }
  510. }
  511. privmsgMatcher := func(item history.Item) bool {
  512. return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
  513. }
  514. privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
  515. lastDiscarded := client.history.LastDiscarded()
  516. if lastDiscarded.Before(oldestLostMessage) {
  517. oldestLostMessage = lastDiscarded
  518. }
  519. for _, item := range privmsgHistory {
  520. sender := server.clients.Get(stripMaskFromNick(item.Nick))
  521. if sender != nil {
  522. friends.Add(sender)
  523. }
  524. }
  525. timestamp := session.resumeDetails.Timestamp
  526. gap := lastDiscarded.Sub(timestamp)
  527. session.resumeDetails.HistoryIncomplete = gap > 0 || timestamp.IsZero()
  528. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  529. details := client.Details()
  530. oldNickmask := details.nickMask
  531. client.SetRawHostname(session.rawHostname)
  532. hostname := client.Hostname() // may be a vhost
  533. timestampString := timestamp.Format(IRCv3TimestampFormat)
  534. // send quit/resume messages to friends
  535. for friend := range friends {
  536. if friend == client {
  537. continue
  538. }
  539. for _, fSession := range friend.Sessions() {
  540. if fSession.capabilities.Has(caps.Resume) {
  541. if !session.resumeDetails.HistoryIncomplete {
  542. fSession.Send(nil, oldNickmask, "RESUMED", hostname, "ok")
  543. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  544. fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
  545. } else {
  546. fSession.Send(nil, oldNickmask, "RESUMED", hostname)
  547. }
  548. } else {
  549. if !session.resumeDetails.HistoryIncomplete {
  550. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  551. } else if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  552. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of message history lost)"), gapSeconds))
  553. } else {
  554. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (message history may have been lost)")))
  555. }
  556. }
  557. }
  558. }
  559. if session.resumeDetails.HistoryIncomplete && !timestamp.IsZero() {
  560. 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))
  561. } else {
  562. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", client.t("Resume may have lost some message history"))
  563. }
  564. session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
  565. server.playRegistrationBurst(session)
  566. for _, channel := range client.Channels() {
  567. channel.Resume(session, timestamp)
  568. }
  569. // replay direct PRIVSMG history
  570. if !timestamp.IsZero() {
  571. now := time.Now().UTC()
  572. items, complete := client.history.Between(timestamp, now, false, 0)
  573. rb := NewResponseBuffer(client.Sessions()[0])
  574. client.replayPrivmsgHistory(rb, items, complete)
  575. rb.Send(true)
  576. }
  577. session.resumeDetails = nil
  578. }
  579. func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
  580. var batchID string
  581. details := client.Details()
  582. nick := details.nick
  583. if 0 < len(items) {
  584. batchID = rb.StartNestedHistoryBatch(nick)
  585. }
  586. allowTags := rb.session.capabilities.Has(caps.MessageTags)
  587. for _, item := range items {
  588. var command string
  589. switch item.Type {
  590. case history.Privmsg:
  591. command = "PRIVMSG"
  592. case history.Notice:
  593. command = "NOTICE"
  594. case history.Tagmsg:
  595. if allowTags {
  596. command = "TAGMSG"
  597. } else {
  598. continue
  599. }
  600. default:
  601. continue
  602. }
  603. var tags map[string]string
  604. if allowTags {
  605. tags = item.Tags
  606. }
  607. if item.Params[0] == "" {
  608. // this message was sent *to* the client from another nick
  609. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
  610. } else {
  611. // this message was sent *from* the client to another nick; the target is item.Params[0]
  612. // substitute the client's current nickmask in case they changed nick
  613. rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
  614. }
  615. }
  616. rb.EndNestedBatch(batchID)
  617. if !complete {
  618. rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  619. }
  620. }
  621. // IdleTime returns how long this client's been idle.
  622. func (client *Client) IdleTime() time.Duration {
  623. client.stateMutex.RLock()
  624. defer client.stateMutex.RUnlock()
  625. return time.Since(client.atime)
  626. }
  627. // SignonTime returns this client's signon time as a unix timestamp.
  628. func (client *Client) SignonTime() int64 {
  629. return client.ctime.Unix()
  630. }
  631. // IdleSeconds returns the number of seconds this client's been idle.
  632. func (client *Client) IdleSeconds() uint64 {
  633. return uint64(client.IdleTime().Seconds())
  634. }
  635. // HasNick returns true if the client's nickname is set (used in registration).
  636. func (client *Client) HasNick() bool {
  637. client.stateMutex.RLock()
  638. defer client.stateMutex.RUnlock()
  639. return client.nick != "" && client.nick != "*"
  640. }
  641. // HasUsername returns true if the client's username is set (used in registration).
  642. func (client *Client) HasUsername() bool {
  643. client.stateMutex.RLock()
  644. defer client.stateMutex.RUnlock()
  645. return client.username != "" && client.username != "*"
  646. }
  647. // SetNames sets the client's ident and realname.
  648. func (client *Client) SetNames(username, realname string, fromIdent bool) error {
  649. limit := client.server.Config().Limits.IdentLen
  650. if !fromIdent {
  651. limit -= 1 // leave room for the prepended ~
  652. }
  653. if limit < len(username) {
  654. username = username[:limit]
  655. }
  656. if !isIdent(username) {
  657. return errInvalidUsername
  658. }
  659. if !fromIdent {
  660. username = "~" + username
  661. }
  662. client.stateMutex.Lock()
  663. defer client.stateMutex.Unlock()
  664. if client.username == "" {
  665. client.username = username
  666. }
  667. if client.realname == "" {
  668. client.realname = realname
  669. }
  670. return nil
  671. }
  672. // HasRoleCapabs returns true if client has the given (role) capabilities.
  673. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  674. oper := client.Oper()
  675. if oper == nil {
  676. return false
  677. }
  678. for _, capab := range capabs {
  679. if !oper.Class.Capabilities[capab] {
  680. return false
  681. }
  682. }
  683. return true
  684. }
  685. // ModeString returns the mode string for this client.
  686. func (client *Client) ModeString() (str string) {
  687. return "+" + client.flags.String()
  688. }
  689. // Friends refers to clients that share a channel with this client.
  690. func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
  691. result = make(map[*Session]bool)
  692. // look at the client's own sessions
  693. for _, session := range client.Sessions() {
  694. if session.capabilities.HasAll(capabs...) {
  695. result[session] = true
  696. }
  697. }
  698. for _, channel := range client.Channels() {
  699. for _, member := range channel.Members() {
  700. for _, session := range member.Sessions() {
  701. if session.capabilities.HasAll(capabs...) {
  702. result[session] = true
  703. }
  704. }
  705. }
  706. }
  707. return
  708. }
  709. func (client *Client) SetOper(oper *Oper) {
  710. client.stateMutex.Lock()
  711. defer client.stateMutex.Unlock()
  712. client.oper = oper
  713. // operators typically get a vhost, update the nickmask
  714. client.updateNickMaskNoMutex()
  715. }
  716. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  717. // this is annoying to do correctly
  718. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  719. username := client.Username()
  720. for fClient := range client.Friends(caps.ChgHost) {
  721. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  722. }
  723. }
  724. // choose the correct vhost to display
  725. func (client *Client) getVHostNoMutex() string {
  726. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  727. if client.vhost != "" {
  728. return client.vhost
  729. } else if client.oper != nil {
  730. return client.oper.Vhost
  731. } else {
  732. return ""
  733. }
  734. }
  735. // SetVHost updates the client's hostserv-based vhost
  736. func (client *Client) SetVHost(vhost string) (updated bool) {
  737. client.stateMutex.Lock()
  738. defer client.stateMutex.Unlock()
  739. updated = (client.vhost != vhost)
  740. client.vhost = vhost
  741. if updated {
  742. client.updateNickMaskNoMutex()
  743. }
  744. return
  745. }
  746. // updateNick updates `nick` and `nickCasefolded`.
  747. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  748. client.stateMutex.Lock()
  749. defer client.stateMutex.Unlock()
  750. client.nick = nick
  751. client.nickCasefolded = nickCasefolded
  752. client.skeleton = skeleton
  753. client.updateNickMaskNoMutex()
  754. }
  755. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  756. func (client *Client) updateNickMaskNoMutex() {
  757. client.hostname = client.getVHostNoMutex()
  758. if client.hostname == "" {
  759. client.hostname = client.cloakedHostname
  760. if client.hostname == "" {
  761. client.hostname = client.rawHostname
  762. }
  763. }
  764. cfhostname, err := Casefold(client.hostname)
  765. if err != nil {
  766. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  767. cfhostname = client.hostname // YOLO
  768. }
  769. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  770. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  771. }
  772. // AllNickmasks returns all the possible nickmasks for the client.
  773. func (client *Client) AllNickmasks() (masks []string) {
  774. client.stateMutex.RLock()
  775. nick := client.nickCasefolded
  776. username := client.username
  777. rawHostname := client.rawHostname
  778. cloakedHostname := client.cloakedHostname
  779. vhost := client.getVHostNoMutex()
  780. client.stateMutex.RUnlock()
  781. username = strings.ToLower(username)
  782. if len(vhost) > 0 {
  783. cfvhost, err := Casefold(vhost)
  784. if err == nil {
  785. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  786. }
  787. }
  788. var rawhostmask string
  789. cfrawhost, err := Casefold(rawHostname)
  790. if err == nil {
  791. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  792. masks = append(masks, rawhostmask)
  793. }
  794. if cloakedHostname != "" {
  795. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
  796. }
  797. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  798. if ipmask != rawhostmask {
  799. masks = append(masks, ipmask)
  800. }
  801. return
  802. }
  803. // LoggedIntoAccount returns true if this client is logged into an account.
  804. func (client *Client) LoggedIntoAccount() bool {
  805. return client.Account() != ""
  806. }
  807. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  808. func (client *Client) RplISupport(rb *ResponseBuffer) {
  809. translatedISupport := client.t("are supported by this server")
  810. nick := client.Nick()
  811. config := client.server.Config()
  812. for _, cachedTokenLine := range config.Server.isupport.CachedReply {
  813. length := len(cachedTokenLine) + 2
  814. tokenline := make([]string, length)
  815. tokenline[0] = nick
  816. copy(tokenline[1:], cachedTokenLine)
  817. tokenline[length-1] = translatedISupport
  818. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  819. }
  820. }
  821. // Quit sets the given quit message for the client.
  822. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  823. // the command handler or calling it yourself.)
  824. func (client *Client) Quit(message string, session *Session) {
  825. setFinalData := func(sess *Session) {
  826. message := sess.quitMessage
  827. var finalData []byte
  828. // #364: don't send QUIT lines to unregistered clients
  829. if client.registered {
  830. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  831. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  832. }
  833. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  834. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  835. finalData = append(finalData, errorMsgBytes...)
  836. sess.socket.SetFinalData(finalData)
  837. }
  838. client.stateMutex.Lock()
  839. defer client.stateMutex.Unlock()
  840. var sessions []*Session
  841. if session != nil {
  842. sessions = []*Session{session}
  843. } else {
  844. sessions = client.sessions
  845. }
  846. for _, session := range sessions {
  847. if session.SetQuitMessage(message) {
  848. setFinalData(session)
  849. }
  850. }
  851. }
  852. // destroy gets rid of a client, removes them from server lists etc.
  853. // if `session` is nil, destroys the client unconditionally, removing all sessions;
  854. // otherwise, destroys one specific session, only destroying the client if it
  855. // has no more sessions.
  856. func (client *Client) destroy(session *Session) {
  857. var sessionsToDestroy []*Session
  858. client.stateMutex.Lock()
  859. details := client.detailsNoMutex()
  860. brbState := client.brbTimer.state
  861. brbAt := client.brbTimer.brbAt
  862. wasReattach := session != nil && session.client != client
  863. sessionRemoved := false
  864. var remainingSessions int
  865. if session == nil {
  866. sessionsToDestroy = client.sessions
  867. client.sessions = nil
  868. remainingSessions = 0
  869. } else {
  870. sessionRemoved, remainingSessions = client.removeSession(session)
  871. if sessionRemoved {
  872. sessionsToDestroy = []*Session{session}
  873. }
  874. }
  875. // should we destroy the whole client this time?
  876. // BRB is not respected if this is a destroy of the whole client (i.e., session == nil)
  877. brbEligible := session != nil && (brbState == BrbEnabled || brbState == BrbSticky)
  878. shouldDestroy := !client.destroyed && remainingSessions == 0 && !brbEligible
  879. if shouldDestroy {
  880. // if it's our job to destroy it, don't let anyone else try
  881. client.destroyed = true
  882. }
  883. exitedSnomaskSent := client.exitedSnomaskSent
  884. client.stateMutex.Unlock()
  885. // destroy all applicable sessions:
  886. var quitMessage string
  887. for _, session := range sessionsToDestroy {
  888. if session.client != client {
  889. // session has been attached to a new client; do not destroy it
  890. continue
  891. }
  892. session.idletimer.Stop()
  893. // send quit/error message to client if they haven't been sent already
  894. client.Quit("", session)
  895. quitMessage = session.quitMessage
  896. session.SetDestroyed()
  897. session.socket.Close()
  898. // remove from connection limits
  899. var source string
  900. if client.isTor {
  901. client.server.torLimiter.RemoveClient()
  902. source = "tor"
  903. } else {
  904. ip := session.realIP
  905. if session.proxiedIP != nil {
  906. ip = session.proxiedIP
  907. }
  908. client.server.connectionLimiter.RemoveClient(ip)
  909. source = ip.String()
  910. }
  911. client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
  912. }
  913. // do not destroy the client if it has either remaining sessions, or is BRB'ed
  914. if !shouldDestroy {
  915. return
  916. }
  917. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  918. // a lot of RAM, so limit concurrency to avoid thrashing
  919. client.server.semaphores.ClientDestroy.Acquire()
  920. defer client.server.semaphores.ClientDestroy.Release()
  921. if !wasReattach {
  922. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
  923. }
  924. registered := client.Registered()
  925. if registered {
  926. client.server.whoWas.Append(client.WhoWas())
  927. }
  928. client.server.resumeManager.Delete(client)
  929. // alert monitors
  930. if registered {
  931. client.server.monitorManager.AlertAbout(client, false)
  932. }
  933. // clean up monitor state
  934. client.server.monitorManager.RemoveAll(client)
  935. splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
  936. // clean up channels
  937. // (note that if this is a reattach, client has no channels and therefore no friends)
  938. friends := make(ClientSet)
  939. for _, channel := range client.Channels() {
  940. channel.Quit(client)
  941. channel.history.Add(history.Item{
  942. Type: history.Quit,
  943. Nick: details.nickMask,
  944. AccountName: details.accountName,
  945. Message: splitQuitMessage,
  946. })
  947. for _, member := range channel.Members() {
  948. friends.Add(member)
  949. }
  950. }
  951. friends.Remove(client)
  952. // clean up server
  953. client.server.clients.Remove(client)
  954. // clean up self
  955. client.nickTimer.Stop()
  956. client.brbTimer.Disable()
  957. client.server.accounts.Logout(client)
  958. // send quit messages to friends
  959. if registered {
  960. client.server.stats.ChangeTotal(-1)
  961. }
  962. if client.HasMode(modes.Invisible) {
  963. client.server.stats.ChangeInvisible(-1)
  964. }
  965. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  966. client.server.stats.ChangeOperators(-1)
  967. }
  968. // this happens under failure to return from BRB
  969. if quitMessage == "" {
  970. if !brbAt.IsZero() {
  971. awayMessage := client.AwayMessage()
  972. if awayMessage != "" {
  973. quitMessage = fmt.Sprintf("%s [%s ago]", awayMessage, time.Since(brbAt).Truncate(time.Second).String())
  974. }
  975. }
  976. }
  977. if quitMessage == "" {
  978. quitMessage = "Exited"
  979. }
  980. for friend := range friends {
  981. friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
  982. }
  983. if !exitedSnomaskSent && registered {
  984. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
  985. }
  986. }
  987. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  988. // Adds account-tag to the line as well.
  989. func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  990. if session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  991. session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  992. } else {
  993. for _, messagePair := range message.Wrapped {
  994. session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  995. }
  996. }
  997. }
  998. // Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
  999. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  1000. for _, session := range client.Sessions() {
  1001. err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
  1002. if err_ != nil {
  1003. err = err_
  1004. }
  1005. }
  1006. return
  1007. }
  1008. func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  1009. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  1010. // attach account-tag
  1011. if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
  1012. msg.SetTag("account", accountName)
  1013. }
  1014. // attach message-id
  1015. if msgid != "" && session.capabilities.Has(caps.MessageTags) {
  1016. msg.SetTag("msgid", msgid)
  1017. }
  1018. // attach server-time
  1019. if session.capabilities.Has(caps.ServerTime) {
  1020. if serverTime.IsZero() {
  1021. serverTime = time.Now().UTC()
  1022. }
  1023. msg.SetTag("time", serverTime.Format(IRCv3TimestampFormat))
  1024. }
  1025. return session.SendRawMessage(msg, blocking)
  1026. }
  1027. var (
  1028. // these are all the output commands that MUST have their last param be a trailing.
  1029. // this is needed because dumb clients like to treat trailing params separately from the
  1030. // other params in messages.
  1031. commandsThatMustUseTrailing = map[string]bool{
  1032. "PRIVMSG": true,
  1033. "NOTICE": true,
  1034. RPL_WHOISCHANNELS: true,
  1035. RPL_USERHOST: true,
  1036. }
  1037. )
  1038. // SendRawMessage sends a raw message to the client.
  1039. func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  1040. // use dumb hack to force the last param to be a trailing param if required
  1041. var usedTrailingHack bool
  1042. config := session.client.server.Config()
  1043. if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
  1044. lastParam := message.Params[len(message.Params)-1]
  1045. // to force trailing, we ensure the final param contains a space
  1046. if strings.IndexByte(lastParam, ' ') == -1 {
  1047. message.Params[len(message.Params)-1] = lastParam + " "
  1048. usedTrailingHack = true
  1049. }
  1050. }
  1051. // assemble message
  1052. maxlenRest := session.MaxlenRest()
  1053. line, err := message.LineBytesStrict(false, maxlenRest)
  1054. if err != nil {
  1055. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  1056. session.client.server.logger.Error("internal", logline)
  1057. message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  1058. line, _ := message.LineBytesStrict(false, 0)
  1059. if blocking {
  1060. session.socket.BlockingWrite(line)
  1061. } else {
  1062. session.socket.Write(line)
  1063. }
  1064. return err
  1065. }
  1066. // if we used the trailing hack, we need to strip the final space we appended earlier on
  1067. if usedTrailingHack {
  1068. copy(line[len(line)-3:], "\r\n")
  1069. line = line[:len(line)-1]
  1070. }
  1071. if session.client.server.logger.IsLoggingRawIO() {
  1072. logline := string(line[:len(line)-2]) // strip "\r\n"
  1073. session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
  1074. }
  1075. if blocking {
  1076. return session.socket.BlockingWrite(line)
  1077. } else {
  1078. return session.socket.Write(line)
  1079. }
  1080. }
  1081. // Send sends an IRC line to the client.
  1082. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1083. for _, session := range client.Sessions() {
  1084. err_ := session.Send(tags, prefix, command, params...)
  1085. if err_ != nil {
  1086. err = err_
  1087. }
  1088. }
  1089. return
  1090. }
  1091. func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1092. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  1093. if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  1094. msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  1095. }
  1096. return session.SendRawMessage(msg, false)
  1097. }
  1098. // Notice sends the client a notice from the server.
  1099. func (client *Client) Notice(text string) {
  1100. client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
  1101. }
  1102. func (client *Client) addChannel(channel *Channel) {
  1103. client.stateMutex.Lock()
  1104. client.channels[channel] = true
  1105. client.stateMutex.Unlock()
  1106. }
  1107. func (client *Client) removeChannel(channel *Channel) {
  1108. client.stateMutex.Lock()
  1109. delete(client.channels, channel)
  1110. client.stateMutex.Unlock()
  1111. }
  1112. // Records that the client has been invited to join an invite-only channel
  1113. func (client *Client) Invite(casefoldedChannel string) {
  1114. client.stateMutex.Lock()
  1115. defer client.stateMutex.Unlock()
  1116. if client.invitedTo == nil {
  1117. client.invitedTo = make(map[string]bool)
  1118. }
  1119. client.invitedTo[casefoldedChannel] = true
  1120. }
  1121. // Checks that the client was invited to join a given channel
  1122. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  1123. client.stateMutex.Lock()
  1124. defer client.stateMutex.Unlock()
  1125. invited = client.invitedTo[casefoldedChannel]
  1126. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  1127. delete(client.invitedTo, casefoldedChannel)
  1128. return
  1129. }