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

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