Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

client.go 50KB

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