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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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/modes"
  20. "github.com/oragono/oragono/irc/sno"
  21. "github.com/oragono/oragono/irc/utils"
  22. )
  23. const (
  24. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  25. IdentTimeoutSeconds = 1.5
  26. )
  27. var (
  28. LoopbackIP = net.ParseIP("127.0.0.1")
  29. )
  30. // Client is an IRC client.
  31. type Client struct {
  32. account string
  33. accountName string
  34. atime time.Time
  35. authorized bool
  36. awayMessage string
  37. capabilities *caps.Set
  38. capState caps.State
  39. capVersion caps.Version
  40. certfp string
  41. channels ChannelSet
  42. ctime time.Time
  43. exitedSnomaskSent bool
  44. fakelag *Fakelag
  45. flags *modes.ModeSet
  46. hasQuit bool
  47. hops int
  48. hostname string
  49. idletimer *IdleTimer
  50. isDestroyed bool
  51. isQuitting bool
  52. languages []string
  53. maxlenTags uint32
  54. maxlenRest uint32
  55. nick string
  56. nickCasefolded string
  57. nickMaskCasefolded string
  58. nickMaskString string // cache for nickmask string since it's used with lots of replies
  59. nickTimer *NickTimer
  60. oper *Oper
  61. preregNick string
  62. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  63. quitMessage string
  64. rawHostname string
  65. realname string
  66. registered bool
  67. resumeDetails *ResumeDetails
  68. saslInProgress bool
  69. saslMechanism string
  70. saslValue string
  71. server *Server
  72. socket *Socket
  73. stateMutex sync.RWMutex // tier 1
  74. username string
  75. vhost string
  76. }
  77. // NewClient sets up a new client and starts its goroutine.
  78. func NewClient(server *Server, conn net.Conn, isTLS bool) {
  79. now := time.Now()
  80. config := server.Config()
  81. fullLineLenLimit := config.Limits.LineLen.Tags + config.Limits.LineLen.Rest
  82. socket := NewSocket(conn, fullLineLenLimit*2, config.Server.MaxSendQBytes)
  83. client := &Client{
  84. atime: now,
  85. authorized: server.Password() == nil,
  86. capabilities: caps.NewSet(),
  87. capState: caps.NoneState,
  88. capVersion: caps.Cap301,
  89. channels: make(ChannelSet),
  90. ctime: now,
  91. flags: modes.NewModeSet(),
  92. server: server,
  93. socket: socket,
  94. nick: "*", // * is used until actual nick is given
  95. nickCasefolded: "*",
  96. nickMaskString: "*", // * is used until actual nick is given
  97. }
  98. client.languages = server.languages.Default()
  99. client.recomputeMaxlens()
  100. if isTLS {
  101. client.SetMode(modes.TLS, true)
  102. // error is not useful to us here anyways so we can ignore it
  103. client.certfp, _ = client.socket.CertFP()
  104. }
  105. if config.Server.CheckIdent && !utils.AddrIsUnix(conn.RemoteAddr()) {
  106. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  107. if err != nil {
  108. server.logger.Error("internal", "bad server address", err.Error())
  109. return
  110. }
  111. serverPort, _ := strconv.Atoi(serverPortString)
  112. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  113. if err != nil {
  114. server.logger.Error("internal", "bad client address", err.Error())
  115. return
  116. }
  117. clientPort, _ := strconv.Atoi(clientPortString)
  118. client.Notice(client.t("*** Looking up your username"))
  119. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  120. if err == nil {
  121. username := resp.Identifier
  122. _, err := CasefoldName(username) // ensure it's a valid username
  123. if err == nil {
  124. client.Notice(client.t("*** Found your username"))
  125. client.username = username
  126. // we don't need to updateNickMask here since nickMask is not used for anything yet
  127. } else {
  128. client.Notice(client.t("*** Got a malformed username, ignoring"))
  129. }
  130. } else {
  131. client.Notice(client.t("*** Could not find your username"))
  132. }
  133. }
  134. go client.run()
  135. }
  136. func (client *Client) resetFakelag() {
  137. fakelag := func() *Fakelag {
  138. if client.HasRoleCapabs("nofakelag") {
  139. return nil
  140. }
  141. flc := client.server.FakelagConfig()
  142. if !flc.Enabled {
  143. return nil
  144. }
  145. return NewFakelag(flc.Window, flc.BurstLimit, flc.MessagesPerWindow, flc.Cooldown)
  146. }()
  147. client.stateMutex.Lock()
  148. defer client.stateMutex.Unlock()
  149. client.fakelag = fakelag
  150. }
  151. // IP returns the IP address of this client.
  152. func (client *Client) IP() net.IP {
  153. if client.proxiedIP != nil {
  154. return client.proxiedIP
  155. }
  156. if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
  157. return ip
  158. }
  159. // unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
  160. return LoopbackIP
  161. }
  162. // IPString returns the IP address of this client as a string.
  163. func (client *Client) IPString() string {
  164. ip := client.IP().String()
  165. if 0 < len(ip) && ip[0] == ':' {
  166. ip = "0" + ip
  167. }
  168. return ip
  169. }
  170. //
  171. // command goroutine
  172. //
  173. func (client *Client) recomputeMaxlens() (int, int) {
  174. maxlenTags := 512
  175. maxlenRest := 512
  176. if client.capabilities.Has(caps.MessageTags) {
  177. maxlenTags = 4096
  178. }
  179. if client.capabilities.Has(caps.MaxLine) {
  180. limits := client.server.Limits()
  181. if limits.LineLen.Tags > maxlenTags {
  182. maxlenTags = limits.LineLen.Tags
  183. }
  184. maxlenRest = limits.LineLen.Rest
  185. }
  186. atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
  187. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  188. return maxlenTags, maxlenRest
  189. }
  190. // allow these negotiated length limits to be read without locks; this is a convenience
  191. // so that Client.Send doesn't have to acquire any Client locks
  192. func (client *Client) maxlens() (int, int) {
  193. return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
  194. }
  195. func (client *Client) run() {
  196. var err error
  197. var isExiting bool
  198. var line string
  199. var msg ircmsg.IrcMessage
  200. defer func() {
  201. if r := recover(); r != nil {
  202. client.server.logger.Error("internal",
  203. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  204. if client.server.RecoverFromErrors() {
  205. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  206. } else {
  207. panic(r)
  208. }
  209. }
  210. // ensure client connection gets closed
  211. client.destroy(false)
  212. }()
  213. client.idletimer = NewIdleTimer(client)
  214. client.idletimer.Start()
  215. client.nickTimer = NewNickTimer(client)
  216. client.resetFakelag()
  217. // Set the hostname for this client
  218. // (may be overridden by a later PROXY command from stunnel)
  219. client.rawHostname = utils.AddrLookupHostname(client.socket.conn.RemoteAddr())
  220. for {
  221. maxlenTags, maxlenRest := client.recomputeMaxlens()
  222. line, err = client.socket.Read()
  223. if err != nil {
  224. quitMessage := "connection closed"
  225. if err == errReadQ {
  226. quitMessage = "readQ exceeded"
  227. }
  228. client.Quit(quitMessage)
  229. break
  230. }
  231. client.server.logger.Debug("userinput ", client.nick, "<- ", line)
  232. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  233. if err == ircmsg.ErrorLineIsEmpty {
  234. continue
  235. } else if err != nil {
  236. client.Quit(client.t("Received malformed line"))
  237. break
  238. }
  239. cmd, exists := Commands[msg.Command]
  240. if !exists {
  241. if len(msg.Command) > 0 {
  242. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
  243. } else {
  244. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
  245. }
  246. continue
  247. }
  248. isExiting = cmd.Run(client.server, client, msg)
  249. if isExiting || client.isQuitting {
  250. break
  251. }
  252. }
  253. }
  254. //
  255. // idle, quit, timers and timeouts
  256. //
  257. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  258. func (client *Client) Active() {
  259. client.stateMutex.Lock()
  260. defer client.stateMutex.Unlock()
  261. client.atime = time.Now()
  262. }
  263. // Touch marks the client as alive (as it it has a connection to us and we
  264. // can receive messages from it).
  265. func (client *Client) Touch() {
  266. client.idletimer.Touch()
  267. }
  268. // Ping sends the client a PING message.
  269. func (client *Client) Ping() {
  270. client.Send(nil, "", "PING", client.nick)
  271. }
  272. // Register sets the client details as appropriate when entering the network.
  273. func (client *Client) Register() {
  274. client.stateMutex.Lock()
  275. alreadyRegistered := client.registered
  276. client.registered = true
  277. client.stateMutex.Unlock()
  278. if alreadyRegistered {
  279. return
  280. }
  281. // apply resume details if we're able to.
  282. client.TryResume()
  283. // finish registration
  284. client.updateNickMask("")
  285. client.server.monitorManager.AlertAbout(client, true)
  286. }
  287. // TryResume tries to resume if the client asked us to.
  288. func (client *Client) TryResume() {
  289. if client.resumeDetails == nil {
  290. return
  291. }
  292. server := client.server
  293. // just grab these mutexes for safety. later we can work out whether we can grab+release them earlier
  294. server.clients.Lock()
  295. defer server.clients.Unlock()
  296. server.channels.Lock()
  297. defer server.channels.Unlock()
  298. oldnick := client.resumeDetails.OldNick
  299. timestamp := client.resumeDetails.Timestamp
  300. var timestampString string
  301. if timestamp != nil {
  302. timestampString = timestamp.UTC().Format("2006-01-02T15:04:05.999Z")
  303. }
  304. // can't use server.clients.Get since we hold server.clients' tier 1 mutex
  305. casefoldedName, err := CasefoldName(oldnick)
  306. if err != nil {
  307. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  308. return
  309. }
  310. oldClient := server.clients.byNick[casefoldedName]
  311. if oldClient == nil {
  312. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  313. return
  314. }
  315. oldAccountName := oldClient.Account()
  316. newAccountName := client.Account()
  317. if oldAccountName == "" || newAccountName == "" || oldAccountName != newAccountName {
  318. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must be logged into the same account"))
  319. return
  320. }
  321. if !oldClient.HasMode(modes.TLS) || !client.HasMode(modes.TLS) {
  322. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  323. return
  324. }
  325. // unmark the new client's nick as being occupied
  326. server.clients.removeInternal(client)
  327. // send RESUMED to the reconnecting client
  328. if timestamp == nil {
  329. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  330. } else {
  331. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  332. }
  333. // send QUIT/RESUMED to friends
  334. for friend := range oldClient.Friends() {
  335. if friend.capabilities.Has(caps.Resume) {
  336. if timestamp == nil {
  337. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  338. } else {
  339. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  340. }
  341. } else {
  342. friend.Send(nil, oldClient.NickMaskString(), "QUIT", friend.t("Client reconnected"))
  343. }
  344. }
  345. // apply old client's details to new client
  346. client.nick = oldClient.nick
  347. client.updateNickMaskNoMutex()
  348. rejoinChannel := func(channel *Channel) {
  349. channel.joinPartMutex.Lock()
  350. defer channel.joinPartMutex.Unlock()
  351. channel.stateMutex.Lock()
  352. client.channels[channel] = true
  353. client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
  354. oldModeSet := channel.members[oldClient]
  355. channel.members.Remove(oldClient)
  356. channel.members[client] = oldModeSet
  357. channel.stateMutex.Unlock()
  358. channel.regenerateMembersCache()
  359. // construct fake modestring if necessary
  360. oldModes := oldModeSet.String()
  361. var params []string
  362. if 0 < len(oldModes) {
  363. params = []string{channel.name, "+" + oldModes}
  364. for range oldModes {
  365. params = append(params, client.nick)
  366. }
  367. }
  368. // send join for old clients
  369. for member := range channel.members {
  370. if member.capabilities.Has(caps.Resume) {
  371. continue
  372. }
  373. if member.capabilities.Has(caps.ExtendedJoin) {
  374. member.Send(nil, client.nickMaskString, "JOIN", channel.name, client.AccountName(), client.realname)
  375. } else {
  376. member.Send(nil, client.nickMaskString, "JOIN", channel.name)
  377. }
  378. // send fake modestring if necessary
  379. if 0 < len(oldModes) {
  380. member.Send(nil, server.name, "MODE", params...)
  381. }
  382. }
  383. }
  384. for channel := range oldClient.channels {
  385. rejoinChannel(channel)
  386. }
  387. server.clients.byNick[oldnick] = client
  388. oldClient.destroy(true)
  389. }
  390. // IdleTime returns how long this client's been idle.
  391. func (client *Client) IdleTime() time.Duration {
  392. client.stateMutex.RLock()
  393. defer client.stateMutex.RUnlock()
  394. return time.Since(client.atime)
  395. }
  396. // SignonTime returns this client's signon time as a unix timestamp.
  397. func (client *Client) SignonTime() int64 {
  398. return client.ctime.Unix()
  399. }
  400. // IdleSeconds returns the number of seconds this client's been idle.
  401. func (client *Client) IdleSeconds() uint64 {
  402. return uint64(client.IdleTime().Seconds())
  403. }
  404. // HasNick returns true if the client's nickname is set (used in registration).
  405. func (client *Client) HasNick() bool {
  406. client.stateMutex.RLock()
  407. defer client.stateMutex.RUnlock()
  408. return client.nick != "" && client.nick != "*"
  409. }
  410. // HasUsername returns true if the client's username is set (used in registration).
  411. func (client *Client) HasUsername() bool {
  412. client.stateMutex.RLock()
  413. defer client.stateMutex.RUnlock()
  414. return client.username != "" && client.username != "*"
  415. }
  416. // HasRoleCapabs returns true if client has the given (role) capabilities.
  417. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  418. oper := client.Oper()
  419. if oper == nil {
  420. return false
  421. }
  422. for _, capab := range capabs {
  423. if !oper.Class.Capabilities[capab] {
  424. return false
  425. }
  426. }
  427. return true
  428. }
  429. // ModeString returns the mode string for this client.
  430. func (client *Client) ModeString() (str string) {
  431. return "+" + client.flags.String()
  432. }
  433. // Friends refers to clients that share a channel with this client.
  434. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  435. friends := make(ClientSet)
  436. // make sure that I have the right caps
  437. hasCaps := true
  438. for _, capab := range capabs {
  439. if !client.capabilities.Has(capab) {
  440. hasCaps = false
  441. break
  442. }
  443. }
  444. if hasCaps {
  445. friends.Add(client)
  446. }
  447. for _, channel := range client.Channels() {
  448. for _, member := range channel.Members() {
  449. // make sure they have all the required caps
  450. hasCaps = true
  451. for _, capab := range capabs {
  452. if !member.capabilities.Has(capab) {
  453. hasCaps = false
  454. break
  455. }
  456. }
  457. if hasCaps {
  458. friends.Add(member)
  459. }
  460. }
  461. }
  462. return friends
  463. }
  464. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  465. // this is annoying to do correctly
  466. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  467. username := client.Username()
  468. for fClient := range client.Friends(caps.ChgHost) {
  469. fClient.sendFromClientInternal("", client, oldNickMask, nil, "CHGHOST", username, vhost)
  470. }
  471. }
  472. // choose the correct vhost to display
  473. func (client *Client) getVHostNoMutex() string {
  474. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  475. if client.vhost != "" {
  476. return client.vhost
  477. } else if client.oper != nil {
  478. return client.oper.Vhost
  479. } else {
  480. return ""
  481. }
  482. }
  483. // SetVHost updates the client's hostserv-based vhost
  484. func (client *Client) SetVHost(vhost string) (updated bool) {
  485. client.stateMutex.Lock()
  486. defer client.stateMutex.Unlock()
  487. updated = (client.vhost != vhost)
  488. client.vhost = vhost
  489. if updated {
  490. client.updateNickMaskNoMutex()
  491. }
  492. return
  493. }
  494. // updateNick updates `nick` and `nickCasefolded`.
  495. func (client *Client) updateNick(nick string) {
  496. casefoldedName, err := CasefoldName(nick)
  497. if err != nil {
  498. client.server.logger.Error("internal", "nick couldn't be casefolded", nick, err.Error())
  499. return
  500. }
  501. client.stateMutex.Lock()
  502. client.nick = nick
  503. client.nickCasefolded = casefoldedName
  504. client.stateMutex.Unlock()
  505. }
  506. // updateNickMask updates the casefolded nickname and nickmask.
  507. func (client *Client) updateNickMask(nick string) {
  508. // on "", just regenerate the nickmask etc.
  509. // otherwise, update the actual nick
  510. if nick != "" {
  511. client.updateNick(nick)
  512. }
  513. client.stateMutex.Lock()
  514. defer client.stateMutex.Unlock()
  515. client.updateNickMaskNoMutex()
  516. }
  517. // updateNickMask updates the casefolded nickname and nickmask, not acquiring any mutexes.
  518. func (client *Client) updateNickMaskNoMutex() {
  519. client.hostname = client.getVHostNoMutex()
  520. if client.hostname == "" {
  521. client.hostname = client.rawHostname
  522. }
  523. nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  524. nickMaskCasefolded, err := Casefold(nickMaskString)
  525. if err != nil {
  526. client.server.logger.Error("internal", "nickmask couldn't be casefolded", nickMaskString, err.Error())
  527. return
  528. }
  529. client.nickMaskString = nickMaskString
  530. client.nickMaskCasefolded = nickMaskCasefolded
  531. }
  532. // AllNickmasks returns all the possible nickmasks for the client.
  533. func (client *Client) AllNickmasks() []string {
  534. var masks []string
  535. var mask string
  536. var err error
  537. client.stateMutex.RLock()
  538. nick := client.nick
  539. username := client.username
  540. rawHostname := client.rawHostname
  541. vhost := client.getVHostNoMutex()
  542. client.stateMutex.RUnlock()
  543. if len(vhost) > 0 {
  544. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, vhost))
  545. if err == nil {
  546. masks = append(masks, mask)
  547. }
  548. }
  549. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, rawHostname))
  550. if err == nil {
  551. masks = append(masks, mask)
  552. }
  553. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", nick, username, client.IPString()))
  554. if err == nil && mask2 != mask {
  555. masks = append(masks, mask2)
  556. }
  557. return masks
  558. }
  559. // LoggedIntoAccount returns true if this client is logged into an account.
  560. func (client *Client) LoggedIntoAccount() bool {
  561. return client.Account() != ""
  562. }
  563. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  564. func (client *Client) RplISupport(rb *ResponseBuffer) {
  565. translatedISupport := client.t("are supported by this server")
  566. nick := client.Nick()
  567. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  568. length := len(cachedTokenLine) + 2
  569. tokenline := make([]string, length)
  570. tokenline[0] = nick
  571. copy(tokenline[1:], cachedTokenLine)
  572. tokenline[length-1] = translatedISupport
  573. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  574. }
  575. }
  576. // Quit sets the given quit message for the client and tells the client to quit out.
  577. func (client *Client) Quit(message string) {
  578. client.stateMutex.Lock()
  579. alreadyQuit := client.isQuitting
  580. if !alreadyQuit {
  581. client.isQuitting = true
  582. client.quitMessage = message
  583. }
  584. client.stateMutex.Unlock()
  585. if alreadyQuit {
  586. return
  587. }
  588. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  589. quitLine, _ := quitMsg.Line()
  590. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  591. errorLine, _ := errorMsg.Line()
  592. client.socket.SetFinalData(quitLine + errorLine)
  593. }
  594. // destroy gets rid of a client, removes them from server lists etc.
  595. func (client *Client) destroy(beingResumed bool) {
  596. // allow destroy() to execute at most once
  597. if !beingResumed {
  598. client.stateMutex.Lock()
  599. }
  600. isDestroyed := client.isDestroyed
  601. client.isDestroyed = true
  602. if !beingResumed {
  603. client.stateMutex.Unlock()
  604. }
  605. if isDestroyed {
  606. return
  607. }
  608. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  609. // a lot of RAM, so limit concurrency to avoid thrashing
  610. client.server.semaphores.ClientDestroy.Acquire()
  611. defer client.server.semaphores.ClientDestroy.Release()
  612. if beingResumed {
  613. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  614. } else {
  615. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  616. }
  617. // send quit/error message to client if they haven't been sent already
  618. client.Quit("Connection closed")
  619. if !beingResumed {
  620. client.server.whoWas.Append(client.WhoWas())
  621. }
  622. // remove from connection limits
  623. ipaddr := client.IP()
  624. // this check shouldn't be required but eh
  625. if ipaddr != nil {
  626. client.server.connectionLimiter.RemoveClient(ipaddr)
  627. }
  628. // alert monitors
  629. client.server.monitorManager.AlertAbout(client, false)
  630. // clean up monitor state
  631. client.server.monitorManager.RemoveAll(client)
  632. // clean up channels
  633. friends := make(ClientSet)
  634. for _, channel := range client.Channels() {
  635. if !beingResumed {
  636. channel.Quit(client)
  637. }
  638. for _, member := range channel.Members() {
  639. friends.Add(member)
  640. }
  641. }
  642. friends.Remove(client)
  643. // clean up server
  644. if !beingResumed {
  645. client.server.clients.Remove(client)
  646. }
  647. // clean up self
  648. client.idletimer.Stop()
  649. client.nickTimer.Stop()
  650. client.server.accounts.Logout(client)
  651. client.socket.Close()
  652. // send quit messages to friends
  653. if !beingResumed {
  654. if client.Registered() {
  655. client.server.stats.ChangeTotal(-1)
  656. }
  657. if client.HasMode(modes.Invisible) {
  658. client.server.stats.ChangeInvisible(-1)
  659. }
  660. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  661. client.server.stats.ChangeOperators(-1)
  662. }
  663. for friend := range friends {
  664. if client.quitMessage == "" {
  665. client.quitMessage = "Exited"
  666. }
  667. friend.Send(nil, client.nickMaskString, "QUIT", client.quitMessage)
  668. }
  669. }
  670. if !client.exitedSnomaskSent {
  671. if beingResumed {
  672. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  673. } else {
  674. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  675. }
  676. }
  677. }
  678. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  679. // Adds account-tag to the line as well.
  680. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
  681. if client.capabilities.Has(caps.MaxLine) {
  682. client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
  683. } else {
  684. for _, str := range message.For512 {
  685. client.SendFromClient(msgid, from, tags, command, target, str)
  686. }
  687. }
  688. }
  689. // SendFromClient sends an IRC line coming from a specific client.
  690. // Adds account-tag to the line as well.
  691. func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  692. return client.sendFromClientInternal(msgid, from, from.NickMaskString(), tags, command, params...)
  693. }
  694. // XXX this is a hack where we allow overriding the client's nickmask
  695. // this is to support CHGHOST, which requires that we send the *original* nickmask with the response
  696. func (client *Client) sendFromClientInternal(msgid string, from *Client, nickmask string, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  697. // attach account-tag
  698. if client.capabilities.Has(caps.AccountTag) && from.LoggedIntoAccount() {
  699. if tags == nil {
  700. tags = ircmsg.MakeTags("account", from.AccountName())
  701. } else {
  702. (*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
  703. }
  704. }
  705. // attach message-id
  706. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  707. if tags == nil {
  708. tags = ircmsg.MakeTags("draft/msgid", msgid)
  709. } else {
  710. (*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
  711. }
  712. }
  713. return client.Send(tags, nickmask, command, params...)
  714. }
  715. var (
  716. // these are all the output commands that MUST have their last param be a trailing.
  717. // this is needed because dumb clients like to treat trailing params separately from the
  718. // other params in messages.
  719. commandsThatMustUseTrailing = map[string]bool{
  720. "PRIVMSG": true,
  721. "NOTICE": true,
  722. RPL_WHOISCHANNELS: true,
  723. RPL_USERHOST: true,
  724. }
  725. )
  726. // SendRawMessage sends a raw message to the client.
  727. func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
  728. // use dumb hack to force the last param to be a trailing param if required
  729. var usedTrailingHack bool
  730. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  731. lastParam := message.Params[len(message.Params)-1]
  732. // to force trailing, we ensure the final param contains a space
  733. if !strings.Contains(lastParam, " ") {
  734. message.Params[len(message.Params)-1] = lastParam + " "
  735. usedTrailingHack = true
  736. }
  737. }
  738. // assemble message
  739. maxlenTags, maxlenRest := client.maxlens()
  740. line, err := message.LineMaxLenBytes(maxlenTags, maxlenRest)
  741. if err != nil {
  742. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  743. client.server.logger.Error("internal", logline)
  744. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  745. line, _ := message.LineBytes()
  746. client.socket.Write(line)
  747. return err
  748. }
  749. // if we used the trailing hack, we need to strip the final space we appended earlier on
  750. if usedTrailingHack {
  751. copy(line[len(line)-3:], []byte{'\r', '\n'})
  752. line = line[:len(line)-1]
  753. }
  754. if client.server.logger.IsLoggingRawIO() {
  755. logline := string(line[:len(line)-2]) // strip "\r\n"
  756. client.server.logger.Debug("useroutput", client.nick, " ->", logline)
  757. }
  758. client.socket.Write(line)
  759. return nil
  760. }
  761. // Send sends an IRC line to the client.
  762. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  763. // attach server-time
  764. if client.capabilities.Has(caps.ServerTime) {
  765. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  766. if tags == nil {
  767. tags = ircmsg.MakeTags("time", t)
  768. } else {
  769. (*tags)["time"] = ircmsg.MakeTagValue(t)
  770. }
  771. }
  772. // send out the message
  773. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  774. client.SendRawMessage(message)
  775. return nil
  776. }
  777. // Notice sends the client a notice from the server.
  778. func (client *Client) Notice(text string) {
  779. limit := 400
  780. if client.capabilities.Has(caps.MaxLine) {
  781. limit = client.server.Limits().LineLen.Rest - 110
  782. }
  783. lines := wordWrap(text, limit)
  784. // force blank lines to be sent if we receive them
  785. if len(lines) == 0 {
  786. lines = []string{""}
  787. }
  788. for _, line := range lines {
  789. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  790. }
  791. }
  792. func (client *Client) addChannel(channel *Channel) {
  793. client.stateMutex.Lock()
  794. client.channels[channel] = true
  795. client.stateMutex.Unlock()
  796. }
  797. func (client *Client) removeChannel(channel *Channel) {
  798. client.stateMutex.Lock()
  799. delete(client.channels, channel)
  800. client.stateMutex.Unlock()
  801. }