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

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