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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. firstLine := true
  221. for {
  222. maxlenTags, maxlenRest := client.recomputeMaxlens()
  223. line, err = client.socket.Read()
  224. if err != nil {
  225. quitMessage := "connection closed"
  226. if err == errReadQ {
  227. quitMessage = "readQ exceeded"
  228. }
  229. client.Quit(quitMessage)
  230. break
  231. }
  232. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  233. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  234. if firstLine {
  235. firstLine = false
  236. if strings.HasPrefix(line, "PROXY") {
  237. err = handleProxyCommand(client.server, client, line)
  238. if err != nil {
  239. break
  240. } else {
  241. continue
  242. }
  243. }
  244. }
  245. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  246. if err == ircmsg.ErrorLineIsEmpty {
  247. continue
  248. } else if err != nil {
  249. client.Quit(client.t("Received malformed line"))
  250. break
  251. }
  252. cmd, exists := Commands[msg.Command]
  253. if !exists {
  254. if len(msg.Command) > 0 {
  255. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
  256. } else {
  257. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
  258. }
  259. continue
  260. }
  261. isExiting = cmd.Run(client.server, client, msg)
  262. if isExiting || client.isQuitting {
  263. break
  264. }
  265. }
  266. }
  267. //
  268. // idle, quit, timers and timeouts
  269. //
  270. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  271. func (client *Client) Active() {
  272. client.stateMutex.Lock()
  273. defer client.stateMutex.Unlock()
  274. client.atime = time.Now()
  275. }
  276. // Touch marks the client as alive (as it it has a connection to us and we
  277. // can receive messages from it).
  278. func (client *Client) Touch() {
  279. client.idletimer.Touch()
  280. }
  281. // Ping sends the client a PING message.
  282. func (client *Client) Ping() {
  283. client.Send(nil, "", "PING", client.nick)
  284. }
  285. // Register sets the client details as appropriate when entering the network.
  286. func (client *Client) Register() {
  287. client.stateMutex.Lock()
  288. alreadyRegistered := client.registered
  289. client.registered = true
  290. client.stateMutex.Unlock()
  291. if alreadyRegistered {
  292. return
  293. }
  294. // apply resume details if we're able to.
  295. client.TryResume()
  296. // finish registration
  297. client.updateNickMask("")
  298. client.server.monitorManager.AlertAbout(client, true)
  299. }
  300. // TryResume tries to resume if the client asked us to.
  301. func (client *Client) TryResume() {
  302. if client.resumeDetails == nil {
  303. return
  304. }
  305. server := client.server
  306. // just grab these mutexes for safety. later we can work out whether we can grab+release them earlier
  307. server.clients.Lock()
  308. defer server.clients.Unlock()
  309. server.channels.Lock()
  310. defer server.channels.Unlock()
  311. oldnick := client.resumeDetails.OldNick
  312. timestamp := client.resumeDetails.Timestamp
  313. var timestampString string
  314. if timestamp != nil {
  315. timestampString = timestamp.UTC().Format("2006-01-02T15:04:05.999Z")
  316. }
  317. // can't use server.clients.Get since we hold server.clients' tier 1 mutex
  318. casefoldedName, err := CasefoldName(oldnick)
  319. if err != nil {
  320. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  321. return
  322. }
  323. oldClient := server.clients.byNick[casefoldedName]
  324. if oldClient == nil {
  325. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  326. return
  327. }
  328. oldAccountName := oldClient.Account()
  329. newAccountName := client.Account()
  330. if oldAccountName == "" || newAccountName == "" || oldAccountName != newAccountName {
  331. 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"))
  332. return
  333. }
  334. if !oldClient.HasMode(modes.TLS) || !client.HasMode(modes.TLS) {
  335. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  336. return
  337. }
  338. // unmark the new client's nick as being occupied
  339. server.clients.removeInternal(client)
  340. // send RESUMED to the reconnecting client
  341. if timestamp == nil {
  342. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  343. } else {
  344. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  345. }
  346. // send QUIT/RESUMED to friends
  347. for friend := range oldClient.Friends() {
  348. if friend.capabilities.Has(caps.Resume) {
  349. if timestamp == nil {
  350. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  351. } else {
  352. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  353. }
  354. } else {
  355. friend.Send(nil, oldClient.NickMaskString(), "QUIT", friend.t("Client reconnected"))
  356. }
  357. }
  358. // apply old client's details to new client
  359. client.nick = oldClient.nick
  360. client.updateNickMaskNoMutex()
  361. rejoinChannel := func(channel *Channel) {
  362. channel.joinPartMutex.Lock()
  363. defer channel.joinPartMutex.Unlock()
  364. channel.stateMutex.Lock()
  365. client.channels[channel] = true
  366. client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
  367. oldModeSet := channel.members[oldClient]
  368. channel.members.Remove(oldClient)
  369. channel.members[client] = oldModeSet
  370. channel.stateMutex.Unlock()
  371. channel.regenerateMembersCache()
  372. // construct fake modestring if necessary
  373. oldModes := oldModeSet.String()
  374. var params []string
  375. if 0 < len(oldModes) {
  376. params = []string{channel.name, "+" + oldModes}
  377. for range oldModes {
  378. params = append(params, client.nick)
  379. }
  380. }
  381. // send join for old clients
  382. for member := range channel.members {
  383. if member.capabilities.Has(caps.Resume) {
  384. continue
  385. }
  386. if member.capabilities.Has(caps.ExtendedJoin) {
  387. member.Send(nil, client.nickMaskString, "JOIN", channel.name, client.AccountName(), client.realname)
  388. } else {
  389. member.Send(nil, client.nickMaskString, "JOIN", channel.name)
  390. }
  391. // send fake modestring if necessary
  392. if 0 < len(oldModes) {
  393. member.Send(nil, server.name, "MODE", params...)
  394. }
  395. }
  396. }
  397. for channel := range oldClient.channels {
  398. rejoinChannel(channel)
  399. }
  400. server.clients.byNick[oldnick] = client
  401. oldClient.destroy(true)
  402. }
  403. // IdleTime returns how long this client's been idle.
  404. func (client *Client) IdleTime() time.Duration {
  405. client.stateMutex.RLock()
  406. defer client.stateMutex.RUnlock()
  407. return time.Since(client.atime)
  408. }
  409. // SignonTime returns this client's signon time as a unix timestamp.
  410. func (client *Client) SignonTime() int64 {
  411. return client.ctime.Unix()
  412. }
  413. // IdleSeconds returns the number of seconds this client's been idle.
  414. func (client *Client) IdleSeconds() uint64 {
  415. return uint64(client.IdleTime().Seconds())
  416. }
  417. // HasNick returns true if the client's nickname is set (used in registration).
  418. func (client *Client) HasNick() bool {
  419. client.stateMutex.RLock()
  420. defer client.stateMutex.RUnlock()
  421. return client.nick != "" && client.nick != "*"
  422. }
  423. // HasUsername returns true if the client's username is set (used in registration).
  424. func (client *Client) HasUsername() bool {
  425. client.stateMutex.RLock()
  426. defer client.stateMutex.RUnlock()
  427. return client.username != "" && client.username != "*"
  428. }
  429. // HasRoleCapabs returns true if client has the given (role) capabilities.
  430. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  431. oper := client.Oper()
  432. if oper == nil {
  433. return false
  434. }
  435. for _, capab := range capabs {
  436. if !oper.Class.Capabilities[capab] {
  437. return false
  438. }
  439. }
  440. return true
  441. }
  442. // ModeString returns the mode string for this client.
  443. func (client *Client) ModeString() (str string) {
  444. return "+" + client.flags.String()
  445. }
  446. // Friends refers to clients that share a channel with this client.
  447. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  448. friends := make(ClientSet)
  449. // make sure that I have the right caps
  450. hasCaps := true
  451. for _, capab := range capabs {
  452. if !client.capabilities.Has(capab) {
  453. hasCaps = false
  454. break
  455. }
  456. }
  457. if hasCaps {
  458. friends.Add(client)
  459. }
  460. for _, channel := range client.Channels() {
  461. for _, member := range channel.Members() {
  462. // make sure they have all the required caps
  463. hasCaps = true
  464. for _, capab := range capabs {
  465. if !member.capabilities.Has(capab) {
  466. hasCaps = false
  467. break
  468. }
  469. }
  470. if hasCaps {
  471. friends.Add(member)
  472. }
  473. }
  474. }
  475. return friends
  476. }
  477. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  478. // this is annoying to do correctly
  479. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  480. username := client.Username()
  481. for fClient := range client.Friends(caps.ChgHost) {
  482. fClient.sendFromClientInternal("", client, oldNickMask, nil, "CHGHOST", username, vhost)
  483. }
  484. }
  485. // choose the correct vhost to display
  486. func (client *Client) getVHostNoMutex() string {
  487. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  488. if client.vhost != "" {
  489. return client.vhost
  490. } else if client.oper != nil {
  491. return client.oper.Vhost
  492. } else {
  493. return ""
  494. }
  495. }
  496. // SetVHost updates the client's hostserv-based vhost
  497. func (client *Client) SetVHost(vhost string) (updated bool) {
  498. client.stateMutex.Lock()
  499. defer client.stateMutex.Unlock()
  500. updated = (client.vhost != vhost)
  501. client.vhost = vhost
  502. if updated {
  503. client.updateNickMaskNoMutex()
  504. }
  505. return
  506. }
  507. // updateNick updates `nick` and `nickCasefolded`.
  508. func (client *Client) updateNick(nick string) {
  509. casefoldedName, err := CasefoldName(nick)
  510. if err != nil {
  511. client.server.logger.Error("internal", "nick couldn't be casefolded", nick, err.Error())
  512. return
  513. }
  514. client.stateMutex.Lock()
  515. client.nick = nick
  516. client.nickCasefolded = casefoldedName
  517. client.stateMutex.Unlock()
  518. }
  519. // updateNickMask updates the casefolded nickname and nickmask.
  520. func (client *Client) updateNickMask(nick string) {
  521. // on "", just regenerate the nickmask etc.
  522. // otherwise, update the actual nick
  523. if nick != "" {
  524. client.updateNick(nick)
  525. }
  526. client.stateMutex.Lock()
  527. defer client.stateMutex.Unlock()
  528. client.updateNickMaskNoMutex()
  529. }
  530. // updateNickMask updates the casefolded nickname and nickmask, not acquiring any mutexes.
  531. func (client *Client) updateNickMaskNoMutex() {
  532. client.hostname = client.getVHostNoMutex()
  533. if client.hostname == "" {
  534. client.hostname = client.rawHostname
  535. }
  536. nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  537. nickMaskCasefolded, err := Casefold(nickMaskString)
  538. if err != nil {
  539. client.server.logger.Error("internal", "nickmask couldn't be casefolded", nickMaskString, err.Error())
  540. return
  541. }
  542. client.nickMaskString = nickMaskString
  543. client.nickMaskCasefolded = nickMaskCasefolded
  544. }
  545. // AllNickmasks returns all the possible nickmasks for the client.
  546. func (client *Client) AllNickmasks() []string {
  547. var masks []string
  548. var mask string
  549. var err error
  550. client.stateMutex.RLock()
  551. nick := client.nick
  552. username := client.username
  553. rawHostname := client.rawHostname
  554. vhost := client.getVHostNoMutex()
  555. client.stateMutex.RUnlock()
  556. if len(vhost) > 0 {
  557. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, vhost))
  558. if err == nil {
  559. masks = append(masks, mask)
  560. }
  561. }
  562. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, rawHostname))
  563. if err == nil {
  564. masks = append(masks, mask)
  565. }
  566. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", nick, username, client.IPString()))
  567. if err == nil && mask2 != mask {
  568. masks = append(masks, mask2)
  569. }
  570. return masks
  571. }
  572. // LoggedIntoAccount returns true if this client is logged into an account.
  573. func (client *Client) LoggedIntoAccount() bool {
  574. return client.Account() != ""
  575. }
  576. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  577. func (client *Client) RplISupport(rb *ResponseBuffer) {
  578. translatedISupport := client.t("are supported by this server")
  579. nick := client.Nick()
  580. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  581. length := len(cachedTokenLine) + 2
  582. tokenline := make([]string, length)
  583. tokenline[0] = nick
  584. copy(tokenline[1:], cachedTokenLine)
  585. tokenline[length-1] = translatedISupport
  586. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  587. }
  588. }
  589. // Quit sets the given quit message for the client and tells the client to quit out.
  590. func (client *Client) Quit(message string) {
  591. client.stateMutex.Lock()
  592. alreadyQuit := client.isQuitting
  593. if !alreadyQuit {
  594. client.isQuitting = true
  595. client.quitMessage = message
  596. }
  597. client.stateMutex.Unlock()
  598. if alreadyQuit {
  599. return
  600. }
  601. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  602. quitLine, _ := quitMsg.Line()
  603. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  604. errorLine, _ := errorMsg.Line()
  605. client.socket.SetFinalData(quitLine + errorLine)
  606. }
  607. // destroy gets rid of a client, removes them from server lists etc.
  608. func (client *Client) destroy(beingResumed bool) {
  609. // allow destroy() to execute at most once
  610. if !beingResumed {
  611. client.stateMutex.Lock()
  612. }
  613. isDestroyed := client.isDestroyed
  614. client.isDestroyed = true
  615. if !beingResumed {
  616. client.stateMutex.Unlock()
  617. }
  618. if isDestroyed {
  619. return
  620. }
  621. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  622. // a lot of RAM, so limit concurrency to avoid thrashing
  623. client.server.semaphores.ClientDestroy.Acquire()
  624. defer client.server.semaphores.ClientDestroy.Release()
  625. if beingResumed {
  626. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  627. } else {
  628. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  629. }
  630. // send quit/error message to client if they haven't been sent already
  631. client.Quit("Connection closed")
  632. if !beingResumed {
  633. client.server.whoWas.Append(client.WhoWas())
  634. }
  635. // remove from connection limits
  636. ipaddr := client.IP()
  637. // this check shouldn't be required but eh
  638. if ipaddr != nil {
  639. client.server.connectionLimiter.RemoveClient(ipaddr)
  640. }
  641. // alert monitors
  642. client.server.monitorManager.AlertAbout(client, false)
  643. // clean up monitor state
  644. client.server.monitorManager.RemoveAll(client)
  645. // clean up channels
  646. friends := make(ClientSet)
  647. for _, channel := range client.Channels() {
  648. if !beingResumed {
  649. channel.Quit(client)
  650. }
  651. for _, member := range channel.Members() {
  652. friends.Add(member)
  653. }
  654. }
  655. friends.Remove(client)
  656. // clean up server
  657. if !beingResumed {
  658. client.server.clients.Remove(client)
  659. }
  660. // clean up self
  661. client.idletimer.Stop()
  662. client.nickTimer.Stop()
  663. client.server.accounts.Logout(client)
  664. client.socket.Close()
  665. // send quit messages to friends
  666. if !beingResumed {
  667. if client.Registered() {
  668. client.server.stats.ChangeTotal(-1)
  669. }
  670. if client.HasMode(modes.Invisible) {
  671. client.server.stats.ChangeInvisible(-1)
  672. }
  673. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  674. client.server.stats.ChangeOperators(-1)
  675. }
  676. for friend := range friends {
  677. if client.quitMessage == "" {
  678. client.quitMessage = "Exited"
  679. }
  680. friend.Send(nil, client.nickMaskString, "QUIT", client.quitMessage)
  681. }
  682. }
  683. if !client.exitedSnomaskSent {
  684. if beingResumed {
  685. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  686. } else {
  687. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  688. }
  689. }
  690. }
  691. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  692. // Adds account-tag to the line as well.
  693. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
  694. if client.capabilities.Has(caps.MaxLine) {
  695. client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
  696. } else {
  697. for _, str := range message.For512 {
  698. client.SendFromClient(msgid, from, tags, command, target, str)
  699. }
  700. }
  701. }
  702. // SendFromClient sends an IRC line coming from a specific client.
  703. // Adds account-tag to the line as well.
  704. func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  705. return client.sendFromClientInternal(msgid, from, from.NickMaskString(), tags, command, params...)
  706. }
  707. // XXX this is a hack where we allow overriding the client's nickmask
  708. // this is to support CHGHOST, which requires that we send the *original* nickmask with the response
  709. func (client *Client) sendFromClientInternal(msgid string, from *Client, nickmask string, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  710. // attach account-tag
  711. if client.capabilities.Has(caps.AccountTag) && from.LoggedIntoAccount() {
  712. if tags == nil {
  713. tags = ircmsg.MakeTags("account", from.AccountName())
  714. } else {
  715. (*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
  716. }
  717. }
  718. // attach message-id
  719. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  720. if tags == nil {
  721. tags = ircmsg.MakeTags("draft/msgid", msgid)
  722. } else {
  723. (*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
  724. }
  725. }
  726. return client.Send(tags, nickmask, command, params...)
  727. }
  728. var (
  729. // these are all the output commands that MUST have their last param be a trailing.
  730. // this is needed because dumb clients like to treat trailing params separately from the
  731. // other params in messages.
  732. commandsThatMustUseTrailing = map[string]bool{
  733. "PRIVMSG": true,
  734. "NOTICE": true,
  735. RPL_WHOISCHANNELS: true,
  736. RPL_USERHOST: true,
  737. }
  738. )
  739. // SendRawMessage sends a raw message to the client.
  740. func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
  741. // use dumb hack to force the last param to be a trailing param if required
  742. var usedTrailingHack bool
  743. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  744. lastParam := message.Params[len(message.Params)-1]
  745. // to force trailing, we ensure the final param contains a space
  746. if !strings.Contains(lastParam, " ") {
  747. message.Params[len(message.Params)-1] = lastParam + " "
  748. usedTrailingHack = true
  749. }
  750. }
  751. // assemble message
  752. maxlenTags, maxlenRest := client.maxlens()
  753. line, err := message.LineMaxLenBytes(maxlenTags, maxlenRest)
  754. if err != nil {
  755. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  756. client.server.logger.Error("internal", logline)
  757. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  758. line, _ := message.LineBytes()
  759. client.socket.Write(line)
  760. return err
  761. }
  762. // if we used the trailing hack, we need to strip the final space we appended earlier on
  763. if usedTrailingHack {
  764. copy(line[len(line)-3:], []byte{'\r', '\n'})
  765. line = line[:len(line)-1]
  766. }
  767. if client.server.logger.IsLoggingRawIO() {
  768. logline := string(line[:len(line)-2]) // strip "\r\n"
  769. client.server.logger.Debug("useroutput", client.nick, " ->", logline)
  770. }
  771. client.socket.Write(line)
  772. return nil
  773. }
  774. // Send sends an IRC line to the client.
  775. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  776. // attach server-time
  777. if client.capabilities.Has(caps.ServerTime) {
  778. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  779. if tags == nil {
  780. tags = ircmsg.MakeTags("time", t)
  781. } else {
  782. (*tags)["time"] = ircmsg.MakeTagValue(t)
  783. }
  784. }
  785. // send out the message
  786. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  787. client.SendRawMessage(message)
  788. return nil
  789. }
  790. // Notice sends the client a notice from the server.
  791. func (client *Client) Notice(text string) {
  792. limit := 400
  793. if client.capabilities.Has(caps.MaxLine) {
  794. limit = client.server.Limits().LineLen.Rest - 110
  795. }
  796. lines := wordWrap(text, limit)
  797. // force blank lines to be sent if we receive them
  798. if len(lines) == 0 {
  799. lines = []string{""}
  800. }
  801. for _, line := range lines {
  802. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  803. }
  804. }
  805. func (client *Client) addChannel(channel *Channel) {
  806. client.stateMutex.Lock()
  807. client.channels[channel] = true
  808. client.stateMutex.Unlock()
  809. }
  810. func (client *Client) removeChannel(channel *Channel) {
  811. client.stateMutex.Lock()
  812. delete(client.channels, channel)
  813. client.stateMutex.Unlock()
  814. }