Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

client.go 53KB

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