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.

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