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

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