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 58KB

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