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

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