You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 49KB

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