You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 57KB

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