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

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