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

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