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

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