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

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