選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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