Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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