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

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