Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

client.go 49KB

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