Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 57KB

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