Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

client.go 56KB

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