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 56KB

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