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 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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. "net"
  9. "runtime/debug"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/goshuirc/irc-go/ircfmt"
  16. "github.com/goshuirc/irc-go/ircmsg"
  17. ident "github.com/oragono/go-ident"
  18. "github.com/oragono/oragono/irc/caps"
  19. "github.com/oragono/oragono/irc/connection_limits"
  20. "github.com/oragono/oragono/irc/history"
  21. "github.com/oragono/oragono/irc/modes"
  22. "github.com/oragono/oragono/irc/sno"
  23. "github.com/oragono/oragono/irc/utils"
  24. )
  25. const (
  26. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  27. IdentTimeoutSeconds = 1.5
  28. IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
  29. )
  30. var (
  31. LoopbackIP = net.ParseIP("127.0.0.1")
  32. )
  33. // ResumeDetails is a place to stash data at various stages of
  34. // the resume process: when handling the RESUME command itself,
  35. // when completing the registration, and when rejoining channels.
  36. type ResumeDetails struct {
  37. OldClient *Client
  38. OldNick string
  39. OldNickMask string
  40. PresentedToken string
  41. Timestamp time.Time
  42. ResumedAt time.Time
  43. Channels []string
  44. HistoryIncomplete bool
  45. }
  46. // Client is an IRC client.
  47. type Client struct {
  48. account string
  49. accountName string // display name of the account: uncasefolded, '*' if not logged in
  50. atime time.Time
  51. authorized bool
  52. awayMessage string
  53. capabilities *caps.Set
  54. capState caps.State
  55. capVersion caps.Version
  56. certfp string
  57. channels ChannelSet
  58. ctime time.Time
  59. exitedSnomaskSent bool
  60. fakelag *Fakelag
  61. flags *modes.ModeSet
  62. hasQuit bool
  63. hops int
  64. hostname string
  65. idletimer *IdleTimer
  66. invitedTo map[string]bool
  67. isDestroyed bool
  68. isQuitting bool
  69. languages []string
  70. loginThrottle connection_limits.GenericThrottle
  71. maxlenTags uint32
  72. maxlenRest uint32
  73. nick string
  74. nickCasefolded string
  75. nickMaskCasefolded string
  76. nickMaskString string // cache for nickmask string since it's used with lots of replies
  77. nickTimer *NickTimer
  78. oper *Oper
  79. preregNick string
  80. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  81. quitMessage string
  82. rawHostname string
  83. realname string
  84. registered bool
  85. resumeDetails *ResumeDetails
  86. resumeToken string
  87. saslInProgress bool
  88. saslMechanism string
  89. saslValue string
  90. server *Server
  91. socket *Socket
  92. stateMutex sync.RWMutex // tier 1
  93. username string
  94. vhost string
  95. history *history.Buffer
  96. }
  97. // WhoWas is the subset of client details needed to answer a WHOWAS query
  98. type WhoWas struct {
  99. nick string
  100. nickCasefolded string
  101. username string
  102. hostname string
  103. realname string
  104. }
  105. // ClientDetails is a standard set of details about a client
  106. type ClientDetails struct {
  107. WhoWas
  108. nickMask string
  109. nickMaskCasefolded string
  110. account string
  111. accountName string
  112. }
  113. // NewClient sets up a new client and starts its goroutine.
  114. func NewClient(server *Server, conn net.Conn, isTLS bool) {
  115. now := time.Now()
  116. config := server.Config()
  117. fullLineLenLimit := config.Limits.LineLen.Tags + config.Limits.LineLen.Rest
  118. socket := NewSocket(conn, fullLineLenLimit*2, config.Server.MaxSendQBytes)
  119. client := &Client{
  120. atime: now,
  121. authorized: server.Password() == nil,
  122. capabilities: caps.NewSet(),
  123. capState: caps.NoneState,
  124. capVersion: caps.Cap301,
  125. channels: make(ChannelSet),
  126. ctime: now,
  127. flags: modes.NewModeSet(),
  128. loginThrottle: connection_limits.GenericThrottle{
  129. Duration: config.Accounts.LoginThrottling.Duration,
  130. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  131. },
  132. server: server,
  133. socket: socket,
  134. accountName: "*",
  135. nick: "*", // * is used until actual nick is given
  136. nickCasefolded: "*",
  137. nickMaskString: "*", // * is used until actual nick is given
  138. history: history.NewHistoryBuffer(config.History.ClientLength),
  139. }
  140. client.languages = server.languages.Default()
  141. client.recomputeMaxlens()
  142. if isTLS {
  143. client.SetMode(modes.TLS, true)
  144. // error is not useful to us here anyways so we can ignore it
  145. client.certfp, _ = client.socket.CertFP()
  146. }
  147. if config.Server.CheckIdent && !utils.AddrIsUnix(conn.RemoteAddr()) {
  148. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  149. if err != nil {
  150. server.logger.Error("internal", "bad server address", err.Error())
  151. return
  152. }
  153. serverPort, _ := strconv.Atoi(serverPortString)
  154. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  155. if err != nil {
  156. server.logger.Error("internal", "bad client address", err.Error())
  157. return
  158. }
  159. clientPort, _ := strconv.Atoi(clientPortString)
  160. client.Notice(client.t("*** Looking up your username"))
  161. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  162. if err == nil {
  163. username := resp.Identifier
  164. _, err := CasefoldName(username) // ensure it's a valid username
  165. if err == nil {
  166. client.Notice(client.t("*** Found your username"))
  167. client.username = username
  168. // we don't need to updateNickMask here since nickMask is not used for anything yet
  169. } else {
  170. client.Notice(client.t("*** Got a malformed username, ignoring"))
  171. }
  172. } else {
  173. client.Notice(client.t("*** Could not find your username"))
  174. }
  175. }
  176. go client.run()
  177. }
  178. func (client *Client) resetFakelag() {
  179. fakelag := func() *Fakelag {
  180. if client.HasRoleCapabs("nofakelag") {
  181. return nil
  182. }
  183. flc := client.server.FakelagConfig()
  184. if !flc.Enabled {
  185. return nil
  186. }
  187. return NewFakelag(flc.Window, flc.BurstLimit, flc.MessagesPerWindow, flc.Cooldown)
  188. }()
  189. client.stateMutex.Lock()
  190. defer client.stateMutex.Unlock()
  191. client.fakelag = fakelag
  192. }
  193. // IP returns the IP address of this client.
  194. func (client *Client) IP() net.IP {
  195. if client.proxiedIP != nil {
  196. return client.proxiedIP
  197. }
  198. if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
  199. return ip
  200. }
  201. // unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
  202. return LoopbackIP
  203. }
  204. // IPString returns the IP address of this client as a string.
  205. func (client *Client) IPString() string {
  206. ip := client.IP().String()
  207. if 0 < len(ip) && ip[0] == ':' {
  208. ip = "0" + ip
  209. }
  210. return ip
  211. }
  212. //
  213. // command goroutine
  214. //
  215. func (client *Client) recomputeMaxlens() (int, int) {
  216. maxlenTags := 512
  217. maxlenRest := 512
  218. if client.capabilities.Has(caps.MessageTags) {
  219. maxlenTags = 4096
  220. }
  221. if client.capabilities.Has(caps.MaxLine) {
  222. limits := client.server.Limits()
  223. if limits.LineLen.Tags > maxlenTags {
  224. maxlenTags = limits.LineLen.Tags
  225. }
  226. maxlenRest = limits.LineLen.Rest
  227. }
  228. atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
  229. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  230. return maxlenTags, maxlenRest
  231. }
  232. // allow these negotiated length limits to be read without locks; this is a convenience
  233. // so that Client.Send doesn't have to acquire any Client locks
  234. func (client *Client) maxlens() (int, int) {
  235. return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
  236. }
  237. func (client *Client) run() {
  238. var err error
  239. var isExiting bool
  240. var line string
  241. var msg ircmsg.IrcMessage
  242. defer func() {
  243. if r := recover(); r != nil {
  244. client.server.logger.Error("internal",
  245. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  246. if client.server.RecoverFromErrors() {
  247. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  248. } else {
  249. panic(r)
  250. }
  251. }
  252. // ensure client connection gets closed
  253. client.destroy(false)
  254. }()
  255. client.idletimer = NewIdleTimer(client)
  256. client.idletimer.Start()
  257. client.nickTimer = NewNickTimer(client)
  258. client.resetFakelag()
  259. // Set the hostname for this client
  260. // (may be overridden by a later PROXY command from stunnel)
  261. client.rawHostname = utils.AddrLookupHostname(client.socket.conn.RemoteAddr())
  262. firstLine := true
  263. for {
  264. maxlenTags, maxlenRest := client.recomputeMaxlens()
  265. line, err = client.socket.Read()
  266. if err != nil {
  267. quitMessage := "connection closed"
  268. if err == errReadQ {
  269. quitMessage = "readQ exceeded"
  270. }
  271. client.Quit(quitMessage)
  272. break
  273. }
  274. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  275. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  276. if firstLine {
  277. firstLine = false
  278. if strings.HasPrefix(line, "PROXY") {
  279. err = handleProxyCommand(client.server, client, line)
  280. if err != nil {
  281. break
  282. } else {
  283. continue
  284. }
  285. }
  286. }
  287. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  288. if err == ircmsg.ErrorLineIsEmpty {
  289. continue
  290. } else if err != nil {
  291. client.Quit(client.t("Received malformed line"))
  292. break
  293. }
  294. cmd, exists := Commands[msg.Command]
  295. if !exists {
  296. if len(msg.Command) > 0 {
  297. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
  298. } else {
  299. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
  300. }
  301. continue
  302. }
  303. isExiting = cmd.Run(client.server, client, msg)
  304. if isExiting || client.isQuitting {
  305. break
  306. }
  307. }
  308. }
  309. //
  310. // idle, quit, timers and timeouts
  311. //
  312. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  313. func (client *Client) Active() {
  314. client.stateMutex.Lock()
  315. defer client.stateMutex.Unlock()
  316. client.atime = time.Now()
  317. }
  318. // Ping sends the client a PING message.
  319. func (client *Client) Ping() {
  320. client.Send(nil, "", "PING", client.nick)
  321. }
  322. // Register sets the client details as appropriate when entering the network.
  323. func (client *Client) Register() {
  324. client.stateMutex.Lock()
  325. alreadyRegistered := client.registered
  326. client.registered = true
  327. client.stateMutex.Unlock()
  328. if alreadyRegistered {
  329. return
  330. }
  331. // apply resume details if we're able to.
  332. client.TryResume()
  333. // finish registration
  334. client.updateNickMask("")
  335. client.server.monitorManager.AlertAbout(client, true)
  336. }
  337. // TryResume tries to resume if the client asked us to.
  338. func (client *Client) TryResume() {
  339. if client.resumeDetails == nil {
  340. return
  341. }
  342. server := client.server
  343. config := server.Config()
  344. oldnick := client.resumeDetails.OldNick
  345. timestamp := client.resumeDetails.Timestamp
  346. var timestampString string
  347. if !timestamp.IsZero() {
  348. timestampString = timestamp.UTC().Format(IRCv3TimestampFormat)
  349. }
  350. oldClient := server.clients.Get(oldnick)
  351. if oldClient == nil {
  352. client.Send(nil, server.name, "RESUME", "ERR", oldnick, client.t("Cannot resume connection, old client not found"))
  353. client.resumeDetails = nil
  354. return
  355. }
  356. oldNick := oldClient.Nick()
  357. oldNickmask := oldClient.NickMaskString()
  358. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  359. if !resumeAllowed {
  360. client.Send(nil, server.name, "RESUME", "ERR", oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  361. client.resumeDetails = nil
  362. return
  363. }
  364. oldResumeToken := oldClient.ResumeToken()
  365. if oldResumeToken == "" || !utils.SecretTokensMatch(oldResumeToken, client.resumeDetails.PresentedToken) {
  366. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection, invalid resume token"))
  367. client.resumeDetails = nil
  368. return
  369. }
  370. err := server.clients.Resume(client, oldClient)
  371. if err != nil {
  372. client.resumeDetails = nil
  373. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection"))
  374. return
  375. }
  376. // this is a bit racey
  377. client.resumeDetails.ResumedAt = time.Now()
  378. client.nickTimer.Touch()
  379. // resume successful, proceed to copy client state (nickname, flags, etc.)
  380. // after this, the server thinks that `newClient` owns the nickname
  381. client.resumeDetails.OldClient = oldClient
  382. // transfer monitor stuff
  383. server.monitorManager.Resume(client, oldClient)
  384. // record the names, not the pointers, of the channels,
  385. // to avoid dumb annoying race conditions
  386. channels := oldClient.Channels()
  387. client.resumeDetails.Channels = make([]string, len(channels))
  388. for i, channel := range channels {
  389. client.resumeDetails.Channels[i] = channel.Name()
  390. }
  391. username := client.Username()
  392. hostname := client.Hostname()
  393. friends := make(ClientSet)
  394. oldestLostMessage := time.Now()
  395. // work out how much time, if any, is not covered by history buffers
  396. for _, channel := range channels {
  397. for _, member := range channel.Members() {
  398. friends.Add(member)
  399. lastDiscarded := channel.history.LastDiscarded()
  400. if lastDiscarded.Before(oldestLostMessage) {
  401. oldestLostMessage = lastDiscarded
  402. }
  403. }
  404. }
  405. privmsgMatcher := func(item history.Item) bool {
  406. return item.Type == history.Privmsg || item.Type == history.Notice
  407. }
  408. privmsgHistory := oldClient.history.Match(privmsgMatcher, 0)
  409. lastDiscarded := oldClient.history.LastDiscarded()
  410. if lastDiscarded.Before(oldestLostMessage) {
  411. oldestLostMessage = lastDiscarded
  412. }
  413. for _, item := range privmsgHistory {
  414. // TODO this is the nickmask, fix that
  415. sender := server.clients.Get(item.Nick)
  416. if sender != nil {
  417. friends.Add(sender)
  418. }
  419. }
  420. gap := lastDiscarded.Sub(timestamp)
  421. client.resumeDetails.HistoryIncomplete = gap > 0
  422. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  423. // send quit/resume messages to friends
  424. for friend := range friends {
  425. if friend.capabilities.Has(caps.Resume) {
  426. if timestamp.IsZero() {
  427. friend.Send(nil, oldNickmask, "RESUMED", username, hostname)
  428. } else {
  429. friend.Send(nil, oldNickmask, "RESUMED", username, hostname, timestampString)
  430. }
  431. } else {
  432. if client.resumeDetails.HistoryIncomplete {
  433. friend.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of history lost)"), gapSeconds))
  434. } else {
  435. friend.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  436. }
  437. }
  438. }
  439. if client.resumeDetails.HistoryIncomplete {
  440. client.Send(nil, client.server.name, "RESUME", "WARN", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
  441. }
  442. client.Send(nil, client.server.name, "RESUME", "SUCCESS", oldNick)
  443. // after we send the rest of the registration burst, we'll try rejoining channels
  444. }
  445. func (client *Client) tryResumeChannels() {
  446. details := client.resumeDetails
  447. if details == nil {
  448. return
  449. }
  450. channels := make([]*Channel, len(details.Channels))
  451. for _, name := range details.Channels {
  452. channel := client.server.channels.Get(name)
  453. if channel == nil {
  454. continue
  455. }
  456. channel.Resume(client, details.OldClient, details.Timestamp)
  457. channels = append(channels, channel)
  458. }
  459. // replay direct PRIVSMG history
  460. if !details.Timestamp.IsZero() {
  461. now := time.Now()
  462. nick := client.Nick()
  463. items, complete := client.history.Between(details.Timestamp, now)
  464. for _, item := range items {
  465. var command string
  466. switch item.Type {
  467. case history.Privmsg:
  468. command = "PRIVMSG"
  469. case history.Notice:
  470. command = "NOTICE"
  471. default:
  472. continue
  473. }
  474. client.sendSplitMsgFromClientInternal(true, item.Time, item.Msgid, item.Nick, item.AccountName, nil, command, nick, item.Message)
  475. }
  476. if !complete {
  477. client.Send(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  478. }
  479. }
  480. details.OldClient.destroy(true)
  481. }
  482. // copy applicable state from oldClient to client as part of a resume
  483. func (client *Client) copyResumeData(oldClient *Client) {
  484. oldClient.stateMutex.RLock()
  485. flags := oldClient.flags
  486. history := oldClient.history
  487. nick := oldClient.nick
  488. nickCasefolded := oldClient.nickCasefolded
  489. vhost := oldClient.vhost
  490. account := oldClient.account
  491. accountName := oldClient.accountName
  492. oldClient.stateMutex.RUnlock()
  493. // copy all flags, *except* TLS (in the case that the admins enabled
  494. // resume over plaintext)
  495. hasTLS := client.flags.HasMode(modes.TLS)
  496. temp := modes.NewModeSet()
  497. temp.Copy(flags)
  498. temp.SetMode(modes.TLS, hasTLS)
  499. client.flags.Copy(temp)
  500. client.stateMutex.Lock()
  501. defer client.stateMutex.Unlock()
  502. // reuse the old client's history buffer
  503. client.history = history
  504. // copy other data
  505. client.nick = nick
  506. client.nickCasefolded = nickCasefolded
  507. client.vhost = vhost
  508. client.account = account
  509. client.accountName = accountName
  510. client.updateNickMaskNoMutex()
  511. }
  512. // IdleTime returns how long this client's been idle.
  513. func (client *Client) IdleTime() time.Duration {
  514. client.stateMutex.RLock()
  515. defer client.stateMutex.RUnlock()
  516. return time.Since(client.atime)
  517. }
  518. // SignonTime returns this client's signon time as a unix timestamp.
  519. func (client *Client) SignonTime() int64 {
  520. return client.ctime.Unix()
  521. }
  522. // IdleSeconds returns the number of seconds this client's been idle.
  523. func (client *Client) IdleSeconds() uint64 {
  524. return uint64(client.IdleTime().Seconds())
  525. }
  526. // HasNick returns true if the client's nickname is set (used in registration).
  527. func (client *Client) HasNick() bool {
  528. client.stateMutex.RLock()
  529. defer client.stateMutex.RUnlock()
  530. return client.nick != "" && client.nick != "*"
  531. }
  532. // HasUsername returns true if the client's username is set (used in registration).
  533. func (client *Client) HasUsername() bool {
  534. client.stateMutex.RLock()
  535. defer client.stateMutex.RUnlock()
  536. return client.username != "" && client.username != "*"
  537. }
  538. func (client *Client) SetNames(username, realname string) error {
  539. _, err := CasefoldName(username)
  540. if err != nil {
  541. return errInvalidUsername
  542. }
  543. client.stateMutex.Lock()
  544. defer client.stateMutex.Unlock()
  545. if client.username == "" {
  546. client.username = "~" + username
  547. }
  548. if client.realname == "" {
  549. client.realname = realname
  550. }
  551. return nil
  552. }
  553. // HasRoleCapabs returns true if client has the given (role) capabilities.
  554. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  555. oper := client.Oper()
  556. if oper == nil {
  557. return false
  558. }
  559. for _, capab := range capabs {
  560. if !oper.Class.Capabilities[capab] {
  561. return false
  562. }
  563. }
  564. return true
  565. }
  566. // ModeString returns the mode string for this client.
  567. func (client *Client) ModeString() (str string) {
  568. return "+" + client.flags.String()
  569. }
  570. // Friends refers to clients that share a channel with this client.
  571. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  572. friends := make(ClientSet)
  573. // make sure that I have the right caps
  574. hasCaps := true
  575. for _, capab := range capabs {
  576. if !client.capabilities.Has(capab) {
  577. hasCaps = false
  578. break
  579. }
  580. }
  581. if hasCaps {
  582. friends.Add(client)
  583. }
  584. for _, channel := range client.Channels() {
  585. for _, member := range channel.Members() {
  586. // make sure they have all the required caps
  587. hasCaps = true
  588. for _, capab := range capabs {
  589. if !member.capabilities.Has(capab) {
  590. hasCaps = false
  591. break
  592. }
  593. }
  594. if hasCaps {
  595. friends.Add(member)
  596. }
  597. }
  598. }
  599. return friends
  600. }
  601. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  602. // this is annoying to do correctly
  603. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  604. username := client.Username()
  605. for fClient := range client.Friends(caps.ChgHost) {
  606. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  607. }
  608. }
  609. // choose the correct vhost to display
  610. func (client *Client) getVHostNoMutex() string {
  611. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  612. if client.vhost != "" {
  613. return client.vhost
  614. } else if client.oper != nil {
  615. return client.oper.Vhost
  616. } else {
  617. return ""
  618. }
  619. }
  620. // SetVHost updates the client's hostserv-based vhost
  621. func (client *Client) SetVHost(vhost string) (updated bool) {
  622. client.stateMutex.Lock()
  623. defer client.stateMutex.Unlock()
  624. updated = (client.vhost != vhost)
  625. client.vhost = vhost
  626. if updated {
  627. client.updateNickMaskNoMutex()
  628. }
  629. return
  630. }
  631. // updateNick updates `nick` and `nickCasefolded`.
  632. func (client *Client) updateNick(nick string) {
  633. casefoldedName, err := CasefoldName(nick)
  634. if err != nil {
  635. client.server.logger.Error("internal", "nick couldn't be casefolded", nick, err.Error())
  636. return
  637. }
  638. client.stateMutex.Lock()
  639. client.nick = nick
  640. client.nickCasefolded = casefoldedName
  641. client.stateMutex.Unlock()
  642. }
  643. // updateNickMask updates the casefolded nickname and nickmask.
  644. func (client *Client) updateNickMask(nick string) {
  645. // on "", just regenerate the nickmask etc.
  646. // otherwise, update the actual nick
  647. if nick != "" {
  648. client.updateNick(nick)
  649. }
  650. client.stateMutex.Lock()
  651. defer client.stateMutex.Unlock()
  652. client.updateNickMaskNoMutex()
  653. }
  654. // updateNickMask updates the casefolded nickname and nickmask, not acquiring any mutexes.
  655. func (client *Client) updateNickMaskNoMutex() {
  656. client.hostname = client.getVHostNoMutex()
  657. if client.hostname == "" {
  658. client.hostname = client.rawHostname
  659. }
  660. nickMaskString := fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  661. nickMaskCasefolded, err := Casefold(nickMaskString)
  662. if err != nil {
  663. client.server.logger.Error("internal", "nickmask couldn't be casefolded", nickMaskString, err.Error())
  664. return
  665. }
  666. client.nickMaskString = nickMaskString
  667. client.nickMaskCasefolded = nickMaskCasefolded
  668. }
  669. // AllNickmasks returns all the possible nickmasks for the client.
  670. func (client *Client) AllNickmasks() []string {
  671. var masks []string
  672. var mask string
  673. var err error
  674. client.stateMutex.RLock()
  675. nick := client.nick
  676. username := client.username
  677. rawHostname := client.rawHostname
  678. vhost := client.getVHostNoMutex()
  679. client.stateMutex.RUnlock()
  680. if len(vhost) > 0 {
  681. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, vhost))
  682. if err == nil {
  683. masks = append(masks, mask)
  684. }
  685. }
  686. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", nick, username, rawHostname))
  687. if err == nil {
  688. masks = append(masks, mask)
  689. }
  690. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", nick, username, client.IPString()))
  691. if err == nil && mask2 != mask {
  692. masks = append(masks, mask2)
  693. }
  694. return masks
  695. }
  696. // LoggedIntoAccount returns true if this client is logged into an account.
  697. func (client *Client) LoggedIntoAccount() bool {
  698. return client.Account() != ""
  699. }
  700. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  701. func (client *Client) RplISupport(rb *ResponseBuffer) {
  702. translatedISupport := client.t("are supported by this server")
  703. nick := client.Nick()
  704. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  705. length := len(cachedTokenLine) + 2
  706. tokenline := make([]string, length)
  707. tokenline[0] = nick
  708. copy(tokenline[1:], cachedTokenLine)
  709. tokenline[length-1] = translatedISupport
  710. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  711. }
  712. }
  713. // Quit sets the given quit message for the client and tells the client to quit out.
  714. func (client *Client) Quit(message string) {
  715. client.stateMutex.Lock()
  716. alreadyQuit := client.isQuitting
  717. if !alreadyQuit {
  718. client.isQuitting = true
  719. client.quitMessage = message
  720. }
  721. client.stateMutex.Unlock()
  722. if alreadyQuit {
  723. return
  724. }
  725. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  726. quitLine, _ := quitMsg.Line()
  727. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  728. errorLine, _ := errorMsg.Line()
  729. client.socket.SetFinalData(quitLine + errorLine)
  730. }
  731. // destroy gets rid of a client, removes them from server lists etc.
  732. func (client *Client) destroy(beingResumed bool) {
  733. // allow destroy() to execute at most once
  734. client.stateMutex.Lock()
  735. isDestroyed := client.isDestroyed
  736. client.isDestroyed = true
  737. quitMessage := client.quitMessage
  738. nickMaskString := client.nickMaskString
  739. accountName := client.accountName
  740. client.stateMutex.Unlock()
  741. if isDestroyed {
  742. return
  743. }
  744. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  745. // a lot of RAM, so limit concurrency to avoid thrashing
  746. client.server.semaphores.ClientDestroy.Acquire()
  747. defer client.server.semaphores.ClientDestroy.Release()
  748. if beingResumed {
  749. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  750. } else {
  751. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  752. }
  753. // send quit/error message to client if they haven't been sent already
  754. client.Quit("Connection closed")
  755. if !beingResumed {
  756. client.server.whoWas.Append(client.WhoWas())
  757. }
  758. // remove from connection limits
  759. ipaddr := client.IP()
  760. // this check shouldn't be required but eh
  761. if ipaddr != nil {
  762. client.server.connectionLimiter.RemoveClient(ipaddr)
  763. }
  764. // alert monitors
  765. client.server.monitorManager.AlertAbout(client, false)
  766. // clean up monitor state
  767. client.server.monitorManager.RemoveAll(client)
  768. // clean up channels
  769. friends := make(ClientSet)
  770. for _, channel := range client.Channels() {
  771. if !beingResumed {
  772. channel.Quit(client)
  773. channel.history.Add(history.Item{
  774. Type: history.Quit,
  775. Nick: nickMaskString,
  776. AccountName: accountName,
  777. Message: utils.MakeSplitMessage(quitMessage, true),
  778. })
  779. }
  780. for _, member := range channel.Members() {
  781. friends.Add(member)
  782. }
  783. }
  784. friends.Remove(client)
  785. // clean up server
  786. if !beingResumed {
  787. client.server.clients.Remove(client)
  788. }
  789. // clean up self
  790. client.idletimer.Stop()
  791. client.nickTimer.Stop()
  792. client.server.accounts.Logout(client)
  793. client.socket.Close()
  794. // send quit messages to friends
  795. if !beingResumed {
  796. if client.Registered() {
  797. client.server.stats.ChangeTotal(-1)
  798. }
  799. if client.HasMode(modes.Invisible) {
  800. client.server.stats.ChangeInvisible(-1)
  801. }
  802. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  803. client.server.stats.ChangeOperators(-1)
  804. }
  805. for friend := range friends {
  806. if quitMessage == "" {
  807. quitMessage = "Exited"
  808. }
  809. friend.Send(nil, client.nickMaskString, "QUIT", quitMessage)
  810. }
  811. }
  812. if !client.exitedSnomaskSent {
  813. if beingResumed {
  814. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  815. } else {
  816. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  817. }
  818. }
  819. }
  820. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  821. // Adds account-tag to the line as well.
  822. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags Tags, command, target string, message utils.SplitMessage) {
  823. client.sendSplitMsgFromClientInternal(false, time.Time{}, msgid, from.NickMaskString(), from.AccountName(), tags, command, target, message)
  824. }
  825. func (client *Client) sendSplitMsgFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags Tags, command, target string, message utils.SplitMessage) {
  826. if client.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  827. client.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, target, message.Original)
  828. } else {
  829. for _, str := range message.Wrapped {
  830. client.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, target, str)
  831. }
  832. }
  833. }
  834. // SendFromClient sends an IRC line coming from a specific client.
  835. // Adds account-tag to the line as well.
  836. func (client *Client) SendFromClient(msgid string, from *Client, tags Tags, command string, params ...string) error {
  837. return client.sendFromClientInternal(false, time.Time{}, msgid, from.NickMaskString(), from.AccountName(), tags, command, params...)
  838. }
  839. // helper to add a tag to `tags` (or create a new tag set if the current one is nil)
  840. func ensureTag(tags Tags, tagName, tagValue string) (result Tags) {
  841. if tags == nil {
  842. result = ircmsg.MakeTags(tagName, tagValue)
  843. } else {
  844. result = tags
  845. (*tags)[tagName] = ircmsg.MakeTagValue(tagValue)
  846. }
  847. return
  848. }
  849. // XXX this is a hack where we allow overriding the client's nickmask
  850. // this is to support CHGHOST, which requires that we send the *original* nickmask with the response
  851. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags Tags, command string, params ...string) error {
  852. // attach account-tag
  853. if client.capabilities.Has(caps.AccountTag) && accountName != "*" {
  854. tags = ensureTag(tags, "account", accountName)
  855. }
  856. // attach message-id
  857. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  858. tags = ensureTag(tags, "draft/msgid", msgid)
  859. }
  860. return client.sendInternal(blocking, serverTime, tags, nickmask, command, params...)
  861. }
  862. var (
  863. // these are all the output commands that MUST have their last param be a trailing.
  864. // this is needed because dumb clients like to treat trailing params separately from the
  865. // other params in messages.
  866. commandsThatMustUseTrailing = map[string]bool{
  867. "PRIVMSG": true,
  868. "NOTICE": true,
  869. RPL_WHOISCHANNELS: true,
  870. RPL_USERHOST: true,
  871. }
  872. )
  873. // SendRawMessage sends a raw message to the client.
  874. func (client *Client) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  875. // use dumb hack to force the last param to be a trailing param if required
  876. var usedTrailingHack bool
  877. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  878. lastParam := message.Params[len(message.Params)-1]
  879. // to force trailing, we ensure the final param contains a space
  880. if !strings.Contains(lastParam, " ") {
  881. message.Params[len(message.Params)-1] = lastParam + " "
  882. usedTrailingHack = true
  883. }
  884. }
  885. // assemble message
  886. maxlenTags, maxlenRest := client.maxlens()
  887. line, err := message.LineMaxLenBytes(maxlenTags, maxlenRest)
  888. if err != nil {
  889. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  890. client.server.logger.Error("internal", logline)
  891. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  892. line, _ := message.LineBytes()
  893. if blocking {
  894. client.socket.BlockingWrite(line)
  895. } else {
  896. client.socket.Write(line)
  897. }
  898. return err
  899. }
  900. // if we used the trailing hack, we need to strip the final space we appended earlier on
  901. if usedTrailingHack {
  902. copy(line[len(line)-3:], []byte{'\r', '\n'})
  903. line = line[:len(line)-1]
  904. }
  905. if client.server.logger.IsLoggingRawIO() {
  906. logline := string(line[:len(line)-2]) // strip "\r\n"
  907. client.server.logger.Debug("useroutput", client.nick, " ->", logline)
  908. }
  909. if blocking {
  910. return client.socket.BlockingWrite(line)
  911. } else {
  912. return client.socket.Write(line)
  913. }
  914. }
  915. func (client *Client) sendInternal(blocking bool, serverTime time.Time, tags Tags, prefix string, command string, params ...string) error {
  916. // attach server time
  917. if client.capabilities.Has(caps.ServerTime) {
  918. if serverTime.IsZero() {
  919. serverTime = time.Now()
  920. }
  921. tags = ensureTag(tags, "time", serverTime.UTC().Format(IRCv3TimestampFormat))
  922. }
  923. // send out the message
  924. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  925. client.SendRawMessage(message, blocking)
  926. return nil
  927. }
  928. // Send sends an IRC line to the client.
  929. func (client *Client) Send(tags Tags, prefix string, command string, params ...string) error {
  930. return client.sendInternal(false, time.Time{}, tags, prefix, command, params...)
  931. }
  932. // Notice sends the client a notice from the server.
  933. func (client *Client) Notice(text string) {
  934. limit := 400
  935. if client.capabilities.Has(caps.MaxLine) {
  936. limit = client.server.Limits().LineLen.Rest - 110
  937. }
  938. lines := utils.WordWrap(text, limit)
  939. // force blank lines to be sent if we receive them
  940. if len(lines) == 0 {
  941. lines = []string{""}
  942. }
  943. for _, line := range lines {
  944. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  945. }
  946. }
  947. func (client *Client) addChannel(channel *Channel) {
  948. client.stateMutex.Lock()
  949. client.channels[channel] = true
  950. client.stateMutex.Unlock()
  951. }
  952. func (client *Client) removeChannel(channel *Channel) {
  953. client.stateMutex.Lock()
  954. delete(client.channels, channel)
  955. client.stateMutex.Unlock()
  956. }
  957. // Ensures the client has a cryptographically secure resume token, and returns
  958. // its value. An error is returned if a token was previously assigned.
  959. func (client *Client) generateResumeToken() (token string, err error) {
  960. newToken := utils.GenerateSecretToken()
  961. client.stateMutex.Lock()
  962. defer client.stateMutex.Unlock()
  963. if client.resumeToken == "" {
  964. client.resumeToken = newToken
  965. } else {
  966. err = errResumeTokenAlreadySet
  967. }
  968. return client.resumeToken, err
  969. }
  970. // Records that the client has been invited to join an invite-only channel
  971. func (client *Client) Invite(casefoldedChannel string) {
  972. client.stateMutex.Lock()
  973. defer client.stateMutex.Unlock()
  974. if client.invitedTo == nil {
  975. client.invitedTo = make(map[string]bool)
  976. }
  977. client.invitedTo[casefoldedChannel] = true
  978. }
  979. // Checks that the client was invited to join a given channel
  980. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  981. client.stateMutex.Lock()
  982. defer client.stateMutex.Unlock()
  983. invited = client.invitedTo[casefoldedChannel]
  984. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  985. delete(client.invitedTo, casefoldedChannel)
  986. return
  987. }