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 58KB

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