You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 23KB

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