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

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