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

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