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

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