Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

client.go 51KB

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