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

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