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