Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

client.go 49KB

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