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

client.go 62KB

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