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

client.go 50KB

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