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.

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