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

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