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

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