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

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