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

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