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

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