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

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