選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

client.go 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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 *modes.ModeSet
  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. client := &Client{
  87. atime: now,
  88. authorized: server.Password() == nil,
  89. capabilities: caps.NewSet(),
  90. capState: caps.NoneState,
  91. capVersion: caps.Cap301,
  92. channels: make(ChannelSet),
  93. ctime: now,
  94. flags: modes.NewModeSet(),
  95. server: server,
  96. socket: socket,
  97. nick: "*", // * is used until actual nick is given
  98. nickCasefolded: "*",
  99. nickMaskString: "*", // * is used until actual nick is given
  100. }
  101. client.languages = server.languages.Default()
  102. client.recomputeMaxlens()
  103. if isTLS {
  104. client.SetMode(modes.TLS, true)
  105. // error is not useful to us here anyways so we can ignore it
  106. client.certfp, _ = client.socket.CertFP()
  107. }
  108. if server.checkIdent && !utils.AddrIsUnix(conn.RemoteAddr()) {
  109. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  110. serverPort, _ := strconv.Atoi(serverPortString)
  111. if err != nil {
  112. log.Fatal(err)
  113. }
  114. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  115. clientPort, _ := strconv.Atoi(clientPortString)
  116. if err != nil {
  117. log.Fatal(err)
  118. }
  119. client.Notice(client.t("*** Looking up your username"))
  120. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  121. if err == nil {
  122. username := resp.Identifier
  123. _, err := CasefoldName(username) // ensure it's a valid username
  124. if err == nil {
  125. client.Notice(client.t("*** Found your username"))
  126. client.username = username
  127. // we don't need to updateNickMask here since nickMask is not used for anything yet
  128. } else {
  129. client.Notice(client.t("*** Got a malformed username, ignoring"))
  130. }
  131. } else {
  132. client.Notice(client.t("*** Could not find your username"))
  133. }
  134. }
  135. go client.run()
  136. return client
  137. }
  138. func (client *Client) resetFakelag() {
  139. fakelag := func() *Fakelag {
  140. if client.HasRoleCapabs("nofakelag") {
  141. return nil
  142. }
  143. flc := client.server.FakelagConfig()
  144. if !flc.Enabled {
  145. return nil
  146. }
  147. return NewFakelag(flc.Window, flc.BurstLimit, flc.MessagesPerWindow, flc.Cooldown)
  148. }()
  149. client.stateMutex.Lock()
  150. defer client.stateMutex.Unlock()
  151. client.fakelag = fakelag
  152. }
  153. // IP returns the IP address of this client.
  154. func (client *Client) IP() net.IP {
  155. if client.proxiedIP != nil {
  156. return client.proxiedIP
  157. }
  158. if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
  159. return ip
  160. }
  161. // unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
  162. return LoopbackIP
  163. }
  164. // IPString returns the IP address of this client as a string.
  165. func (client *Client) IPString() string {
  166. ip := client.IP().String()
  167. if 0 < len(ip) && ip[0] == ':' {
  168. ip = "0" + ip
  169. }
  170. return ip
  171. }
  172. //
  173. // command goroutine
  174. //
  175. func (client *Client) recomputeMaxlens() (int, int) {
  176. maxlenTags := 512
  177. maxlenRest := 512
  178. if client.capabilities.Has(caps.MessageTags) {
  179. maxlenTags = 4096
  180. }
  181. if client.capabilities.Has(caps.MaxLine) {
  182. limits := client.server.Limits()
  183. if limits.LineLen.Tags > maxlenTags {
  184. maxlenTags = limits.LineLen.Tags
  185. }
  186. maxlenRest = limits.LineLen.Rest
  187. }
  188. atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
  189. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  190. return maxlenTags, maxlenRest
  191. }
  192. // allow these negotiated length limits to be read without locks; this is a convenience
  193. // so that Client.Send doesn't have to acquire any Client locks
  194. func (client *Client) maxlens() (int, int) {
  195. return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
  196. }
  197. func (client *Client) run() {
  198. var err error
  199. var isExiting bool
  200. var line string
  201. var msg ircmsg.IrcMessage
  202. defer func() {
  203. if r := recover(); r != nil {
  204. client.server.logger.Error("internal",
  205. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  206. if client.server.RecoverFromErrors() {
  207. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  208. } else {
  209. panic(r)
  210. }
  211. }
  212. // ensure client connection gets closed
  213. client.destroy(false)
  214. }()
  215. client.idletimer = NewIdleTimer(client)
  216. client.idletimer.Start()
  217. client.nickTimer = NewNickTimer(client)
  218. client.resetFakelag()
  219. // Set the hostname for this client
  220. // (may be overridden by a later PROXY command from stunnel)
  221. client.rawHostname = utils.AddrLookupHostname(client.socket.conn.RemoteAddr())
  222. for {
  223. maxlenTags, maxlenRest := client.recomputeMaxlens()
  224. line, err = client.socket.Read()
  225. if err != nil {
  226. quitMessage := "connection closed"
  227. if err == errReadQ {
  228. quitMessage = "readQ exceeded"
  229. }
  230. client.Quit(quitMessage)
  231. break
  232. }
  233. client.server.logger.Debug("userinput ", client.nick, "<- ", line)
  234. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  235. if err == ircmsg.ErrorLineIsEmpty {
  236. continue
  237. } else if err != nil {
  238. client.Quit(client.t("Received malformed line"))
  239. break
  240. }
  241. cmd, exists := Commands[msg.Command]
  242. if !exists {
  243. if len(msg.Command) > 0 {
  244. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
  245. } else {
  246. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
  247. }
  248. continue
  249. }
  250. isExiting = cmd.Run(client.server, client, msg)
  251. if isExiting || client.isQuitting {
  252. break
  253. }
  254. }
  255. }
  256. //
  257. // idle, quit, timers and timeouts
  258. //
  259. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  260. func (client *Client) Active() {
  261. client.stateMutex.Lock()
  262. defer client.stateMutex.Unlock()
  263. client.atime = time.Now()
  264. }
  265. // Touch marks the client as alive (as it it has a connection to us and we
  266. // can receive messages from it).
  267. func (client *Client) Touch() {
  268. client.idletimer.Touch()
  269. }
  270. // Ping sends the client a PING message.
  271. func (client *Client) Ping() {
  272. client.Send(nil, "", "PING", client.nick)
  273. }
  274. //
  275. // server goroutine
  276. //
  277. // Register sets the client details as appropriate when entering the network.
  278. func (client *Client) Register() {
  279. client.stateMutex.Lock()
  280. alreadyRegistered := client.registered
  281. client.registered = true
  282. client.stateMutex.Unlock()
  283. if alreadyRegistered {
  284. return
  285. }
  286. // apply resume details if we're able to.
  287. client.TryResume()
  288. // finish registration
  289. client.updateNickMask("")
  290. client.server.monitorManager.AlertAbout(client, true)
  291. }
  292. // TryResume tries to resume if the client asked us to.
  293. func (client *Client) TryResume() {
  294. if client.resumeDetails == nil {
  295. return
  296. }
  297. server := client.server
  298. // just grab these mutexes for safety. later we can work out whether we can grab+release them earlier
  299. server.clients.Lock()
  300. defer server.clients.Unlock()
  301. server.channels.Lock()
  302. defer server.channels.Unlock()
  303. oldnick := client.resumeDetails.OldNick
  304. timestamp := client.resumeDetails.Timestamp
  305. var timestampString string
  306. if timestamp != nil {
  307. timestampString = timestamp.UTC().Format("2006-01-02T15:04:05.999Z")
  308. }
  309. // can't use server.clients.Get since we hold server.clients' tier 1 mutex
  310. casefoldedName, err := CasefoldName(oldnick)
  311. if err != nil {
  312. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  313. return
  314. }
  315. oldClient := server.clients.byNick[casefoldedName]
  316. if oldClient == nil {
  317. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  318. return
  319. }
  320. oldAccountName := oldClient.Account()
  321. newAccountName := client.Account()
  322. if oldAccountName == "" || newAccountName == "" || oldAccountName != newAccountName {
  323. 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"))
  324. return
  325. }
  326. if !oldClient.HasMode(modes.TLS) || !client.HasMode(modes.TLS) {
  327. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  328. return
  329. }
  330. // unmark the new client's nick as being occupied
  331. server.clients.removeInternal(client)
  332. // send RESUMED to the reconnecting client
  333. if timestamp == nil {
  334. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  335. } else {
  336. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  337. }
  338. // send QUIT/RESUMED to friends
  339. for friend := range oldClient.Friends() {
  340. if friend.capabilities.Has(caps.Resume) {
  341. if timestamp == nil {
  342. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  343. } else {
  344. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  345. }
  346. } else {
  347. friend.Send(nil, oldClient.NickMaskString(), "QUIT", friend.t("Client reconnected"))
  348. }
  349. }
  350. // apply old client's details to new client
  351. client.nick = oldClient.nick
  352. client.updateNickMaskNoMutex()
  353. rejoinChannel := func(channel *Channel) {
  354. channel.joinPartMutex.Lock()
  355. defer channel.joinPartMutex.Unlock()
  356. channel.stateMutex.Lock()
  357. client.channels[channel] = true
  358. client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
  359. oldModeSet := channel.members[oldClient]
  360. channel.members.Remove(oldClient)
  361. channel.members[client] = oldModeSet
  362. channel.stateMutex.Unlock()
  363. channel.regenerateMembersCache()
  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. }
  389. for channel := range oldClient.channels {
  390. rejoinChannel(channel)
  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. return "+" + client.flags.String()
  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. nick := client.Nick()
  536. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  537. length := len(cachedTokenLine) + 2
  538. tokenline := make([]string, length)
  539. tokenline[0] = nick
  540. copy(tokenline[1:], cachedTokenLine)
  541. tokenline[length-1] = translatedISupport
  542. rb.Add(nil, client.server.name, RPL_ISUPPORT, 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. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  578. // a lot of RAM, so limit concurrency to avoid thrashing
  579. client.server.semaphores.ClientDestroy.Acquire()
  580. defer client.server.semaphores.ClientDestroy.Release()
  581. if beingResumed {
  582. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  583. } else {
  584. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  585. }
  586. // send quit/error message to client if they haven't been sent already
  587. client.Quit("Connection closed")
  588. if !beingResumed {
  589. client.server.whoWas.Append(client.WhoWas())
  590. }
  591. // remove from connection limits
  592. ipaddr := client.IP()
  593. // this check shouldn't be required but eh
  594. if ipaddr != nil {
  595. client.server.connectionLimiter.RemoveClient(ipaddr)
  596. }
  597. // alert monitors
  598. client.server.monitorManager.AlertAbout(client, false)
  599. // clean up monitor state
  600. client.server.monitorManager.RemoveAll(client)
  601. // clean up channels
  602. friends := make(ClientSet)
  603. for _, channel := range client.Channels() {
  604. if !beingResumed {
  605. channel.Quit(client)
  606. }
  607. for _, member := range channel.Members() {
  608. friends.Add(member)
  609. }
  610. }
  611. friends.Remove(client)
  612. // clean up server
  613. if !beingResumed {
  614. client.server.clients.Remove(client)
  615. }
  616. // clean up self
  617. client.idletimer.Stop()
  618. client.nickTimer.Stop()
  619. client.server.accounts.Logout(client)
  620. client.socket.Close()
  621. // send quit messages to friends
  622. if !beingResumed {
  623. client.server.stats.ChangeTotal(-1)
  624. if client.HasMode(modes.Invisible) {
  625. client.server.stats.ChangeInvisible(-1)
  626. }
  627. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  628. client.server.stats.ChangeOperators(-1)
  629. }
  630. for friend := range friends {
  631. if client.quitMessage == "" {
  632. client.quitMessage = "Exited"
  633. }
  634. friend.Send(nil, client.nickMaskString, "QUIT", client.quitMessage)
  635. }
  636. }
  637. if !client.exitedSnomaskSent {
  638. if beingResumed {
  639. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  640. } else {
  641. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  642. }
  643. }
  644. }
  645. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  646. // Adds account-tag to the line as well.
  647. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
  648. if client.capabilities.Has(caps.MaxLine) {
  649. client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
  650. } else {
  651. for _, str := range message.For512 {
  652. client.SendFromClient(msgid, from, tags, command, target, str)
  653. }
  654. }
  655. }
  656. // SendFromClient sends an IRC line coming from a specific client.
  657. // Adds account-tag to the line as well.
  658. func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  659. // attach account-tag
  660. if client.capabilities.Has(caps.AccountTag) && from.LoggedIntoAccount() {
  661. if tags == nil {
  662. tags = ircmsg.MakeTags("account", from.AccountName())
  663. } else {
  664. (*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
  665. }
  666. }
  667. // attach message-id
  668. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  669. if tags == nil {
  670. tags = ircmsg.MakeTags("draft/msgid", msgid)
  671. } else {
  672. (*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
  673. }
  674. }
  675. return client.Send(tags, from.nickMaskString, command, params...)
  676. }
  677. var (
  678. // these are all the output commands that MUST have their last param be a trailing.
  679. // this is needed because dumb clients like to treat trailing params separately from the
  680. // other params in messages.
  681. commandsThatMustUseTrailing = map[string]bool{
  682. "PRIVMSG": true,
  683. "NOTICE": true,
  684. RPL_WHOISCHANNELS: true,
  685. RPL_USERHOST: true,
  686. }
  687. )
  688. // SendRawMessage sends a raw message to the client.
  689. func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
  690. // use dumb hack to force the last param to be a trailing param if required
  691. var usedTrailingHack bool
  692. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  693. lastParam := message.Params[len(message.Params)-1]
  694. // to force trailing, we ensure the final param contains a space
  695. if !strings.Contains(lastParam, " ") {
  696. message.Params[len(message.Params)-1] = lastParam + " "
  697. usedTrailingHack = true
  698. }
  699. }
  700. // assemble message
  701. maxlenTags, maxlenRest := client.maxlens()
  702. line, err := message.LineMaxLen(maxlenTags, maxlenRest)
  703. if err != nil {
  704. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  705. client.server.logger.Error("internal", logline)
  706. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  707. line, _ := message.Line()
  708. client.socket.Write(line)
  709. return err
  710. }
  711. // if we used the trailing hack, we need to strip the final space we appended earlier on
  712. if usedTrailingHack {
  713. line = line[:len(line)-3] + "\r\n"
  714. }
  715. client.server.logger.Debug("useroutput", client.nick, " ->", strings.TrimRight(line, "\r\n"))
  716. client.socket.Write(line)
  717. return nil
  718. }
  719. // Send sends an IRC line to the client.
  720. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  721. // attach server-time
  722. if client.capabilities.Has(caps.ServerTime) {
  723. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  724. if tags == nil {
  725. tags = ircmsg.MakeTags("time", t)
  726. } else {
  727. (*tags)["time"] = ircmsg.MakeTagValue(t)
  728. }
  729. }
  730. // send out the message
  731. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  732. client.SendRawMessage(message)
  733. return nil
  734. }
  735. // Notice sends the client a notice from the server.
  736. func (client *Client) Notice(text string) {
  737. limit := 400
  738. if client.capabilities.Has(caps.MaxLine) {
  739. limit = client.server.Limits().LineLen.Rest - 110
  740. }
  741. lines := wordWrap(text, limit)
  742. // force blank lines to be sent if we receive them
  743. if len(lines) == 0 {
  744. lines = []string{""}
  745. }
  746. for _, line := range lines {
  747. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  748. }
  749. }
  750. func (client *Client) addChannel(channel *Channel) {
  751. client.stateMutex.Lock()
  752. client.channels[channel] = true
  753. client.stateMutex.Unlock()
  754. }
  755. func (client *Client) removeChannel(channel *Channel) {
  756. client.stateMutex.Lock()
  757. delete(client.channels, channel)
  758. client.stateMutex.Unlock()
  759. }