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

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