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

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