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

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