Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

client.go 52KB

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