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

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