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.

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