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

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