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

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