Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 56KB

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