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.

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