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

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