Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

client.go 51KB

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