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

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