Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 36KB

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