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

client.go 57KB

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