您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

client.go 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. flags map[modes.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. nickTimer *NickTimer
  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: caps.NoneState,
  88. capVersion: caps.Cap301,
  89. channels: make(ChannelSet),
  90. ctime: now,
  91. flags: make(map[modes.Mode]bool),
  92. server: server,
  93. socket: &socket,
  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[modes.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 && !utils.AddrIsUnix(conn.RemoteAddr()) {
  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 != nil {
  138. return client.proxiedIP
  139. }
  140. if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
  141. return ip
  142. }
  143. // unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
  144. return LoopbackIP
  145. }
  146. // IPString returns the IP address of this client as a string.
  147. func (client *Client) IPString() string {
  148. ip := client.IP().String()
  149. if 0 < len(ip) && ip[0] == ':' {
  150. ip = "0" + ip
  151. }
  152. return ip
  153. }
  154. //
  155. // command goroutine
  156. //
  157. func (client *Client) recomputeMaxlens() (int, int) {
  158. maxlenTags := 512
  159. maxlenRest := 512
  160. if client.capabilities.Has(caps.MessageTags) {
  161. maxlenTags = 4096
  162. }
  163. if client.capabilities.Has(caps.MaxLine) {
  164. limits := client.server.Limits()
  165. if limits.LineLen.Tags > maxlenTags {
  166. maxlenTags = limits.LineLen.Tags
  167. }
  168. maxlenRest = limits.LineLen.Rest
  169. }
  170. atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
  171. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  172. return maxlenTags, maxlenRest
  173. }
  174. // allow these negotiated length limits to be read without locks; this is a convenience
  175. // so that Client.Send doesn't have to acquire any Client locks
  176. func (client *Client) maxlens() (int, int) {
  177. return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
  178. }
  179. func (client *Client) run() {
  180. var err error
  181. var isExiting bool
  182. var line string
  183. var msg ircmsg.IrcMessage
  184. defer func() {
  185. if r := recover(); r != nil {
  186. client.server.logger.Error("internal",
  187. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  188. if client.server.RecoverFromErrors() {
  189. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  190. } else {
  191. panic(r)
  192. }
  193. }
  194. // ensure client connection gets closed
  195. client.destroy(false)
  196. }()
  197. client.idletimer = NewIdleTimer(client)
  198. client.idletimer.Start()
  199. client.nickTimer = NewNickTimer(client)
  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.updateNickMask("")
  267. client.server.monitorManager.AlertAbout(client, true)
  268. }
  269. // TryResume tries to resume if the client asked us to.
  270. func (client *Client) TryResume() {
  271. if client.resumeDetails == nil {
  272. return
  273. }
  274. server := client.server
  275. // just grab these mutexes for safety. later we can work out whether we can grab+release them earlier
  276. server.clients.Lock()
  277. defer server.clients.Unlock()
  278. server.channels.Lock()
  279. defer server.channels.Unlock()
  280. oldnick := client.resumeDetails.OldNick
  281. timestamp := client.resumeDetails.Timestamp
  282. var timestampString string
  283. if timestamp != nil {
  284. timestampString = timestamp.UTC().Format("2006-01-02T15:04:05.999Z")
  285. }
  286. // can't use server.clients.Get since we hold server.clients' tier 1 mutex
  287. casefoldedName, err := CasefoldName(oldnick)
  288. if err != nil {
  289. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  290. return
  291. }
  292. oldClient := server.clients.byNick[casefoldedName]
  293. if oldClient == nil {
  294. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old client not found"))
  295. return
  296. }
  297. oldAccountName := oldClient.Account()
  298. newAccountName := client.Account()
  299. if oldAccountName == "" || newAccountName == "" || oldAccountName != newAccountName {
  300. 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"))
  301. return
  302. }
  303. if !oldClient.HasMode(modes.TLS) || !client.HasMode(modes.TLS) {
  304. client.Send(nil, server.name, ERR_CANNOT_RESUME, oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  305. return
  306. }
  307. // unmark the new client's nick as being occupied
  308. server.clients.removeInternal(client)
  309. // send RESUMED to the reconnecting client
  310. if timestamp == nil {
  311. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  312. } else {
  313. client.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  314. }
  315. // send QUIT/RESUMED to friends
  316. for friend := range oldClient.Friends() {
  317. if friend.capabilities.Has(caps.Resume) {
  318. if timestamp == nil {
  319. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname())
  320. } else {
  321. friend.Send(nil, oldClient.NickMaskString(), "RESUMED", oldClient.nick, client.username, client.Hostname(), timestampString)
  322. }
  323. } else {
  324. friend.Send(nil, oldClient.NickMaskString(), "QUIT", friend.t("Client reconnected"))
  325. }
  326. }
  327. // apply old client's details to new client
  328. client.nick = oldClient.nick
  329. client.updateNickMaskNoMutex()
  330. for channel := range oldClient.channels {
  331. channel.stateMutex.Lock()
  332. client.channels[channel] = true
  333. client.resumeDetails.SendFakeJoinsFor = append(client.resumeDetails.SendFakeJoinsFor, channel.name)
  334. oldModeSet := channel.members[oldClient]
  335. channel.members.Remove(oldClient)
  336. channel.members[client] = oldModeSet
  337. channel.regenerateMembersCache(true)
  338. // construct fake modestring if necessary
  339. oldModes := oldModeSet.String()
  340. var params []string
  341. if 0 < len(oldModes) {
  342. params = []string{channel.name, "+" + oldModes}
  343. for range oldModes {
  344. params = append(params, client.nick)
  345. }
  346. }
  347. // send join for old clients
  348. for member := range channel.members {
  349. if member.capabilities.Has(caps.Resume) {
  350. continue
  351. }
  352. if member.capabilities.Has(caps.ExtendedJoin) {
  353. member.Send(nil, client.nickMaskString, "JOIN", channel.name, client.AccountName(), client.realname)
  354. } else {
  355. member.Send(nil, client.nickMaskString, "JOIN", channel.name)
  356. }
  357. // send fake modestring if necessary
  358. if 0 < len(oldModes) {
  359. member.Send(nil, server.name, "MODE", params...)
  360. }
  361. }
  362. channel.stateMutex.Unlock()
  363. }
  364. server.clients.byNick[oldnick] = client
  365. oldClient.destroy(true)
  366. }
  367. // IdleTime returns how long this client's been idle.
  368. func (client *Client) IdleTime() time.Duration {
  369. client.stateMutex.RLock()
  370. defer client.stateMutex.RUnlock()
  371. return time.Since(client.atime)
  372. }
  373. // SignonTime returns this client's signon time as a unix timestamp.
  374. func (client *Client) SignonTime() int64 {
  375. return client.ctime.Unix()
  376. }
  377. // IdleSeconds returns the number of seconds this client's been idle.
  378. func (client *Client) IdleSeconds() uint64 {
  379. return uint64(client.IdleTime().Seconds())
  380. }
  381. // HasNick returns true if the client's nickname is set (used in registration).
  382. func (client *Client) HasNick() bool {
  383. client.stateMutex.RLock()
  384. defer client.stateMutex.RUnlock()
  385. return client.nick != "" && client.nick != "*"
  386. }
  387. // HasUsername returns true if the client's username is set (used in registration).
  388. func (client *Client) HasUsername() bool {
  389. client.stateMutex.RLock()
  390. defer client.stateMutex.RUnlock()
  391. return client.username != "" && client.username != "*"
  392. }
  393. // HasRoleCapabs returns true if client has the given (role) capabilities.
  394. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  395. if client.class == nil {
  396. return false
  397. }
  398. for _, capab := range capabs {
  399. if !client.class.Capabilities[capab] {
  400. return false
  401. }
  402. }
  403. return true
  404. }
  405. // ModeString returns the mode string for this client.
  406. func (client *Client) ModeString() (str string) {
  407. str = "+"
  408. for flag := range client.flags {
  409. str += flag.String()
  410. }
  411. return
  412. }
  413. // Friends refers to clients that share a channel with this client.
  414. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  415. friends := make(ClientSet)
  416. // make sure that I have the right caps
  417. hasCaps := true
  418. for _, capab := range capabs {
  419. if !client.capabilities.Has(capab) {
  420. hasCaps = false
  421. break
  422. }
  423. }
  424. if hasCaps {
  425. friends.Add(client)
  426. }
  427. for _, channel := range client.Channels() {
  428. for _, member := range channel.Members() {
  429. // make sure they have all the required caps
  430. hasCaps = true
  431. for _, capab := range capabs {
  432. if !member.capabilities.Has(capab) {
  433. hasCaps = false
  434. break
  435. }
  436. }
  437. if hasCaps {
  438. friends.Add(member)
  439. }
  440. }
  441. }
  442. return friends
  443. }
  444. // updateNick updates `nick` and `nickCasefolded`.
  445. func (client *Client) updateNick(nick string) {
  446. casefoldedName, err := CasefoldName(nick)
  447. if err != nil {
  448. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
  449. debug.PrintStack()
  450. }
  451. client.stateMutex.Lock()
  452. client.nick = nick
  453. client.nickCasefolded = casefoldedName
  454. client.stateMutex.Unlock()
  455. }
  456. // updateNickMask updates the casefolded nickname and nickmask.
  457. func (client *Client) updateNickMask(nick string) {
  458. // on "", just regenerate the nickmask etc.
  459. // otherwise, update the actual nick
  460. if nick != "" {
  461. client.updateNick(nick)
  462. }
  463. client.stateMutex.Lock()
  464. defer client.stateMutex.Unlock()
  465. client.updateNickMaskNoMutex()
  466. }
  467. // updateNickMask updates the casefolded nickname and nickmask, not holding any mutexes.
  468. func (client *Client) updateNickMaskNoMutex() {
  469. if len(client.vhost) > 0 {
  470. client.hostname = client.vhost
  471. } else {
  472. client.hostname = client.rawHostname
  473. }
  474. nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  475. nickMaskCasefolded, err := Casefold(nickMaskString)
  476. if err != nil {
  477. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
  478. debug.PrintStack()
  479. }
  480. client.nickMaskString = nickMaskString
  481. client.nickMaskCasefolded = nickMaskCasefolded
  482. }
  483. // AllNickmasks returns all the possible nickmasks for the client.
  484. func (client *Client) AllNickmasks() []string {
  485. var masks []string
  486. var mask string
  487. var err error
  488. if len(client.vhost) > 0 {
  489. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.vhost))
  490. if err == nil {
  491. masks = append(masks, mask)
  492. }
  493. }
  494. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.rawHostname))
  495. if err == nil {
  496. masks = append(masks, mask)
  497. }
  498. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.IPString()))
  499. if err == nil && mask2 != mask {
  500. masks = append(masks, mask2)
  501. }
  502. return masks
  503. }
  504. // LoggedIntoAccount returns true if this client is logged into an account.
  505. func (client *Client) LoggedIntoAccount() bool {
  506. return client.Account() != ""
  507. }
  508. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  509. func (client *Client) RplISupport(rb *ResponseBuffer) {
  510. translatedISupport := client.t("are supported by this server")
  511. for _, tokenline := range client.server.ISupport().CachedReply {
  512. // ugly trickery ahead
  513. tokenline = append(tokenline, translatedISupport)
  514. rb.Add(nil, client.server.name, RPL_ISUPPORT, append([]string{client.nick}, tokenline...)...)
  515. }
  516. }
  517. // Quit sets the given quit message for the client and tells the client to quit out.
  518. func (client *Client) Quit(message string) {
  519. client.stateMutex.Lock()
  520. alreadyQuit := client.isQuitting
  521. if !alreadyQuit {
  522. client.isQuitting = true
  523. client.quitMessage = message
  524. }
  525. client.stateMutex.Unlock()
  526. if alreadyQuit {
  527. return
  528. }
  529. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  530. quitLine, _ := quitMsg.Line()
  531. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  532. errorLine, _ := errorMsg.Line()
  533. client.socket.SetFinalData(quitLine + errorLine)
  534. }
  535. // destroy gets rid of a client, removes them from server lists etc.
  536. func (client *Client) destroy(beingResumed bool) {
  537. // allow destroy() to execute at most once
  538. if !beingResumed {
  539. client.stateMutex.Lock()
  540. }
  541. isDestroyed := client.isDestroyed
  542. client.isDestroyed = true
  543. if !beingResumed {
  544. client.stateMutex.Unlock()
  545. }
  546. if isDestroyed {
  547. return
  548. }
  549. if beingResumed {
  550. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  551. } else {
  552. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  553. }
  554. // send quit/error message to client if they haven't been sent already
  555. client.Quit("Connection closed")
  556. friends := client.Friends()
  557. friends.Remove(client)
  558. if !beingResumed {
  559. client.server.whoWas.Append(client)
  560. }
  561. // remove from connection limits
  562. ipaddr := client.IP()
  563. // this check shouldn't be required but eh
  564. if ipaddr != nil {
  565. client.server.connectionLimiter.RemoveClient(ipaddr)
  566. }
  567. // alert monitors
  568. client.server.monitorManager.AlertAbout(client, false)
  569. // clean up monitor state
  570. client.server.monitorManager.RemoveAll(client)
  571. // clean up channels
  572. for _, channel := range client.Channels() {
  573. if !beingResumed {
  574. channel.Quit(client)
  575. }
  576. for _, member := range channel.Members() {
  577. friends.Add(member)
  578. }
  579. }
  580. // clean up server
  581. if !beingResumed {
  582. client.server.clients.Remove(client)
  583. }
  584. // clean up self
  585. if client.idletimer != nil {
  586. client.idletimer.Stop()
  587. }
  588. client.server.accounts.Logout(client)
  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) && client.LoggedIntoAccount() {
  623. if tags == nil {
  624. tags = ircmsg.MakeTags("account", from.AccountName())
  625. } else {
  626. (*tags)["account"] = ircmsg.MakeTagValue(from.AccountName())
  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 dumb clients like to treat trailing params separately 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. // SendRawMessage sends a raw message to the client.
  651. func (client *Client) SendRawMessage(message ircmsg.IrcMessage) error {
  652. // use dumb hack to force the last param to be a trailing param if required
  653. var usedTrailingHack bool
  654. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  655. lastParam := message.Params[len(message.Params)-1]
  656. // to force trailing, we ensure the final param contains a space
  657. if !strings.Contains(lastParam, " ") {
  658. message.Params[len(message.Params)-1] = lastParam + " "
  659. usedTrailingHack = true
  660. }
  661. }
  662. // assemble message
  663. maxlenTags, maxlenRest := client.maxlens()
  664. line, err := message.LineMaxLen(maxlenTags, maxlenRest)
  665. if err != nil {
  666. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  667. client.server.logger.Error("internal", logline)
  668. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  669. line, _ := message.Line()
  670. // if we used the trailing hack, we need to strip the final space we appended earlier on
  671. if usedTrailingHack {
  672. line = line[:len(line)-3] + "\r\n"
  673. }
  674. client.socket.Write(line)
  675. return err
  676. }
  677. client.server.logger.Debug("useroutput", client.nick, " ->", strings.TrimRight(line, "\r\n"))
  678. client.socket.Write(line)
  679. return nil
  680. }
  681. // Send sends an IRC line to the client.
  682. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  683. // attach server-time
  684. if client.capabilities.Has(caps.ServerTime) {
  685. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  686. if tags == nil {
  687. tags = ircmsg.MakeTags("time", t)
  688. } else {
  689. (*tags)["time"] = ircmsg.MakeTagValue(t)
  690. }
  691. }
  692. // send out the message
  693. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  694. client.SendRawMessage(message)
  695. return nil
  696. }
  697. // Notice sends the client a notice from the server.
  698. func (client *Client) Notice(text string) {
  699. limit := 400
  700. if client.capabilities.Has(caps.MaxLine) {
  701. limit = client.server.Limits().LineLen.Rest - 110
  702. }
  703. lines := wordWrap(text, limit)
  704. // force blank lines to be sent if we receive them
  705. if len(lines) == 0 {
  706. lines = []string{""}
  707. }
  708. for _, line := range lines {
  709. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  710. }
  711. }
  712. func (client *Client) addChannel(channel *Channel) {
  713. client.stateMutex.Lock()
  714. client.channels[channel] = true
  715. client.stateMutex.Unlock()
  716. }
  717. func (client *Client) removeChannel(channel *Channel) {
  718. client.stateMutex.Lock()
  719. delete(client.channels, channel)
  720. client.stateMutex.Unlock()
  721. }