You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.go 61KB

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