You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 57KB

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