You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 49KB

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