Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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. for channel := range oldClient.channels {
  354. channel.stateMutex.Lock()
  355. client.channels[channel] = true
  356. client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
  357. oldModeSet := channel.members[oldClient]
  358. channel.members.Remove(oldClient)
  359. channel.members[client] = oldModeSet
  360. channel.regenerateMembersCache(true)
  361. // construct fake modestring if necessary
  362. oldModes := oldModeSet.String()
  363. var params []string
  364. if 0 < len(oldModes) {
  365. params = []string{channel.name, "+" + oldModes}
  366. for range oldModes {
  367. params = append(params, client.nick)
  368. }
  369. }
  370. // send join for old clients
  371. for member := range channel.members {
  372. if member.capabilities.Has(caps.Resume) {
  373. continue
  374. }
  375. if member.capabilities.Has(caps.ExtendedJoin) {
  376. member.Send(nil, client.nickMaskString, "JOIN", channel.name, client.AccountName(), client.realname)
  377. } else {
  378. member.Send(nil, client.nickMaskString, "JOIN", channel.name)
  379. }
  380. // send fake modestring if necessary
  381. if 0 < len(oldModes) {
  382. member.Send(nil, server.name, "MODE", params...)
  383. }
  384. }
  385. channel.stateMutex.Unlock()
  386. }
  387. server.clients.byNick[oldnick] = client
  388. oldClient.destroy(true)
  389. }
  390. // IdleTime returns how long this client's been idle.
  391. func (client *Client) IdleTime() time.Duration {
  392. client.stateMutex.RLock()
  393. defer client.stateMutex.RUnlock()
  394. return time.Since(client.atime)
  395. }
  396. // SignonTime returns this client's signon time as a unix timestamp.
  397. func (client *Client) SignonTime() int64 {
  398. return client.ctime.Unix()
  399. }
  400. // IdleSeconds returns the number of seconds this client's been idle.
  401. func (client *Client) IdleSeconds() uint64 {
  402. return uint64(client.IdleTime().Seconds())
  403. }
  404. // HasNick returns true if the client's nickname is set (used in registration).
  405. func (client *Client) HasNick() bool {
  406. client.stateMutex.RLock()
  407. defer client.stateMutex.RUnlock()
  408. return client.nick != "" && client.nick != "*"
  409. }
  410. // HasUsername returns true if the client's username is set (used in registration).
  411. func (client *Client) HasUsername() bool {
  412. client.stateMutex.RLock()
  413. defer client.stateMutex.RUnlock()
  414. return client.username != "" && client.username != "*"
  415. }
  416. // HasRoleCapabs returns true if client has the given (role) capabilities.
  417. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  418. if client.class == nil {
  419. return false
  420. }
  421. for _, capab := range capabs {
  422. if !client.class.Capabilities[capab] {
  423. return false
  424. }
  425. }
  426. return true
  427. }
  428. // ModeString returns the mode string for this client.
  429. func (client *Client) ModeString() (str string) {
  430. return "+" + client.flags.String()
  431. }
  432. // Friends refers to clients that share a channel with this client.
  433. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  434. friends := make(ClientSet)
  435. // make sure that I have the right caps
  436. hasCaps := true
  437. for _, capab := range capabs {
  438. if !client.capabilities.Has(capab) {
  439. hasCaps = false
  440. break
  441. }
  442. }
  443. if hasCaps {
  444. friends.Add(client)
  445. }
  446. for _, channel := range client.Channels() {
  447. for _, member := range channel.Members() {
  448. // make sure they have all the required caps
  449. hasCaps = true
  450. for _, capab := range capabs {
  451. if !member.capabilities.Has(capab) {
  452. hasCaps = false
  453. break
  454. }
  455. }
  456. if hasCaps {
  457. friends.Add(member)
  458. }
  459. }
  460. }
  461. return friends
  462. }
  463. // updateNick updates `nick` and `nickCasefolded`.
  464. func (client *Client) updateNick(nick string) {
  465. casefoldedName, err := CasefoldName(nick)
  466. if err != nil {
  467. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
  468. debug.PrintStack()
  469. }
  470. client.stateMutex.Lock()
  471. client.nick = nick
  472. client.nickCasefolded = casefoldedName
  473. client.stateMutex.Unlock()
  474. }
  475. // updateNickMask updates the casefolded nickname and nickmask.
  476. func (client *Client) updateNickMask(nick string) {
  477. // on "", just regenerate the nickmask etc.
  478. // otherwise, update the actual nick
  479. if nick != "" {
  480. client.updateNick(nick)
  481. }
  482. client.stateMutex.Lock()
  483. defer client.stateMutex.Unlock()
  484. client.updateNickMaskNoMutex()
  485. }
  486. // updateNickMask updates the casefolded nickname and nickmask, not holding any mutexes.
  487. func (client *Client) updateNickMaskNoMutex() {
  488. if len(client.vhost) > 0 {
  489. client.hostname = client.vhost
  490. } else {
  491. client.hostname = client.rawHostname
  492. }
  493. nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  494. nickMaskCasefolded, err := Casefold(nickMaskString)
  495. if err != nil {
  496. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
  497. debug.PrintStack()
  498. }
  499. client.nickMaskString = nickMaskString
  500. client.nickMaskCasefolded = nickMaskCasefolded
  501. }
  502. // AllNickmasks returns all the possible nickmasks for the client.
  503. func (client *Client) AllNickmasks() []string {
  504. var masks []string
  505. var mask string
  506. var err error
  507. if len(client.vhost) > 0 {
  508. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.vhost))
  509. if err == nil {
  510. masks = append(masks, mask)
  511. }
  512. }
  513. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.rawHostname))
  514. if err == nil {
  515. masks = append(masks, mask)
  516. }
  517. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.IPString()))
  518. if err == nil && mask2 != mask {
  519. masks = append(masks, mask2)
  520. }
  521. return masks
  522. }
  523. // LoggedIntoAccount returns true if this client is logged into an account.
  524. func (client *Client) LoggedIntoAccount() bool {
  525. return client.Account() != ""
  526. }
  527. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  528. func (client *Client) RplISupport(rb *ResponseBuffer) {
  529. translatedISupport := client.t("are supported by this server")
  530. nick := client.Nick()
  531. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  532. length := len(cachedTokenLine) + 2
  533. tokenline := make([]string, length)
  534. tokenline[0] = nick
  535. copy(tokenline[1:], cachedTokenLine)
  536. tokenline[length-1] = translatedISupport
  537. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  538. }
  539. }
  540. // Quit sets the given quit message for the client and tells the client to quit out.
  541. func (client *Client) Quit(message string) {
  542. client.stateMutex.Lock()
  543. alreadyQuit := client.isQuitting
  544. if !alreadyQuit {
  545. client.isQuitting = true
  546. client.quitMessage = message
  547. }
  548. client.stateMutex.Unlock()
  549. if alreadyQuit {
  550. return
  551. }
  552. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  553. quitLine, _ := quitMsg.Line()
  554. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  555. errorLine, _ := errorMsg.Line()
  556. client.socket.SetFinalData(quitLine + errorLine)
  557. }
  558. // destroy gets rid of a client, removes them from server lists etc.
  559. func (client *Client) destroy(beingResumed bool) {
  560. // allow destroy() to execute at most once
  561. if !beingResumed {
  562. client.stateMutex.Lock()
  563. }
  564. isDestroyed := client.isDestroyed
  565. client.isDestroyed = true
  566. if !beingResumed {
  567. client.stateMutex.Unlock()
  568. }
  569. if isDestroyed {
  570. return
  571. }
  572. if beingResumed {
  573. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  574. } else {
  575. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  576. }
  577. // send quit/error message to client if they haven't been sent already
  578. client.Quit("Connection closed")
  579. friends := client.Friends()
  580. friends.Remove(client)
  581. if !beingResumed {
  582. client.server.whoWas.Append(client)
  583. }
  584. // remove from connection limits
  585. ipaddr := client.IP()
  586. // this check shouldn't be required but eh
  587. if ipaddr != nil {
  588. client.server.connectionLimiter.RemoveClient(ipaddr)
  589. }
  590. // alert monitors
  591. client.server.monitorManager.AlertAbout(client, false)
  592. // clean up monitor state
  593. client.server.monitorManager.RemoveAll(client)
  594. // clean up channels
  595. for _, channel := range client.Channels() {
  596. if !beingResumed {
  597. channel.Quit(client)
  598. }
  599. for _, member := range channel.Members() {
  600. friends.Add(member)
  601. }
  602. }
  603. // clean up server
  604. if !beingResumed {
  605. client.server.clients.Remove(client)
  606. }
  607. // clean up self
  608. client.idletimer.Stop()
  609. client.nickTimer.Stop()
  610. client.server.accounts.Logout(client)
  611. client.socket.Close()
  612. // send quit messages to friends
  613. if !beingResumed {
  614. client.server.stats.ChangeTotal(-1)
  615. if client.HasMode(modes.Invisible) {
  616. client.server.stats.ChangeInvisible(-1)
  617. }
  618. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  619. client.server.stats.ChangeOperators(-1)
  620. }
  621. for friend := range friends {
  622. if client.quitMessage == "" {
  623. client.quitMessage = "Exited"
  624. }
  625. friend.Send(nil, client.nickMaskString, "QUIT", client.quitMessage)
  626. }
  627. }
  628. if !client.exitedSnomaskSent {
  629. if beingResumed {
  630. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  631. } else {
  632. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  633. }
  634. }
  635. }
  636. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  637. // Adds account-tag to the line as well.
  638. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
  639. if client.capabilities.Has(caps.MaxLine) {
  640. client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
  641. } else {
  642. for _, str := range message.For512 {
  643. client.SendFromClient(msgid, from, tags, command, target, str)
  644. }
  645. }
  646. }
  647. // SendFromClient sends an IRC line coming from a specific client.
  648. // Adds account-tag to the line as well.
  649. func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  650. // attach account-tag
  651. if client.capabilities.Has(caps.AccountTag) && from.LoggedIntoAccount() {
  652. if tags == nil {
  653. tags = ircmsg.MakeTags("account", from.AccountName())
  654. } else {
  655. (*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
  656. }
  657. }
  658. // attach message-id
  659. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  660. if tags == nil {
  661. tags = ircmsg.MakeTags("draft/msgid", msgid)
  662. } else {
  663. (*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
  664. }
  665. }
  666. return client.Send(tags, from.nickMaskString, command, params...)
  667. }
  668. var (
  669. // these are all the output commands that MUST have their last param be a trailing.
  670. // this is needed because dumb clients like to treat trailing params separately from the
  671. // other params in messages.
  672. commandsThatMustUseTrailing = map[string]bool{
  673. "PRIVMSG": true,
  674. "NOTICE": true,
  675. RPL_WHOISCHANNELS: true,
  676. RPL_USERHOST: true,
  677. }
  678. )
  679. // SendRawMessage sends a raw message to the client.
  680. func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
  681. // use dumb hack to force the last param to be a trailing param if required
  682. var usedTrailingHack bool
  683. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  684. lastParam := message.Params[len(message.Params)-1]
  685. // to force trailing, we ensure the final param contains a space
  686. if !strings.Contains(lastParam, " ") {
  687. message.Params[len(message.Params)-1] = lastParam + " "
  688. usedTrailingHack = true
  689. }
  690. }
  691. // assemble message
  692. maxlenTags, maxlenRest := client.maxlens()
  693. line, err := message.LineMaxLen(maxlenTags, maxlenRest)
  694. if err != nil {
  695. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  696. client.server.logger.Error("internal", logline)
  697. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  698. line, _ := message.Line()
  699. client.socket.Write(line)
  700. return err
  701. }
  702. // if we used the trailing hack, we need to strip the final space we appended earlier on
  703. if usedTrailingHack {
  704. line = line[:len(line)-3] + "\r\n"
  705. }
  706. client.server.logger.Debug("useroutput", client.nick, " ->", strings.TrimRight(line, "\r\n"))
  707. client.socket.Write(line)
  708. return nil
  709. }
  710. // Send sends an IRC line to the client.
  711. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  712. // attach server-time
  713. if client.capabilities.Has(caps.ServerTime) {
  714. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  715. if tags == nil {
  716. tags = ircmsg.MakeTags("time", t)
  717. } else {
  718. (*tags)["time"] = ircmsg.MakeTagValue(t)
  719. }
  720. }
  721. // send out the message
  722. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  723. client.SendRawMessage(message)
  724. return nil
  725. }
  726. // Notice sends the client a notice from the server.
  727. func (client *Client) Notice(text string) {
  728. limit := 400
  729. if client.capabilities.Has(caps.MaxLine) {
  730. limit = client.server.Limits().LineLen.Rest - 110
  731. }
  732. lines := wordWrap(text, limit)
  733. // force blank lines to be sent if we receive them
  734. if len(lines) == 0 {
  735. lines = []string{""}
  736. }
  737. for _, line := range lines {
  738. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  739. }
  740. }
  741. func (client *Client) addChannel(channel *Channel) {
  742. client.stateMutex.Lock()
  743. client.channels[channel] = true
  744. client.stateMutex.Unlock()
  745. }
  746. func (client *Client) removeChannel(channel *Channel) {
  747. client.stateMutex.Lock()
  748. delete(client.channels, channel)
  749. client.stateMutex.Unlock()
  750. }