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

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