您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

client.go 53KB

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