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

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