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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  27. IdentTimeoutSeconds = 1.5
  28. IRCv3TimestampFormat = "2006-01-02T15:04:05.000Z"
  29. )
  30. // ResumeDetails is a place to stash data at various stages of
  31. // the resume process: when handling the RESUME command itself,
  32. // when completing the registration, and when rejoining channels.
  33. type ResumeDetails struct {
  34. PresentedToken string
  35. Timestamp time.Time
  36. HistoryIncomplete bool
  37. }
  38. // Client is an IRC client.
  39. type Client struct {
  40. account string
  41. accountName string // display name of the account: uncasefolded, '*' if not logged in
  42. accountSettings AccountSettings
  43. atime time.Time
  44. away bool
  45. awayMessage string
  46. brbTimer BrbTimer
  47. certfp string
  48. channels ChannelSet
  49. ctime time.Time
  50. exitedSnomaskSent bool
  51. flags modes.ModeSet
  52. hostname string
  53. invitedTo map[string]bool
  54. isTor bool
  55. languages []string
  56. loginThrottle connection_limits.GenericThrottle
  57. nick string
  58. nickCasefolded string
  59. nickMaskCasefolded string
  60. nickMaskString string // cache for nickmask string since it's used with lots of replies
  61. nickTimer NickTimer
  62. oper *Oper
  63. preregNick string
  64. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  65. rawHostname string
  66. cloakedHostname string
  67. realname string
  68. realIP net.IP
  69. registered bool
  70. resumeID string
  71. saslInProgress bool
  72. saslMechanism string
  73. saslValue string
  74. sentPassCommand bool
  75. server *Server
  76. skeleton string
  77. sessions []*Session
  78. stateMutex sync.RWMutex // tier 1
  79. username string
  80. vhost string
  81. history history.Buffer
  82. }
  83. // Session is an individual client connection to the server (TCP connection
  84. // and associated per-connection data, such as capabilities). There is a
  85. // many-one relationship between sessions and clients.
  86. type Session struct {
  87. client *Client
  88. ctime time.Time
  89. atime time.Time
  90. socket *Socket
  91. realIP net.IP
  92. proxiedIP net.IP
  93. rawHostname string
  94. idletimer IdleTimer
  95. fakelag Fakelag
  96. quitMessage string
  97. capabilities caps.Set
  98. maxlenRest uint32
  99. capState caps.State
  100. capVersion caps.Version
  101. registrationMessages int
  102. resumeID string
  103. resumeDetails *ResumeDetails
  104. zncPlaybackTimes *zncPlaybackTimes
  105. }
  106. // sets the session quit message, if there isn't one already
  107. func (sd *Session) SetQuitMessage(message string) (set bool) {
  108. if message == "" {
  109. if sd.quitMessage == "" {
  110. sd.quitMessage = "Connection closed"
  111. return true
  112. } else {
  113. return false
  114. }
  115. } else {
  116. sd.quitMessage = message
  117. return true
  118. }
  119. }
  120. // set the negotiated message length based on session capabilities
  121. func (session *Session) SetMaxlenRest() {
  122. maxlenRest := 512
  123. if session.capabilities.Has(caps.MaxLine) {
  124. maxlenRest = session.client.server.Config().Limits.LineLen.Rest
  125. }
  126. atomic.StoreUint32(&session.maxlenRest, uint32(maxlenRest))
  127. }
  128. // allow the negotiated message length limit to be read without locks; this is a convenience
  129. // so that Session.SendRawMessage doesn't have to acquire any Client locks
  130. func (session *Session) MaxlenRest() int {
  131. return int(atomic.LoadUint32(&session.maxlenRest))
  132. }
  133. // WhoWas is the subset of client details needed to answer a WHOWAS query
  134. type WhoWas struct {
  135. nick string
  136. nickCasefolded string
  137. username string
  138. hostname string
  139. realname string
  140. }
  141. // ClientDetails is a standard set of details about a client
  142. type ClientDetails struct {
  143. WhoWas
  144. nickMask string
  145. nickMaskCasefolded string
  146. account string
  147. accountName string
  148. }
  149. // RunClient sets up a new client and runs its goroutine.
  150. func (server *Server) RunClient(conn clientConn) {
  151. var isBanned bool
  152. var banMsg string
  153. var realIP net.IP
  154. if conn.IsTor {
  155. realIP = utils.IPv4LoopbackAddress
  156. isBanned, banMsg = server.checkTorLimits()
  157. } else {
  158. realIP = utils.AddrToIP(conn.Conn.RemoteAddr())
  159. isBanned, banMsg = server.checkBans(realIP)
  160. }
  161. if isBanned {
  162. // this might not show up properly on some clients,
  163. // but our objective here is just to close the connection out before it has a load impact on us
  164. conn.Conn.Write([]byte(fmt.Sprintf(errorMsg, banMsg)))
  165. conn.Conn.Close()
  166. return
  167. }
  168. server.logger.Info("localconnect-ip", fmt.Sprintf("Client connecting from %v", realIP))
  169. now := time.Now().UTC()
  170. config := server.Config()
  171. fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
  172. // give them 1k of grace over the limit:
  173. socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
  174. client := &Client{
  175. atime: now,
  176. channels: make(ChannelSet),
  177. ctime: now,
  178. isTor: conn.IsTor,
  179. languages: server.Languages().Default(),
  180. loginThrottle: connection_limits.GenericThrottle{
  181. Duration: config.Accounts.LoginThrottling.Duration,
  182. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  183. },
  184. server: server,
  185. accountName: "*",
  186. nick: "*", // * is used until actual nick is given
  187. nickCasefolded: "*",
  188. nickMaskString: "*", // * is used until actual nick is given
  189. }
  190. client.history.Initialize(config.History.ClientLength)
  191. client.brbTimer.Initialize(client)
  192. session := &Session{
  193. client: client,
  194. socket: socket,
  195. capVersion: caps.Cap301,
  196. capState: caps.NoneState,
  197. ctime: now,
  198. atime: now,
  199. realIP: realIP,
  200. }
  201. session.SetMaxlenRest()
  202. client.sessions = []*Session{session}
  203. if conn.IsTLS {
  204. client.SetMode(modes.TLS, true)
  205. // error is not useful to us here anyways so we can ignore it
  206. client.certfp, _ = socket.CertFP()
  207. }
  208. if conn.IsTor {
  209. client.SetMode(modes.TLS, true)
  210. // cover up details of the tor proxying infrastructure (not a user privacy concern,
  211. // but a hardening measure):
  212. session.proxiedIP = utils.IPv4LoopbackAddress
  213. session.rawHostname = config.Server.TorListeners.Vhost
  214. } else {
  215. // set the hostname for this client (may be overridden later by PROXY or WEBIRC)
  216. session.rawHostname = utils.LookupHostname(session.realIP.String())
  217. client.cloakedHostname = config.Server.Cloaks.ComputeCloak(session.realIP)
  218. remoteAddr := conn.Conn.RemoteAddr()
  219. if utils.AddrIsLocal(remoteAddr) {
  220. // treat local connections as secure (may be overridden later by WEBIRC)
  221. client.SetMode(modes.TLS, true)
  222. }
  223. if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
  224. client.doIdentLookup(conn.Conn)
  225. }
  226. }
  227. client.realIP = session.realIP
  228. client.rawHostname = session.rawHostname
  229. client.proxiedIP = session.proxiedIP
  230. client.run(session)
  231. }
  232. func (client *Client) doIdentLookup(conn net.Conn) {
  233. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  234. if err != nil {
  235. client.server.logger.Error("internal", "bad server address", err.Error())
  236. return
  237. }
  238. serverPort, _ := strconv.Atoi(serverPortString)
  239. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  240. if err != nil {
  241. client.server.logger.Error("internal", "bad client address", err.Error())
  242. return
  243. }
  244. clientPort, _ := strconv.Atoi(clientPortString)
  245. client.Notice(client.t("*** Looking up your username"))
  246. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  247. if err == nil {
  248. err := client.SetNames(resp.Identifier, "", true)
  249. if err == nil {
  250. client.Notice(client.t("*** Found your username"))
  251. // we don't need to updateNickMask here since nickMask is not used for anything yet
  252. } else {
  253. client.Notice(client.t("*** Got a malformed username, ignoring"))
  254. }
  255. } else {
  256. client.Notice(client.t("*** Could not find your username"))
  257. }
  258. }
  259. func (client *Client) isAuthorized(config *Config) bool {
  260. saslSent := client.account != ""
  261. // PASS requirement
  262. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  263. return false
  264. }
  265. // Tor connections may be required to authenticate with SASL
  266. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  267. return false
  268. }
  269. // finally, enforce require-sasl
  270. return !config.Accounts.RequireSasl.Enabled || saslSent || utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets)
  271. }
  272. func (session *Session) resetFakelag() {
  273. var flc FakelagConfig = session.client.server.Config().Fakelag
  274. flc.Enabled = flc.Enabled && !session.client.HasRoleCapabs("nofakelag")
  275. session.fakelag.Initialize(flc)
  276. }
  277. // IP returns the IP address of this client.
  278. func (client *Client) IP() net.IP {
  279. client.stateMutex.RLock()
  280. defer client.stateMutex.RUnlock()
  281. if client.proxiedIP != nil {
  282. return client.proxiedIP
  283. }
  284. return client.realIP
  285. }
  286. // IPString returns the IP address of this client as a string.
  287. func (client *Client) IPString() string {
  288. ip := client.IP().String()
  289. if 0 < len(ip) && ip[0] == ':' {
  290. ip = "0" + ip
  291. }
  292. return ip
  293. }
  294. //
  295. // command goroutine
  296. //
  297. func (client *Client) run(session *Session) {
  298. defer func() {
  299. if r := recover(); r != nil {
  300. client.server.logger.Error("internal",
  301. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  302. if client.server.Config().Debug.recoverFromErrors {
  303. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  304. } else {
  305. panic(r)
  306. }
  307. }
  308. // ensure client connection gets closed
  309. client.destroy(session)
  310. }()
  311. session.idletimer.Initialize(session)
  312. session.resetFakelag()
  313. isReattach := client.Registered()
  314. if isReattach {
  315. if session.resumeDetails != nil {
  316. session.playResume()
  317. session.resumeDetails = nil
  318. client.brbTimer.Disable()
  319. } else {
  320. client.playReattachMessages(session)
  321. }
  322. } else {
  323. // don't reset the nick timer during a reattach
  324. client.nickTimer.Initialize(client)
  325. }
  326. firstLine := true
  327. for {
  328. maxlenRest := session.MaxlenRest()
  329. line, err := session.socket.Read()
  330. if err != nil {
  331. quitMessage := "connection closed"
  332. if err == errReadQ {
  333. quitMessage = "readQ exceeded"
  334. }
  335. client.Quit(quitMessage, session)
  336. // since the client did not actually send us a QUIT,
  337. // give them a chance to resume or reattach if applicable:
  338. client.brbTimer.Enable()
  339. break
  340. }
  341. if client.server.logger.IsLoggingRawIO() {
  342. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  343. }
  344. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  345. if !isReattach && firstLine {
  346. firstLine = false
  347. if strings.HasPrefix(line, "PROXY") {
  348. err = handleProxyCommand(client.server, client, session, line)
  349. if err != nil {
  350. break
  351. } else {
  352. continue
  353. }
  354. }
  355. }
  356. if client.registered {
  357. session.fakelag.Touch()
  358. } else {
  359. // DoS hardening, #505
  360. session.registrationMessages++
  361. if client.server.Config().Limits.RegistrationMessages < session.registrationMessages {
  362. client.Send(nil, client.server.name, ERR_UNKNOWNERROR, "*", client.t("You have sent too many registration messages"))
  363. break
  364. }
  365. }
  366. msg, err := ircmsg.ParseLineStrict(line, true, maxlenRest)
  367. if err == ircmsg.ErrorLineIsEmpty {
  368. continue
  369. } else if err == ircmsg.ErrorLineTooLong {
  370. session.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.Nick(), client.t("Input line too long"))
  371. continue
  372. } else if err != nil {
  373. client.Quit(client.t("Received malformed line"), session)
  374. break
  375. }
  376. cmd, exists := Commands[msg.Command]
  377. if !exists {
  378. if len(msg.Command) > 0 {
  379. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), msg.Command, client.t("Unknown command"))
  380. } else {
  381. session.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.Nick(), "lastcmd", client.t("No command given"))
  382. }
  383. continue
  384. }
  385. isExiting := cmd.Run(client.server, client, session, msg)
  386. if isExiting {
  387. break
  388. } else if session.client != client {
  389. // bouncer reattach
  390. go session.client.run(session)
  391. break
  392. }
  393. }
  394. }
  395. func (client *Client) playReattachMessages(session *Session) {
  396. client.server.playRegistrationBurst(session)
  397. for _, channel := range session.client.Channels() {
  398. channel.playJoinForSession(session)
  399. }
  400. }
  401. //
  402. // idle, quit, timers and timeouts
  403. //
  404. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  405. func (client *Client) Active(session *Session) {
  406. now := time.Now().UTC()
  407. client.stateMutex.Lock()
  408. defer client.stateMutex.Unlock()
  409. session.atime = now
  410. client.atime = now
  411. }
  412. // Ping sends the client a PING message.
  413. func (session *Session) Ping() {
  414. session.Send(nil, "", "PING", session.client.Nick())
  415. }
  416. // tryResume tries to resume if the client asked us to.
  417. func (session *Session) tryResume() (success bool) {
  418. var oldResumeID string
  419. defer func() {
  420. if success {
  421. // "On a successful request, the server [...] terminates the old client's connection"
  422. oldSession := session.client.GetSessionByResumeID(oldResumeID)
  423. if oldSession != nil {
  424. session.client.destroy(oldSession)
  425. }
  426. } else {
  427. session.resumeDetails = nil
  428. }
  429. }()
  430. client := session.client
  431. server := client.server
  432. config := server.Config()
  433. oldClient, oldResumeID := server.resumeManager.VerifyToken(client, session.resumeDetails.PresentedToken)
  434. if oldClient == nil {
  435. session.Send(nil, server.name, "FAIL", "RESUME", "INVALID_TOKEN", client.t("Cannot resume connection, token is not valid"))
  436. return
  437. }
  438. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  439. if !resumeAllowed {
  440. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection, old and new clients must have TLS"))
  441. return
  442. }
  443. if oldClient.isTor != client.isTor {
  444. session.Send(nil, server.name, "FAIL", "RESUME", "INSECURE_SESSION", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  445. return
  446. }
  447. err := server.clients.Resume(oldClient, session)
  448. if err != nil {
  449. session.Send(nil, server.name, "FAIL", "RESUME", "CANNOT_RESUME", client.t("Cannot resume connection"))
  450. return
  451. }
  452. success = true
  453. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", oldClient.Nick()))
  454. return
  455. }
  456. // playResume is called from the session's fresh goroutine after a resume;
  457. // it sends notifications to friends, then plays the registration burst and replays
  458. // stored history to the session
  459. func (session *Session) playResume() {
  460. client := session.client
  461. server := client.server
  462. friends := make(ClientSet)
  463. oldestLostMessage := time.Now().UTC()
  464. // work out how much time, if any, is not covered by history buffers
  465. for _, channel := range client.Channels() {
  466. for _, member := range channel.Members() {
  467. friends.Add(member)
  468. lastDiscarded := channel.history.LastDiscarded()
  469. if lastDiscarded.Before(oldestLostMessage) {
  470. oldestLostMessage = lastDiscarded
  471. }
  472. }
  473. }
  474. privmsgMatcher := func(item history.Item) bool {
  475. return item.Type == history.Privmsg || item.Type == history.Notice || item.Type == history.Tagmsg
  476. }
  477. privmsgHistory := client.history.Match(privmsgMatcher, false, 0)
  478. lastDiscarded := client.history.LastDiscarded()
  479. if lastDiscarded.Before(oldestLostMessage) {
  480. oldestLostMessage = lastDiscarded
  481. }
  482. for _, item := range privmsgHistory {
  483. sender := server.clients.Get(stripMaskFromNick(item.Nick))
  484. if sender != nil {
  485. friends.Add(sender)
  486. }
  487. }
  488. timestamp := session.resumeDetails.Timestamp
  489. gap := lastDiscarded.Sub(timestamp)
  490. session.resumeDetails.HistoryIncomplete = gap > 0
  491. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  492. details := client.Details()
  493. oldNickmask := details.nickMask
  494. client.SetRawHostname(session.rawHostname)
  495. hostname := client.Hostname() // may be a vhost
  496. timestampString := session.resumeDetails.Timestamp.Format(IRCv3TimestampFormat)
  497. // send quit/resume messages to friends
  498. for friend := range friends {
  499. if friend == client {
  500. continue
  501. }
  502. for _, fSession := range friend.Sessions() {
  503. if fSession.capabilities.Has(caps.Resume) {
  504. if timestamp.IsZero() {
  505. fSession.Send(nil, oldNickmask, "RESUMED", hostname)
  506. } else {
  507. fSession.Send(nil, oldNickmask, "RESUMED", hostname, timestampString)
  508. }
  509. } else {
  510. if session.resumeDetails.HistoryIncomplete {
  511. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of history lost)"), gapSeconds))
  512. } else {
  513. fSession.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  514. }
  515. }
  516. }
  517. }
  518. if session.resumeDetails.HistoryIncomplete {
  519. 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))
  520. }
  521. session.Send(nil, client.server.name, "RESUME", "SUCCESS", details.nick)
  522. server.playRegistrationBurst(session)
  523. for _, channel := range client.Channels() {
  524. channel.Resume(session, timestamp)
  525. }
  526. // replay direct PRIVSMG history
  527. if !timestamp.IsZero() {
  528. now := time.Now().UTC()
  529. items, complete := client.history.Between(timestamp, now, false, 0)
  530. rb := NewResponseBuffer(client.Sessions()[0])
  531. client.replayPrivmsgHistory(rb, items, complete)
  532. rb.Send(true)
  533. }
  534. session.resumeDetails = nil
  535. }
  536. func (client *Client) replayPrivmsgHistory(rb *ResponseBuffer, items []history.Item, complete bool) {
  537. var batchID string
  538. details := client.Details()
  539. nick := details.nick
  540. if 0 < len(items) {
  541. batchID = rb.StartNestedHistoryBatch(nick)
  542. }
  543. allowTags := rb.session.capabilities.Has(caps.MessageTags)
  544. for _, item := range items {
  545. var command string
  546. switch item.Type {
  547. case history.Privmsg:
  548. command = "PRIVMSG"
  549. case history.Notice:
  550. command = "NOTICE"
  551. case history.Tagmsg:
  552. if allowTags {
  553. command = "TAGMSG"
  554. } else {
  555. continue
  556. }
  557. default:
  558. continue
  559. }
  560. var tags map[string]string
  561. if allowTags {
  562. tags = item.Tags
  563. }
  564. if item.Params[0] == "" {
  565. // this message was sent *to* the client from another nick
  566. rb.AddSplitMessageFromClient(item.Nick, item.AccountName, tags, command, nick, item.Message)
  567. } else {
  568. // this message was sent *from* the client to another nick; the target is item.Params[0]
  569. // substitute the client's current nickmask in case they changed nick
  570. rb.AddSplitMessageFromClient(details.nickMask, item.AccountName, tags, command, item.Params[0], item.Message)
  571. }
  572. }
  573. rb.EndNestedBatch(batchID)
  574. if !complete {
  575. rb.Add(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  576. }
  577. }
  578. // IdleTime returns how long this client's been idle.
  579. func (client *Client) IdleTime() time.Duration {
  580. client.stateMutex.RLock()
  581. defer client.stateMutex.RUnlock()
  582. return time.Since(client.atime)
  583. }
  584. // SignonTime returns this client's signon time as a unix timestamp.
  585. func (client *Client) SignonTime() int64 {
  586. return client.ctime.Unix()
  587. }
  588. // IdleSeconds returns the number of seconds this client's been idle.
  589. func (client *Client) IdleSeconds() uint64 {
  590. return uint64(client.IdleTime().Seconds())
  591. }
  592. // HasNick returns true if the client's nickname is set (used in registration).
  593. func (client *Client) HasNick() bool {
  594. client.stateMutex.RLock()
  595. defer client.stateMutex.RUnlock()
  596. return client.nick != "" && client.nick != "*"
  597. }
  598. // HasUsername returns true if the client's username is set (used in registration).
  599. func (client *Client) HasUsername() bool {
  600. client.stateMutex.RLock()
  601. defer client.stateMutex.RUnlock()
  602. return client.username != "" && client.username != "*"
  603. }
  604. // SetNames sets the client's ident and realname.
  605. func (client *Client) SetNames(username, realname string, fromIdent bool) error {
  606. limit := client.server.Config().Limits.IdentLen
  607. if !fromIdent {
  608. limit -= 1 // leave room for the prepended ~
  609. }
  610. if limit < len(username) {
  611. username = username[:limit]
  612. }
  613. if !isIdent(username) {
  614. return errInvalidUsername
  615. }
  616. if !fromIdent {
  617. username = "~" + username
  618. }
  619. client.stateMutex.Lock()
  620. defer client.stateMutex.Unlock()
  621. if client.username == "" {
  622. client.username = username
  623. }
  624. if client.realname == "" {
  625. client.realname = realname
  626. }
  627. return nil
  628. }
  629. // HasRoleCapabs returns true if client has the given (role) capabilities.
  630. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  631. oper := client.Oper()
  632. if oper == nil {
  633. return false
  634. }
  635. for _, capab := range capabs {
  636. if !oper.Class.Capabilities[capab] {
  637. return false
  638. }
  639. }
  640. return true
  641. }
  642. // ModeString returns the mode string for this client.
  643. func (client *Client) ModeString() (str string) {
  644. return "+" + client.flags.String()
  645. }
  646. // Friends refers to clients that share a channel with this client.
  647. func (client *Client) Friends(capabs ...caps.Capability) (result map[*Session]bool) {
  648. result = make(map[*Session]bool)
  649. // look at the client's own sessions
  650. for _, session := range client.Sessions() {
  651. if session.capabilities.HasAll(capabs...) {
  652. result[session] = true
  653. }
  654. }
  655. for _, channel := range client.Channels() {
  656. for _, member := range channel.Members() {
  657. for _, session := range member.Sessions() {
  658. if session.capabilities.HasAll(capabs...) {
  659. result[session] = true
  660. }
  661. }
  662. }
  663. }
  664. return
  665. }
  666. func (client *Client) SetOper(oper *Oper) {
  667. client.stateMutex.Lock()
  668. defer client.stateMutex.Unlock()
  669. client.oper = oper
  670. // operators typically get a vhost, update the nickmask
  671. client.updateNickMaskNoMutex()
  672. }
  673. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  674. // this is annoying to do correctly
  675. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  676. username := client.Username()
  677. for fClient := range client.Friends(caps.ChgHost) {
  678. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  679. }
  680. }
  681. // choose the correct vhost to display
  682. func (client *Client) getVHostNoMutex() string {
  683. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  684. if client.vhost != "" {
  685. return client.vhost
  686. } else if client.oper != nil {
  687. return client.oper.Vhost
  688. } else {
  689. return ""
  690. }
  691. }
  692. // SetVHost updates the client's hostserv-based vhost
  693. func (client *Client) SetVHost(vhost string) (updated bool) {
  694. client.stateMutex.Lock()
  695. defer client.stateMutex.Unlock()
  696. updated = (client.vhost != vhost)
  697. client.vhost = vhost
  698. if updated {
  699. client.updateNickMaskNoMutex()
  700. }
  701. return
  702. }
  703. // updateNick updates `nick` and `nickCasefolded`.
  704. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  705. client.stateMutex.Lock()
  706. defer client.stateMutex.Unlock()
  707. client.nick = nick
  708. client.nickCasefolded = nickCasefolded
  709. client.skeleton = skeleton
  710. client.updateNickMaskNoMutex()
  711. }
  712. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  713. func (client *Client) updateNickMaskNoMutex() {
  714. client.hostname = client.getVHostNoMutex()
  715. if client.hostname == "" {
  716. client.hostname = client.cloakedHostname
  717. if client.hostname == "" {
  718. client.hostname = client.rawHostname
  719. }
  720. }
  721. cfhostname, err := Casefold(client.hostname)
  722. if err != nil {
  723. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  724. cfhostname = client.hostname // YOLO
  725. }
  726. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  727. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  728. }
  729. // AllNickmasks returns all the possible nickmasks for the client.
  730. func (client *Client) AllNickmasks() (masks []string) {
  731. client.stateMutex.RLock()
  732. nick := client.nickCasefolded
  733. username := client.username
  734. rawHostname := client.rawHostname
  735. cloakedHostname := client.cloakedHostname
  736. vhost := client.getVHostNoMutex()
  737. client.stateMutex.RUnlock()
  738. username = strings.ToLower(username)
  739. if len(vhost) > 0 {
  740. cfvhost, err := Casefold(vhost)
  741. if err == nil {
  742. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  743. }
  744. }
  745. var rawhostmask string
  746. cfrawhost, err := Casefold(rawHostname)
  747. if err == nil {
  748. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  749. masks = append(masks, rawhostmask)
  750. }
  751. if cloakedHostname != "" {
  752. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cloakedHostname))
  753. }
  754. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  755. if ipmask != rawhostmask {
  756. masks = append(masks, ipmask)
  757. }
  758. return
  759. }
  760. // LoggedIntoAccount returns true if this client is logged into an account.
  761. func (client *Client) LoggedIntoAccount() bool {
  762. return client.Account() != ""
  763. }
  764. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  765. func (client *Client) RplISupport(rb *ResponseBuffer) {
  766. translatedISupport := client.t("are supported by this server")
  767. nick := client.Nick()
  768. config := client.server.Config()
  769. for _, cachedTokenLine := range config.Server.isupport.CachedReply {
  770. length := len(cachedTokenLine) + 2
  771. tokenline := make([]string, length)
  772. tokenline[0] = nick
  773. copy(tokenline[1:], cachedTokenLine)
  774. tokenline[length-1] = translatedISupport
  775. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  776. }
  777. }
  778. // Quit sets the given quit message for the client.
  779. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  780. // the command handler or calling it yourself.)
  781. func (client *Client) Quit(message string, session *Session) {
  782. setFinalData := func(sess *Session) {
  783. message := sess.quitMessage
  784. var finalData []byte
  785. // #364: don't send QUIT lines to unregistered clients
  786. if client.registered {
  787. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  788. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  789. }
  790. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  791. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  792. finalData = append(finalData, errorMsgBytes...)
  793. sess.socket.SetFinalData(finalData)
  794. }
  795. client.stateMutex.Lock()
  796. defer client.stateMutex.Unlock()
  797. var sessions []*Session
  798. if session != nil {
  799. sessions = []*Session{session}
  800. } else {
  801. sessions = client.sessions
  802. }
  803. for _, session := range sessions {
  804. if session.SetQuitMessage(message) {
  805. setFinalData(session)
  806. }
  807. }
  808. }
  809. // destroy gets rid of a client, removes them from server lists etc.
  810. // if `session` is nil, destroys the client unconditionally, removing all sessions;
  811. // otherwise, destroys one specific session, only destroying the client if it
  812. // has no more sessions.
  813. func (client *Client) destroy(session *Session) {
  814. var sessionsToDestroy []*Session
  815. // allow destroy() to execute at most once
  816. client.stateMutex.Lock()
  817. details := client.detailsNoMutex()
  818. brbState := client.brbTimer.state
  819. wasReattach := session != nil && session.client != client
  820. sessionRemoved := false
  821. var remainingSessions int
  822. if session == nil {
  823. sessionsToDestroy = client.sessions
  824. client.sessions = nil
  825. remainingSessions = 0
  826. } else {
  827. sessionRemoved, remainingSessions = client.removeSession(session)
  828. if sessionRemoved {
  829. sessionsToDestroy = []*Session{session}
  830. }
  831. }
  832. client.stateMutex.Unlock()
  833. // destroy all applicable sessions:
  834. var quitMessage string
  835. for _, session := range sessionsToDestroy {
  836. if session.client != client {
  837. // session has been attached to a new client; do not destroy it
  838. continue
  839. }
  840. session.idletimer.Stop()
  841. // send quit/error message to client if they haven't been sent already
  842. client.Quit("", session)
  843. quitMessage = session.quitMessage
  844. session.socket.Close()
  845. // remove from connection limits
  846. var source string
  847. if client.isTor {
  848. client.server.torLimiter.RemoveClient()
  849. source = "tor"
  850. } else {
  851. ip := session.realIP
  852. if session.proxiedIP != nil {
  853. ip = session.proxiedIP
  854. }
  855. client.server.connectionLimiter.RemoveClient(ip)
  856. source = ip.String()
  857. }
  858. client.server.logger.Info("localconnect-ip", fmt.Sprintf("disconnecting session of %s from %s", details.nick, source))
  859. }
  860. // do not destroy the client if it has either remaining sessions, or is BRB'ed
  861. if remainingSessions != 0 || brbState == BrbEnabled || brbState == BrbSticky {
  862. return
  863. }
  864. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  865. // a lot of RAM, so limit concurrency to avoid thrashing
  866. client.server.semaphores.ClientDestroy.Acquire()
  867. defer client.server.semaphores.ClientDestroy.Release()
  868. if !wasReattach {
  869. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", details.nick))
  870. }
  871. registered := client.Registered()
  872. if registered {
  873. client.server.whoWas.Append(client.WhoWas())
  874. }
  875. client.server.resumeManager.Delete(client)
  876. // alert monitors
  877. if registered {
  878. client.server.monitorManager.AlertAbout(client, false)
  879. }
  880. // clean up monitor state
  881. client.server.monitorManager.RemoveAll(client)
  882. splitQuitMessage := utils.MakeSplitMessage(quitMessage, true)
  883. // clean up channels
  884. // (note that if this is a reattach, client has no channels and therefore no friends)
  885. friends := make(ClientSet)
  886. for _, channel := range client.Channels() {
  887. channel.Quit(client)
  888. channel.history.Add(history.Item{
  889. Type: history.Quit,
  890. Nick: details.nickMask,
  891. AccountName: details.accountName,
  892. Message: splitQuitMessage,
  893. })
  894. for _, member := range channel.Members() {
  895. friends.Add(member)
  896. }
  897. }
  898. friends.Remove(client)
  899. // clean up server
  900. client.server.clients.Remove(client)
  901. // clean up self
  902. client.nickTimer.Stop()
  903. client.brbTimer.Disable()
  904. client.server.accounts.Logout(client)
  905. // send quit messages to friends
  906. if registered {
  907. client.server.stats.ChangeTotal(-1)
  908. }
  909. if client.HasMode(modes.Invisible) {
  910. client.server.stats.ChangeInvisible(-1)
  911. }
  912. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  913. client.server.stats.ChangeOperators(-1)
  914. }
  915. for friend := range friends {
  916. if quitMessage == "" {
  917. quitMessage = "Exited"
  918. }
  919. friend.sendFromClientInternal(false, splitQuitMessage.Time, splitQuitMessage.Msgid, details.nickMask, details.accountName, nil, "QUIT", quitMessage)
  920. }
  921. if !client.exitedSnomaskSent && registered {
  922. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), details.nick))
  923. }
  924. }
  925. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  926. // Adds account-tag to the line as well.
  927. func (session *Session) sendSplitMsgFromClientInternal(blocking bool, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  928. if session.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  929. session.sendFromClientInternal(blocking, message.Time, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  930. } else {
  931. for _, messagePair := range message.Wrapped {
  932. session.sendFromClientInternal(blocking, message.Time, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  933. }
  934. }
  935. }
  936. // Sends a line with `nickmask` as the prefix, adding `time` and `account` tags if supported
  937. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  938. for _, session := range client.Sessions() {
  939. err_ := session.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, params...)
  940. if err_ != nil {
  941. err = err_
  942. }
  943. }
  944. return
  945. }
  946. func (session *Session) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) (err error) {
  947. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  948. // attach account-tag
  949. if session.capabilities.Has(caps.AccountTag) && accountName != "*" {
  950. msg.SetTag("account", accountName)
  951. }
  952. // attach message-id
  953. if msgid != "" && session.capabilities.Has(caps.MessageTags) {
  954. msg.SetTag("msgid", msgid)
  955. }
  956. // attach server-time
  957. if session.capabilities.Has(caps.ServerTime) {
  958. if serverTime.IsZero() {
  959. serverTime = time.Now().UTC()
  960. }
  961. msg.SetTag("time", serverTime.Format(IRCv3TimestampFormat))
  962. }
  963. return session.SendRawMessage(msg, blocking)
  964. }
  965. var (
  966. // these are all the output commands that MUST have their last param be a trailing.
  967. // this is needed because dumb clients like to treat trailing params separately from the
  968. // other params in messages.
  969. commandsThatMustUseTrailing = map[string]bool{
  970. "PRIVMSG": true,
  971. "NOTICE": true,
  972. RPL_WHOISCHANNELS: true,
  973. RPL_USERHOST: true,
  974. }
  975. )
  976. // SendRawMessage sends a raw message to the client.
  977. func (session *Session) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  978. // use dumb hack to force the last param to be a trailing param if required
  979. var usedTrailingHack bool
  980. config := session.client.server.Config()
  981. if config.Server.Compatibility.forceTrailing && commandsThatMustUseTrailing[message.Command] && len(message.Params) > 0 {
  982. lastParam := message.Params[len(message.Params)-1]
  983. // to force trailing, we ensure the final param contains a space
  984. if strings.IndexByte(lastParam, ' ') == -1 {
  985. message.Params[len(message.Params)-1] = lastParam + " "
  986. usedTrailingHack = true
  987. }
  988. }
  989. // assemble message
  990. maxlenRest := session.MaxlenRest()
  991. line, err := message.LineBytesStrict(false, maxlenRest)
  992. if err != nil {
  993. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  994. session.client.server.logger.Error("internal", logline)
  995. message = ircmsg.MakeMessage(nil, session.client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  996. line, _ := message.LineBytesStrict(false, 0)
  997. if blocking {
  998. session.socket.BlockingWrite(line)
  999. } else {
  1000. session.socket.Write(line)
  1001. }
  1002. return err
  1003. }
  1004. // if we used the trailing hack, we need to strip the final space we appended earlier on
  1005. if usedTrailingHack {
  1006. copy(line[len(line)-3:], "\r\n")
  1007. line = line[:len(line)-1]
  1008. }
  1009. if session.client.server.logger.IsLoggingRawIO() {
  1010. logline := string(line[:len(line)-2]) // strip "\r\n"
  1011. session.client.server.logger.Debug("useroutput", session.client.Nick(), " ->", logline)
  1012. }
  1013. if blocking {
  1014. return session.socket.BlockingWrite(line)
  1015. } else {
  1016. return session.socket.Write(line)
  1017. }
  1018. }
  1019. // Send sends an IRC line to the client.
  1020. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1021. for _, session := range client.Sessions() {
  1022. err_ := session.Send(tags, prefix, command, params...)
  1023. if err_ != nil {
  1024. err = err_
  1025. }
  1026. }
  1027. return
  1028. }
  1029. func (session *Session) Send(tags map[string]string, prefix string, command string, params ...string) (err error) {
  1030. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  1031. if session.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  1032. msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  1033. }
  1034. return session.SendRawMessage(msg, false)
  1035. }
  1036. // Notice sends the client a notice from the server.
  1037. func (client *Client) Notice(text string) {
  1038. client.Send(nil, client.server.name, "NOTICE", client.Nick(), text)
  1039. }
  1040. func (client *Client) addChannel(channel *Channel) {
  1041. client.stateMutex.Lock()
  1042. client.channels[channel] = true
  1043. client.stateMutex.Unlock()
  1044. }
  1045. func (client *Client) removeChannel(channel *Channel) {
  1046. client.stateMutex.Lock()
  1047. delete(client.channels, channel)
  1048. client.stateMutex.Unlock()
  1049. }
  1050. // Records that the client has been invited to join an invite-only channel
  1051. func (client *Client) Invite(casefoldedChannel string) {
  1052. client.stateMutex.Lock()
  1053. defer client.stateMutex.Unlock()
  1054. if client.invitedTo == nil {
  1055. client.invitedTo = make(map[string]bool)
  1056. }
  1057. client.invitedTo[casefoldedChannel] = true
  1058. }
  1059. // Checks that the client was invited to join a given channel
  1060. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  1061. client.stateMutex.Lock()
  1062. defer client.stateMutex.Unlock()
  1063. invited = client.invitedTo[casefoldedChannel]
  1064. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  1065. delete(client.invitedTo, casefoldedChannel)
  1066. return
  1067. }