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

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