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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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. PresentedToken string
  35. Timestamp time.Time
  36. HistoryIncomplete bool
  37. }
  38. // Client is an IRC client.
  39. type Client struct {
  40. account string
  41. accountName string // display name of the account: uncasefolded, '*' if not logged in
  42. accountSettings AccountSettings
  43. atime time.Time
  44. away bool
  45. awayMessage string
  46. brbTimer BrbTimer
  47. certfp string
  48. channels ChannelSet
  49. ctime time.Time
  50. destroyed bool
  51. exitedSnomaskSent bool
  52. flags modes.ModeSet
  53. hostname string
  54. invitedTo map[string]bool
  55. isTor bool
  56. languages []string
  57. loginThrottle connection_limits.GenericThrottle
  58. nick string
  59. nickCasefolded string
  60. nickMaskCasefolded string
  61. nickMaskString string // cache for nickmask string since it's used with lots of replies
  62. nickTimer NickTimer
  63. oper *Oper
  64. preregNick string
  65. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  66. rawHostname string
  67. cloakedHostname string
  68. realname string
  69. realIP net.IP
  70. registered bool
  71. resumeID string
  72. saslInProgress bool
  73. saslMechanism string
  74. saslValue string
  75. sentPassCommand bool
  76. server *Server
  77. skeleton string
  78. sessions []*Session
  79. stateMutex sync.RWMutex // tier 1
  80. username string
  81. vhost string
  82. history history.Buffer
  83. }
  84. // Session is an individual client connection to the server (TCP connection
  85. // and associated per-connection data, such as capabilities). There is a
  86. // many-one relationship between sessions and clients.
  87. type Session struct {
  88. client *Client
  89. ctime time.Time
  90. atime time.Time
  91. socket *Socket
  92. realIP net.IP
  93. proxiedIP net.IP
  94. rawHostname string
  95. idletimer IdleTimer
  96. fakelag Fakelag
  97. destroyed uint32
  98. quitMessage string
  99. capabilities caps.Set
  100. maxlenRest uint32
  101. capState caps.State
  102. capVersion caps.Version
  103. registrationMessages int
  104. resumeID string
  105. resumeDetails *ResumeDetails
  106. zncPlaybackTimes *zncPlaybackTimes
  107. }
  108. // sets the session quit message, if there isn't one already
  109. func (sd *Session) SetQuitMessage(message string) (set bool) {
  110. if message == "" {
  111. message = "Connection closed"
  112. }
  113. if sd.quitMessage == "" {
  114. sd.quitMessage = message
  115. return true
  116. } else {
  117. return false
  118. }
  119. }
  120. // set the negotiated message length based on session capabilities
  121. func (session *Session) SetMaxlenRest() {
  122. maxlenRest := 512
  123. if session.capabilities.Has(caps.MaxLine) {
  124. maxlenRest = session.client.server.Config().Limits.LineLen.Rest
  125. }
  126. atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
  127. }
  128. // allow the negotiated message length limit to be read without locks; this is a convenience
  129. // so that Session.SendRawMessage doesn't have to acquire any Client locks
  130. func (session *Session) MaxlenRest() int {
  131. return int(atomic.LoadUint32(&session.maxlenRest))
  132. }
  133. // returns whether the session was actively destroyed (for example, by ping
  134. // timeout or NS GHOST).
  135. // avoids a race condition between asynchronous idle-timing-out of sessions,
  136. // and a condition that allows implicit BRB on connection errors (since
  137. // destroy()'s socket.Close() appears to socket.Read() as a connection error)
  138. func (session *Session) Destroyed() bool {
  139. return atomic.LoadUint32(&session.destroyed) == 1
  140. }
  141. // sets the timed-out flag
  142. func (session *Session) SetDestroyed() {
  143. atomic.StoreUint32(&session.destroyed, 1)
  144. }
  145. // WhoWas is the subset of client details needed to answer a WHOWAS query
  146. type WhoWas struct {
  147. nick string
  148. nickCasefolded string
  149. username string
  150. hostname string
  151. realname string
  152. }
  153. // ClientDetails is a standard set of details about a client
  154. type ClientDetails struct {
  155. WhoWas
  156. nickMask string
  157. nickMaskCasefolded string
  158. account string
  159. accountName string
  160. }
  161. // RunClient sets up a new client and runs its goroutine.
  162. func (server *Server) RunClient(conn clientConn) {
  163. var isBanned bool
  164. var banMsg string
  165. var realIP net.IP
  166. if conn.IsTor {
  167. realIP = utils.IPv4LoopbackAddress
  168. isBanned, banMsg = server.checkTorLimits()
  169. } else {
  170. realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
  171. isBanned, banMsg = server.checkBans(realIP)
  172. }
  173. if isBanned {
  174. // this might not show up properly on some clients,
  175. // but our objective here is just to close the connection out before it has a load impact on us
  176. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  177. conn.Conn.Close()
  178. return
  179. }
  180. server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
  181. now := time.Now().UTC()
  182. config := server.Config()
  183. fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
  184. // give them 1k of grace over the limit:
  185. socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
  186. client := &Client{
  187. atime: now,
  188. channels: make(ChannelSet),
  189. ctime: now,
  190. isTor: conn.IsTor,
  191. languages: server.Languages().Default(),
  192. loginThrottle: connection_limits.GenericThrottle{
  193. Duration: config.Accounts.LoginThrottling.Duration,
  194. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  195. },
  196. server: server,
  197. accountName: "*",
  198. nick: "*", // * is used until actual nick is given
  199. nickCasefolded: "*",
  200. nickMaskString: "*", // * is used until actual nick is given
  201. }
  202. client.history.Initialize(config.History.ClientLength)
  203. client.brbTimer.Initialize(client)
  204. session := &Session{
  205. client: client,
  206. socket: socket,
  207. capVersion: caps.Cap301,
  208. capState: caps.NoneState,
  209. ctime: now,
  210. atime: now,
  211. realIP: realIP,
  212. }
  213. session.SetMaxlenRest()
  214. client.sessions = []*Session{session}
  215. if conn.IsTLS {
  216. client.SetMode(modes.TLS, true)
  217. // error is not useful to us here anyways so we can ignore it
  218. client.certfp, _ = socket.CertFP()
  219. }
  220. if conn.IsTor {
  221. client.SetMode(modes.TLS, true)
  222. // cover up details of the tor proxying infrastructure (not a user privacy concern,
  223. // but a hardening measure):
  224. session.proxiedIP = utils.IPv4LoopbackAddress
  225. session.rawHostname = config.Server.TorListeners.Vhost
  226. } else {
  227. // set the hostname for this client (may be overridden later by PROXY or WEBIRC)
  228. session.rawHostname = utils.LookupHostname(session.realIP.String())
  229. client.cloakedHostname = config.Server.Cloaks.ComputeCloak(session.realIP)
  230. remoteAddr := conn.Conn.RemoteAddr()
  231. if utils.AddrIsLocal(remoteAddr) {
  232. // treat local connections as secure (may be overridden later by WEBIRC)
  233. client.SetMode(modes.TLS, true)
  234. }
  235. if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
  236. client.doIdentLookup(conn.Conn)
  237. }
  238. }
  239. client.realIP = session.realIP
  240. client.rawHostname = session.rawHostname
  241. client.proxiedIP = session.proxiedIP
  242. client.run(session)
  243. }
  244. func (client *Client) doIdentLookup(conn net.Conn) {
  245. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  246. if err != nil {
  247. client.server.logger.Error("internal", "bad server address", err.Error())
  248. return
  249. }
  250. serverPort, _ := strconv.Atoi(serverPortString)
  251. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  252. if err != nil {
  253. client.server.logger.Error("internal", "bad client address", err.Error())
  254. return
  255. }
  256. clientPort, _ := strconv.Atoi(clientPortString)
  257. client.Notice(client.t("*** Looking up your username"))
  258. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  259. if err == nil {
  260. err := client.SetNames(resp.Identifier, "", true)
  261. if err == nil {
  262. client.Notice(client.t("*** Found your username"))
  263. // we don't need to updateNickMask here since nickMask is not used for anything yet
  264. } else {
  265. client.Notice(client.t("*** Got a malformed username, ignoring"))
  266. }
  267. } else {
  268. client.Notice(client.t("*** Could not find your username"))
  269. }
  270. }
  271. type AuthOutcome uint
  272. const (
  273. authSuccess AuthOutcome = iota
  274. authFailPass
  275. authFailTorSaslRequired
  276. authFailSaslRequired
  277. )
  278. func (client *Client) isAuthorized(config *Config) AuthOutcome {
  279. saslSent := client.account != ""
  280. // PASS requirement
  281. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  282. return authFailPass
  283. }
  284. // Tor connections may be required to authenticate with SASL
  285. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  286. return authFailTorSaslRequired
  287. }
  288. // finally, enforce require-sasl
  289. if config.Accounts.RequireSasl.Enabled && !saslSent && !utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets) {
  290. return authFailSaslRequired
  291. }
  292. return authSuccess
  293. }
  294. func (session *Session) resetFakelag() {
  295. var flc FakelagConfig = session.client.server.Config().Fakelag
  296. flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
  297. session.fakelag.Initialize(flc)
  298. }
  299. // IP returns the IP address of this client.
  300. func (client *Client) IP() net.IP {
  301. client.stateMutex.RLock()
  302. defer client.stateMutex.RUnlock()
  303. if client.proxiedIP != nil {
  304. return client.proxiedIP
  305. }
  306. return client.realIP
  307. }
  308. // IPString returns the IP address of this client as a string.
  309. func (client *Client) IPString() string {
  310. ip := client.IP().String()
  311. if 0 < len(ip) && ip[0] == ':' {
  312. ip = "0" + ip
  313. }
  314. return ip
  315. }
  316. //
  317. // command goroutine
  318. //
  319. func (client *Client) run(session *Session) {
  320. defer func() {
  321. if r := recover(); r != nil {
  322. client.server.logger.Error("internal",
  323. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  324. if client.server.Config().Debug.recoverFromErrors {
  325. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  326. } else {
  327. panic(r)
  328. }
  329. }
  330. // ensure client connection gets closed
  331. client.destroy(session)
  332. }()
  333. session.idletimer.Initialize(session)
  334. session.resetFakelag()
  335. isReattach := client.Registered()
  336. if isReattach {
  337. if session.resumeDetails != nil {
  338. session.playResume()
  339. session.resumeDetails = nil
  340. client.brbTimer.Disable()
  341. } else {
  342. client.playReattachMessages(session)
  343. }
  344. } else {
  345. // don't reset the nick timer during a reattach
  346. client.nickTimer.Initialize(client)
  347. }
  348. firstLine := !isReattach
  349. for {
  350. maxlenRest := session.MaxlenRest()
  351. line, err := session.socket.Read()
  352. if err != nil {
  353. quitMessage := "connection closed"
  354. if err == errReadQ {
  355. quitMessage = "readQ exceeded"
  356. }
  357. client.Quit(quitMessage, session)
  358. // since the client did not actually send us a QUIT,
  359. // give them a chance to resume if applicable:
  360. if !session.Destroyed() {
  361. client.brbTimer.Enable()
  362. }
  363. break
  364. }
  365. if client.server.logger.IsLoggingRawIO() {
  366. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  367. }
  368. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  369. if firstLine {
  370. firstLine = false
  371. if strings.HasPrefix(line, "PROXY") {
  372. err = handleProxyCommand(client.server, client, session, line)
  373. if err != nil {
  374. break
  375. } else {
  376. continue
  377. }
  378. }
  379. }
  380. if client.registered {
  381. session.fakelag.Touch()
  382. } else {
  383. // DoS hardening, #505
  384. session.registrationMessages++
  385. if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
  386. client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
  387. break
  388. }
  389. }
  390. msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
  391. if err == ircmsg.ErrorLineIsEmpty {
  392. continue
  393. } else if err == ircmsg.ErrorLineTooLong {
  394. session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
  395. continue
  396. } else if err != nil {
  397. client.Quit(client.t("Received malformed line"), session)
  398. break
  399. }
  400. cmd, exists := Commands[msg.Command]
  401. if !exists {
  402. if len(msg.Command) > 0 {
  403. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
  404. } else {
  405. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
  406. }
  407. continue
  408. }
  409. isExiting := cmd.Run(client.server, client, session, msg)
  410. if isExiting {
  411. break
  412. } else if session.client != client {
  413. // bouncer reattach
  414. go session.client.run(session)
  415. break
  416. }
  417. }
  418. }
  419. func (client *Client) playReattachMessages(session *Session) {
  420. client.server.playRegistrationBurst(session)
  421. for _, channel := range session.client.Channels() {
  422. channel.playJoinForSession(session)
  423. }
  424. }
  425. //
  426. // idle, quit, timers and timeouts
  427. //
  428. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  429. func (client *Client) Active(session *Session) {
  430. now := time.Now().UTC()
  431. client.stateMutex.Lock()
  432. defer client.stateMutex.Unlock()
  433. session.atime = now
  434. client.atime = now
  435. }
  436. // Ping sends the client a PING message.
  437. func (session *Session) Ping() {
  438. session.Send(nil, "", "PING", session.client.Nick())
  439. }
  440. // tryResume tries to resume if the client asked us to.
  441. func (session *Session) tryResume() (success bool) {
  442. var oldResumeID string
  443. defer func() {
  444. if success {
  445. // "On a successful request, the server [...] terminates the old client's connection"
  446. oldSession := session.client.GetSessionByResumeID(oldResumeID)
  447. if oldSession != nil {
  448. session.client.destroy(oldSession)
  449. }
  450. } else {
  451. session.resumeDetails = nil
  452. }
  453. }()
  454. client := session.client
  455. server := client.server
  456. config := server.Config()
  457. oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
  458. if oldClient == nil {
  459. session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
  460. return
  461. }
  462. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  463. if !resumeAllowed {
  464. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
  465. return
  466. }
  467. if oldClient.isTor != client.isTor {
  468. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  469. return
  470. }
  471. err := server.clients.Resume(oldClient, session)
  472. if err != nil {
  473. session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
  474. return
  475. }
  476. success = true
  477. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
  478. return
  479. }
  480. // playResume is called from the session's fresh goroutine after a resume;
  481. // it sends notifications to friends, then plays the registration burst and replays
  482. // stored history to the session
  483. func (session *Session) playResume() {
  484. client := session.client
  485. server := client.server
  486. friends := make(ClientSet)
  487. oldestLostMessage := time.Now().UTC()
  488. // work out how much time, if any, is not covered by history buffers
  489. for _, channel := range client.Channels() {
  490. for _, member := range channel.Members() {
  491. friends.Add(member)
  492. lastDiscarded := channel.history.LastDiscarded()
  493. if lastDiscarded.Before(oldestLostMessage) {
  494. oldestLostMessage = lastDiscarded
  495. }
  496. }
  497. }
  498. privmsgMatcher := func(item history.Item) bool {
  499. return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
  500. }
  501. privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
  502. lastDiscarded := client.history.LastDiscarded()
  503. if lastDiscarded.Before(oldestLostMessage) {
  504. oldestLostMessage = lastDiscarded
  505. }
  506. for _, item := range privmsgHistory {
  507. sender := server.clients.Get(stripMaskFromNick(item.Nick))
  508. if sender != nil {
  509. friends.Add(sender)
  510. }
  511. }
  512. timestamp := session.resumeDetails.Timestamp
  513. gap := lastDiscarded.Sub(timestamp)
  514. session.resumeDetails.HistoryIncomplete = gap > 0
  515. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  516. details := client.Details()
  517. oldNickmask := details.nickMask
  518. client.SetRawHostname(session.rawHostname)
  519. hostname := client.Hostname() // may be a vhost
  520. timestampString := session.resumeDetails.Timestamp.Format(IRCv3TimestampFormat)
  521. // send quit/resume messages to friends
  522. for friend := range friends {
  523. if friend == client {
  524. continue
  525. }
  526. for _, fSession := range friend.Sessions() {
  527. if fSession.capabilities.Has(caps.Resume) {
  528. if session.resumeDetails.HistoryIncomplete {
  529. fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
  530. } else {
  531. fSession.Send(nil, oldNickmask, "RESUMED", hostname)
  532. }
  533. } else {
  534. if session.resumeDetails.HistoryIncomplete {
  535. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of history lost)"), gapSeconds))
  536. } else {
  537. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  538. }
  539. }
  540. }
  541. }
  542. if session.resumeDetails.HistoryIncomplete {
  543. session.Send(nil, client.server.name, "WARN", "RESUME", "HISTORY_LOST", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
  544. }
  545. session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
  546. server.playRegistrationBurst(session)
  547. for _, channel := range client.Channels() {
  548. channel.Resume(session, timestamp)
  549. }
  550. // replay direct PRIVSMG history
  551. if !timestamp.IsZero() {
  552. now := time.Now().UTC()
  553. items, complete := client.history.Between(timestamp, now, false, 0)
  554. rb := NewResponseBuffer(client.Sessions()[0])
  555. client.replayPrivmsgHistory(rb, items, complete)
  556. rb.Send(true)
  557. }
  558. session.resumeDetails = nil
  559. }
  560. func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
  561. var batchID string
  562. details := client.Details()
  563. nick := details.nick
  564. if 0 < len(items) {
  565. batchID = rb.StartNestedHistoryBatch(nick)
  566. }
  567. allowTags := rb.session.capabilities.Has(caps.MessageTags)
  568. for _, item := range items {
  569. var command string
  570. switch item.Type {
  571. case history.Privmsg:
  572. command = "PRIVMSG"
  573. case history.Notice:
  574. command = "NOTICE"
  575. case history.Tagmsg:
  576. if allowTags {
  577. command = "TAGMSG"
  578. } else {
  579. continue
  580. }
  581. default:
  582. continue
  583. }
  584. var tags map[string]string
  585. if allowTags {
  586. tags = item.Tags
  587. }
  588. if item.Params[0] == "" {
  589. // this message was sent *to* the client from another nick
  590. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
  591. } else {
  592. // this message was sent *from* the client to another nick; the target is item.Params[0]
  593. // substitute the client's current nickmask in case they changed nick
  594. rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
  595. }
  596. }
  597. rb.EndNestedBatch(batchID)
  598. if !complete {
  599. rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  600. }
  601. }
  602. // IdleTime returns how long this client's been idle.
  603. func (client *Client) IdleTime() time.Duration {
  604. client.stateMutex.RLock()
  605. defer client.stateMutex.RUnlock()
  606. return time.Since(client.atime)
  607. }
  608. // SignonTime returns this client's signon time as a unix timestamp.
  609. func (client *Client) SignonTime() int64 {
  610. return client.ctime.Unix()
  611. }
  612. // IdleSeconds returns the number of seconds this client's been idle.
  613. func (client *Client) IdleSeconds() uint64 {
  614. return uint64(client.IdleTime().Seconds())
  615. }
  616. // HasNick returns true if the client's nickname is set (used in registration).
  617. func (client *Client) HasNick() bool {
  618. client.stateMutex.RLock()
  619. defer client.stateMutex.RUnlock()
  620. return client.nick != "" && client.nick != "*"
  621. }
  622. // HasUsername returns true if the client's username is set (used in registration).
  623. func (client *Client) HasUsername() bool {
  624. client.stateMutex.RLock()
  625. defer client.stateMutex.RUnlock()
  626. return client.username != "" && client.username != "*"
  627. }
  628. // SetNames sets the client's ident and realname.
  629. func (client *Client) SetNames(username, realname string, fromIdent bool) error {
  630. limit := client.server.Config().Limits.IdentLen
  631. if !fromIdent {
  632. limit -= 1 // leave room for the prepended ~
  633. }
  634. if limit < len(username) {
  635. username = username[:limit]
  636. }
  637. if !isIdent(username) {
  638. return errInvalidUsername
  639. }
  640. if !fromIdent {
  641. username = "~" + username
  642. }
  643. client.stateMutex.Lock()
  644. defer client.stateMutex.Unlock()
  645. if client.username == "" {
  646. client.username = username
  647. }
  648. if client.realname == "" {
  649. client.realname = realname
  650. }
  651. return nil
  652. }
  653. // HasRoleCapabs returns true if client has the given (role) capabilities.
  654. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  655. oper := client.Oper()
  656. if oper == nil {
  657. return false
  658. }
  659. for _, capab := range capabs {
  660. if !oper.Class.Capabilities[capab] {
  661. return false
  662. }
  663. }
  664. return true
  665. }
  666. // ModeString returns the mode string for this client.
  667. func (client *Client) ModeString() (str string) {
  668. return "+" + client.flags.String()
  669. }
  670. // Friends refers to clients that share a channel with this client.
  671. func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
  672. result = make(map[*Session]bool)
  673. // look at the client's own sessions
  674. for _, session := range client.Sessions() {
  675. if session.capabilities.HasAll(capabs...) {
  676. result[session] = true
  677. }
  678. }
  679. for _, channel := range client.Channels() {
  680. for _, member := range channel.Members() {
  681. for _, session := range member.Sessions() {
  682. if session.capabilities.HasAll(capabs...) {
  683. result[session] = true
  684. }
  685. }
  686. }
  687. }
  688. return
  689. }
  690. func (client *Client) SetOper(oper *Oper) {
  691. client.stateMutex.Lock()
  692. defer client.stateMutex.Unlock()
  693. client.oper = oper
  694. // operators typically get a vhost, update the nickmask
  695. client.updateNickMaskNoMutex()
  696. }
  697. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  698. // this is annoying to do correctly
  699. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  700. username := client.Username()
  701. for fClient := range client.Friends(caps.ChgHost) {
  702. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  703. }
  704. }
  705. // choose the correct vhost to display
  706. func (client *Client) getVHostNoMutex() string {
  707. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  708. if client.vhost != "" {
  709. return client.vhost
  710. } else if client.oper != nil {
  711. return client.oper.Vhost
  712. } else {
  713. return ""
  714. }
  715. }
  716. // SetVHost updates the client's hostserv-based vhost
  717. func (client *Client) SetVHost(vhost string) (updated bool) {
  718. client.stateMutex.Lock()
  719. defer client.stateMutex.Unlock()
  720. updated = (client.vhost != vhost)
  721. client.vhost = vhost
  722. if updated {
  723. client.updateNickMaskNoMutex()
  724. }
  725. return
  726. }
  727. // updateNick updates `nick` and `nickCasefolded`.
  728. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  729. client.stateMutex.Lock()
  730. defer client.stateMutex.Unlock()
  731. client.nick = nick
  732. client.nickCasefolded = nickCasefolded
  733. client.skeleton = skeleton
  734. client.updateNickMaskNoMutex()
  735. }
  736. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  737. func (client *Client) updateNickMaskNoMutex() {
  738. client.hostname = client.getVHostNoMutex()
  739. if client.hostname == "" {
  740. client.hostname = client.cloakedHostname
  741. if client.hostname == "" {
  742. client.hostname = client.rawHostname
  743. }
  744. }
  745. cfhostname, err := Casefold(client.hostname)
  746. if err != nil {
  747. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  748. cfhostname = client.hostname // YOLO
  749. }
  750. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  751. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  752. }
  753. // AllNickmasks returns all the possible nickmasks for the client.
  754. func (client *Client) AllNickmasks() (masks []string) {
  755. client.stateMutex.RLock()
  756. nick := client.nickCasefolded
  757. username := client.username
  758. rawHostname := client.rawHostname
  759. cloakedHostname := client.cloakedHostname
  760. vhost := client.getVHostNoMutex()
  761. client.stateMutex.RUnlock()
  762. username = strings.ToLower(username)
  763. if len(vhost) > 0 {
  764. cfvhost, err := Casefold(vhost)
  765. if err == nil {
  766. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  767. }
  768. }
  769. var rawhostmask string
  770. cfrawhost, err := Casefold(rawHostname)
  771. if err == nil {
  772. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  773. masks = append(masks, rawhostmask)
  774. }
  775. if cloakedHostname != "" {
  776. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
  777. }
  778. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  779. if ipmask != rawhostmask {
  780. masks = append(masks, ipmask)
  781. }
  782. return
  783. }
  784. // LoggedIntoAccount returns true if this client is logged into an account.
  785. func (client *Client) LoggedIntoAccount() bool {
  786. return client.Account() != ""
  787. }
  788. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  789. func (client *Client) RplISupport(rb *ResponseBuffer) {
  790. translatedISupport := client.t("are supported by this server")
  791. nick := client.Nick()
  792. config := client.server.Config()
  793. for _, cachedTokenLine := range config.Server.isupport.CachedReply {
  794. length := len(cachedTokenLine) + 2
  795. tokenline := make([]string, length)
  796. tokenline[0] = nick
  797. copy(tokenline[1:], cachedTokenLine)
  798. tokenline[length-1] = translatedISupport
  799. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  800. }
  801. }
  802. // Quit sets the given quit message for the client.
  803. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  804. // the command handler or calling it yourself.)
  805. func (client *Client) Quit(message string, session *Session) {
  806. setFinalData := func(sess *Session) {
  807. message := sess.quitMessage
  808. var finalData []byte
  809. // #364: don't send QUIT lines to unregistered clients
  810. if client.registered {
  811. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  812. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  813. }
  814. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  815. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  816. finalData = append(finalData, errorMsgBytes...)
  817. sess.socket.SetFinalData(finalData)
  818. }
  819. client.stateMutex.Lock()
  820. defer client.stateMutex.Unlock()
  821. var sessions []*Session
  822. if session != nil {
  823. sessions = []*Session{session}
  824. } else {
  825. sessions = client.sessions
  826. }
  827. for _, session := range sessions {
  828. if session.SetQuitMessage(message) {
  829. setFinalData(session)
  830. }
  831. }
  832. }
  833. // destroy gets rid of a client, removes them from server lists etc.
  834. // if `session` is nil, destroys the client unconditionally, removing all sessions;
  835. // otherwise, destroys one specific session, only destroying the client if it
  836. // has no more sessions.
  837. func (client *Client) destroy(session *Session) {
  838. var sessionsToDestroy []*Session
  839. client.stateMutex.Lock()
  840. details := client.detailsNoMutex()
  841. brbState := client.brbTimer.state
  842. brbAt := client.brbTimer.brbAt
  843. wasReattach := session != nil && session.client != client
  844. sessionRemoved := false
  845. var remainingSessions int
  846. if session == nil {
  847. sessionsToDestroy = client.sessions
  848. client.sessions = nil
  849. remainingSessions = 0
  850. } else {
  851. sessionRemoved, remainingSessions = client.removeSession(session)
  852. if sessionRemoved {
  853. sessionsToDestroy = []*Session{session}
  854. }
  855. }
  856. // should we destroy the whole client this time?
  857. shouldDestroy := !client.destroyed && remainingSessions == 0 && (brbState != BrbEnabled && brbState != BrbSticky)
  858. if shouldDestroy {
  859. // if it's our job to destroy it, don't let anyone else try
  860. client.destroyed = true
  861. }
  862. exitedSnomaskSent := client.exitedSnomaskSent
  863. client.stateMutex.Unlock()
  864. // destroy all applicable sessions:
  865. var quitMessage string
  866. for _, session := range sessionsToDestroy {
  867. if session.client != client {
  868. // session has been attached to a new client; do not destroy it
  869. continue
  870. }
  871. session.idletimer.Stop()
  872. // send quit/error message to client if they haven't been sent already
  873. client.Quit("", session)
  874. quitMessage = session.quitMessage
  875. session.SetDestroyed()
  876. session.socket.Close()
  877. // remove from connection limits
  878. var source string
  879. if client.isTor {
  880. client.server.torLimiter.RemoveClient()
  881. source = "tor"
  882. } else {
  883. ip := session.realIP
  884. if session.proxiedIP != nil {
  885. ip = session.proxiedIP
  886. }
  887. client.server.connectionLimiter.RemoveClient(ip)
  888. source = ip.String()
  889. }
  890. client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
  891. }
  892. // do not destroy the client if it has either remaining sessions, or is BRB'ed
  893. if !shouldDestroy {
  894. return
  895. }
  896. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  897. // a lot of RAM, so limit concurrency to avoid thrashing
  898. client.server.semaphores.ClientDestroy.Acquire()
  899. defer client.server.semaphores.ClientDestroy.Release()
  900. if !wasReattach {
  901. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
  902. }
  903. registered := client.Registered()
  904. if registered {
  905. client.server.whoWas.Append(client.WhoWas())
  906. }
  907. client.server.resumeManager.Delete(client)
  908. // alert monitors
  909. if registered {
  910. client.server.monitorManager.AlertAbout(client, false)
  911. }
  912. // clean up monitor state
  913. client.server.monitorManager.RemoveAll(client)
  914. splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
  915. // clean up channels
  916. // (note that if this is a reattach, client has no channels and therefore no friends)
  917. friends := make(ClientSet)
  918. for _, channel := range client.Channels() {
  919. channel.Quit(client)
  920. channel.history.Add(history.Item{
  921. Type: history.Quit,
  922. Nick: details.nickMask,
  923. AccountName: details.accountName,
  924. Message: splitQuitMessage,
  925. })
  926. for _, member := range channel.Members() {
  927. friends.Add(member)
  928. }
  929. }
  930. friends.Remove(client)
  931. // clean up server
  932. client.server.clients.Remove(client)
  933. // clean up self
  934. client.nickTimer.Stop()
  935. client.brbTimer.Disable()
  936. client.server.accounts.Logout(client)
  937. // send quit messages to friends
  938. if registered {
  939. client.server.stats.ChangeTotal(-1)
  940. }
  941. if client.HasMode(modes.Invisible) {
  942. client.server.stats.ChangeInvisible(-1)
  943. }
  944. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  945. client.server.stats.ChangeOperators(-1)
  946. }
  947. // this happens under failure to return from BRB
  948. if quitMessage == "" {
  949. if !brbAt.IsZero() {
  950. awayMessage := client.AwayMessage()
  951. if awayMessage != "" {
  952. quitMessage = fmt.Sprintf("%s [%s ago]", awayMessage, time.Since(brbAt).Truncate(time.Second).String())
  953. }
  954. }
  955. }
  956. if quitMessage == "" {
  957. quitMessage = "Exited"
  958. }
  959. for friend := range friends {
  960. friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
  961. }
  962. if !exitedSnomaskSent && registered {
  963. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
  964. }
  965. }
  966. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  967. // Adds account-tag to the line as well.
  968. func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  969. if session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  970. session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  971. } else {
  972. for _, messagePair := range message.Wrapped {
  973. session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  974. }
  975. }
  976. }
  977. // Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
  978. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  979. for _, session := range client.Sessions() {
  980. err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
  981. if err_ != nil {
  982. err = err_
  983. }
  984. }
  985. return
  986. }
  987. func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  988. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  989. // attach account-tag
  990. if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
  991. msg.SetTag("account", accountName)
  992. }
  993. // attach message-id
  994. if msgid != "" && session.capabilities.Has(caps.MessageTags) {
  995. msg.SetTag("msgid", msgid)
  996. }
  997. // attach server-time
  998. if session.capabilities.Has(caps.ServerTime) {
  999. if serverTime.IsZero() {
  1000. serverTime = time.Now().UTC()
  1001. }
  1002. msg.SetTag("time", serverTime.Format(IRCv3TimestampFormat))
  1003. }
  1004. return session.SendRawMessage(msg, blocking)
  1005. }
  1006. var (
  1007. // these are all the output commands that MUST have their last param be a trailing.
  1008. // this is needed because dumb clients like to treat trailing params separately from the
  1009. // other params in messages.
  1010. commandsThatMustUseTrailing = map[string]bool{
  1011. "PRIVMSG": true,
  1012. "NOTICE": true,
  1013. RPL_WHOISCHANNELS: true,
  1014. RPL_USERHOST: true,
  1015. }
  1016. )
  1017. // SendRawMessage sends a raw message to the client.
  1018. func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  1019. // use dumb hack to force the last param to be a trailing param if required
  1020. var usedTrailingHack bool
  1021. config := session.client.server.Config()
  1022. if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
  1023. lastParam := message.Params[len(message.Params)-1]
  1024. // to force trailing, we ensure the final param contains a space
  1025. if strings.IndexByte(lastParam, ' ') == -1 {
  1026. message.Params[len(message.Params)-1] = lastParam + " "
  1027. usedTrailingHack = true
  1028. }
  1029. }
  1030. // assemble message
  1031. maxlenRest := session.MaxlenRest()
  1032. line, err := message.LineBytesStrict(false, maxlenRest)
  1033. if err != nil {
  1034. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  1035. session.client.server.logger.Error("internal", logline)
  1036. message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  1037. line, _ := message.LineBytesStrict(false, 0)
  1038. if blocking {
  1039. session.socket.BlockingWrite(line)
  1040. } else {
  1041. session.socket.Write(line)
  1042. }
  1043. return err
  1044. }
  1045. // if we used the trailing hack, we need to strip the final space we appended earlier on
  1046. if usedTrailingHack {
  1047. copy(line[len(line)-3:], "\r\n")
  1048. line = line[:len(line)-1]
  1049. }
  1050. if session.client.server.logger.IsLoggingRawIO() {
  1051. logline := string(line[:len(line)-2]) // strip "\r\n"
  1052. session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
  1053. }
  1054. if blocking {
  1055. return session.socket.BlockingWrite(line)
  1056. } else {
  1057. return session.socket.Write(line)
  1058. }
  1059. }
  1060. // Send sends an IRC line to the client.
  1061. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1062. for _, session := range client.Sessions() {
  1063. err_ := session.Send(tags, prefix, command, params...)
  1064. if err_ != nil {
  1065. err = err_
  1066. }
  1067. }
  1068. return
  1069. }
  1070. func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1071. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  1072. if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  1073. msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  1074. }
  1075. return session.SendRawMessage(msg, false)
  1076. }
  1077. // Notice sends the client a notice from the server.
  1078. func (client *Client) Notice(text string) {
  1079. client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
  1080. }
  1081. func (client *Client) addChannel(channel *Channel) {
  1082. client.stateMutex.Lock()
  1083. client.channels[channel] = true
  1084. client.stateMutex.Unlock()
  1085. }
  1086. func (client *Client) removeChannel(channel *Channel) {
  1087. client.stateMutex.Lock()
  1088. delete(client.channels, channel)
  1089. client.stateMutex.Unlock()
  1090. }
  1091. // Records that the client has been invited to join an invite-only channel
  1092. func (client *Client) Invite(casefoldedChannel string) {
  1093. client.stateMutex.Lock()
  1094. defer client.stateMutex.Unlock()
  1095. if client.invitedTo == nil {
  1096. client.invitedTo = make(map[string]bool)
  1097. }
  1098. client.invitedTo[casefoldedChannel] = true
  1099. }
  1100. // Checks that the client was invited to join a given channel
  1101. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  1102. client.stateMutex.Lock()
  1103. defer client.stateMutex.Unlock()
  1104. invited = client.invitedTo[casefoldedChannel]
  1105. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  1106. delete(client.invitedTo, casefoldedChannel)
  1107. return
  1108. }