您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

client.go 56KB

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