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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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. var (
  31. LoopbackIP = net.ParseIP("127.0.0.1")
  32. )
  33. // ResumeDetails is a place to stash data at various stages of
  34. // the resume process: when handling the RESUME command itself,
  35. // when completing the registration, and when rejoining channels.
  36. type ResumeDetails struct {
  37. OldClient *Client
  38. OldNick string
  39. OldNickMask string
  40. PresentedToken string
  41. Timestamp time.Time
  42. ResumedAt time.Time
  43. Channels []string
  44. HistoryIncomplete bool
  45. }
  46. // Client is an IRC client.
  47. type Client struct {
  48. account string
  49. accountName string // display name of the account: uncasefolded, '*' if not logged in
  50. atime time.Time
  51. authorized bool
  52. awayMessage string
  53. capabilities *caps.Set
  54. capState caps.State
  55. capVersion caps.Version
  56. certfp string
  57. channels ChannelSet
  58. ctime time.Time
  59. exitedSnomaskSent bool
  60. fakelag *Fakelag
  61. flags *modes.ModeSet
  62. hasQuit bool
  63. hops int
  64. hostname string
  65. idletimer *IdleTimer
  66. invitedTo map[string]bool
  67. isDestroyed bool
  68. isQuitting bool
  69. languages []string
  70. loginThrottle connection_limits.GenericThrottle
  71. maxlenTags uint32
  72. maxlenRest uint32
  73. nick string
  74. nickCasefolded string
  75. nickMaskCasefolded string
  76. nickMaskString string // cache for nickmask string since it's used with lots of replies
  77. nickTimer *NickTimer
  78. oper *Oper
  79. preregNick string
  80. proxiedIP net.IP // actual remote IP if using the PROXY protocol
  81. quitMessage string
  82. rawHostname string
  83. realname string
  84. registered bool
  85. resumeDetails *ResumeDetails
  86. resumeToken string
  87. saslInProgress bool
  88. saslMechanism string
  89. saslValue string
  90. server *Server
  91. skeleton string
  92. socket *Socket
  93. stateMutex sync.RWMutex // tier 1
  94. username string
  95. usernameCasefolded string
  96. vhost string
  97. history *history.Buffer
  98. }
  99. // WhoWas is the subset of client details needed to answer a WHOWAS query
  100. type WhoWas struct {
  101. nick string
  102. nickCasefolded string
  103. username string
  104. hostname string
  105. realname string
  106. }
  107. // ClientDetails is a standard set of details about a client
  108. type ClientDetails struct {
  109. WhoWas
  110. nickMask string
  111. nickMaskCasefolded string
  112. account string
  113. accountName string
  114. }
  115. // NewClient sets up a new client and starts its goroutine.
  116. func NewClient(server *Server, conn net.Conn, isTLS bool) {
  117. now := time.Now()
  118. config := server.Config()
  119. fullLineLenLimit := config.Limits.LineLen.Tags + config.Limits.LineLen.Rest
  120. socket := NewSocket(conn, fullLineLenLimit*2, config.Server.MaxSendQBytes)
  121. client := &Client{
  122. atime: now,
  123. authorized: server.Password() == nil,
  124. capabilities: caps.NewSet(),
  125. capState: caps.NoneState,
  126. capVersion: caps.Cap301,
  127. channels: make(ChannelSet),
  128. ctime: now,
  129. flags: modes.NewModeSet(),
  130. loginThrottle: connection_limits.GenericThrottle{
  131. Duration: config.Accounts.LoginThrottling.Duration,
  132. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  133. },
  134. server: server,
  135. socket: socket,
  136. accountName: "*",
  137. nick: "*", // * is used until actual nick is given
  138. nickCasefolded: "*",
  139. nickMaskString: "*", // * is used until actual nick is given
  140. history: history.NewHistoryBuffer(config.History.ClientLength),
  141. }
  142. client.languages = server.languages.Default()
  143. client.recomputeMaxlens()
  144. if isTLS {
  145. client.SetMode(modes.TLS, true)
  146. // error is not useful to us here anyways so we can ignore it
  147. client.certfp, _ = client.socket.CertFP()
  148. }
  149. if config.Server.CheckIdent && !utils.AddrIsUnix(conn.RemoteAddr()) {
  150. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  151. if err != nil {
  152. server.logger.Error("internal", "bad server address", err.Error())
  153. return
  154. }
  155. serverPort, _ := strconv.Atoi(serverPortString)
  156. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  157. if err != nil {
  158. server.logger.Error("internal", "bad client address", err.Error())
  159. return
  160. }
  161. clientPort, _ := strconv.Atoi(clientPortString)
  162. client.Notice(client.t("*** Looking up your username"))
  163. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  164. if err == nil {
  165. username := resp.Identifier
  166. cfusername, err := CasefoldName(username)
  167. if err == nil {
  168. client.Notice(client.t("*** Found your username"))
  169. client.username = username
  170. client.usernameCasefolded = cfusername
  171. // we don't need to updateNickMask here since nickMask is not used for anything yet
  172. } else {
  173. client.Notice(client.t("*** Got a malformed username, ignoring"))
  174. }
  175. } else {
  176. client.Notice(client.t("*** Could not find your username"))
  177. }
  178. }
  179. go client.run()
  180. }
  181. func (client *Client) resetFakelag() {
  182. fakelag := func() *Fakelag {
  183. if client.HasRoleCapabs("nofakelag") {
  184. return nil
  185. }
  186. flc := client.server.FakelagConfig()
  187. if !flc.Enabled {
  188. return nil
  189. }
  190. return NewFakelag(flc.Window, flc.BurstLimit, flc.MessagesPerWindow, flc.Cooldown)
  191. }()
  192. client.stateMutex.Lock()
  193. defer client.stateMutex.Unlock()
  194. client.fakelag = fakelag
  195. }
  196. // IP returns the IP address of this client.
  197. func (client *Client) IP() net.IP {
  198. if client.proxiedIP != nil {
  199. return client.proxiedIP
  200. }
  201. if ip := utils.AddrToIP(client.socket.conn.RemoteAddr()); ip != nil {
  202. return ip
  203. }
  204. // unix domain socket that hasn't issued PROXY/WEBIRC yet. YOLO
  205. return LoopbackIP
  206. }
  207. // IPString returns the IP address of this client as a string.
  208. func (client *Client) IPString() string {
  209. ip := client.IP().String()
  210. if 0 < len(ip) && ip[0] == ':' {
  211. ip = "0" + ip
  212. }
  213. return ip
  214. }
  215. //
  216. // command goroutine
  217. //
  218. func (client *Client) recomputeMaxlens() (int, int) {
  219. maxlenTags := 512
  220. maxlenRest := 512
  221. if client.capabilities.Has(caps.MessageTags) {
  222. maxlenTags = 4096
  223. }
  224. if client.capabilities.Has(caps.MaxLine) {
  225. limits := client.server.Limits()
  226. if limits.LineLen.Tags > maxlenTags {
  227. maxlenTags = limits.LineLen.Tags
  228. }
  229. maxlenRest = limits.LineLen.Rest
  230. }
  231. atomic.StoreUint32(&client.maxlenTags, uint32(maxlenTags))
  232. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  233. return maxlenTags, maxlenRest
  234. }
  235. // allow these negotiated length limits to be read without locks; this is a convenience
  236. // so that Client.Send doesn't have to acquire any Client locks
  237. func (client *Client) maxlens() (int, int) {
  238. return int(atomic.LoadUint32(&client.maxlenTags)), int(atomic.LoadUint32(&client.maxlenRest))
  239. }
  240. func (client *Client) run() {
  241. var err error
  242. var isExiting bool
  243. var line string
  244. var msg ircmsg.IrcMessage
  245. defer func() {
  246. if r := recover(); r != nil {
  247. client.server.logger.Error("internal",
  248. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  249. if client.server.RecoverFromErrors() {
  250. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  251. } else {
  252. panic(r)
  253. }
  254. }
  255. // ensure client connection gets closed
  256. client.destroy(false)
  257. }()
  258. client.idletimer = NewIdleTimer(client)
  259. client.idletimer.Start()
  260. client.nickTimer = NewNickTimer(client)
  261. client.resetFakelag()
  262. // Set the hostname for this client
  263. // (may be overridden by a later PROXY command from stunnel)
  264. client.rawHostname = utils.AddrLookupHostname(client.socket.conn.RemoteAddr())
  265. firstLine := true
  266. for {
  267. maxlenTags, maxlenRest := client.recomputeMaxlens()
  268. line, err = client.socket.Read()
  269. if err != nil {
  270. quitMessage := "connection closed"
  271. if err == errReadQ {
  272. quitMessage = "readQ exceeded"
  273. }
  274. client.Quit(quitMessage)
  275. break
  276. }
  277. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  278. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  279. if firstLine {
  280. firstLine = false
  281. if strings.HasPrefix(line, "PROXY") {
  282. err = handleProxyCommand(client.server, client, line)
  283. if err != nil {
  284. break
  285. } else {
  286. continue
  287. }
  288. }
  289. }
  290. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  291. if err == ircmsg.ErrorLineIsEmpty {
  292. continue
  293. } else if err != nil {
  294. client.Quit(client.t("Received malformed line"))
  295. break
  296. }
  297. cmd, exists := Commands[msg.Command]
  298. if !exists {
  299. if len(msg.Command) > 0 {
  300. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, client.t("Unknown command"))
  301. } else {
  302. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", client.t("No command given"))
  303. }
  304. continue
  305. }
  306. isExiting = cmd.Run(client.server, client, msg)
  307. if isExiting || client.isQuitting {
  308. break
  309. }
  310. }
  311. }
  312. //
  313. // idle, quit, timers and timeouts
  314. //
  315. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  316. func (client *Client) Active() {
  317. client.stateMutex.Lock()
  318. defer client.stateMutex.Unlock()
  319. client.atime = time.Now()
  320. }
  321. // Ping sends the client a PING message.
  322. func (client *Client) Ping() {
  323. client.Send(nil, "", "PING", client.nick)
  324. }
  325. // Register sets the client details as appropriate when entering the network.
  326. func (client *Client) Register() {
  327. client.stateMutex.Lock()
  328. alreadyRegistered := client.registered
  329. client.registered = true
  330. client.stateMutex.Unlock()
  331. if alreadyRegistered {
  332. return
  333. }
  334. // apply resume details if we're able to.
  335. client.TryResume()
  336. // finish registration
  337. client.updateNickMask()
  338. client.server.monitorManager.AlertAbout(client, true)
  339. }
  340. // TryResume tries to resume if the client asked us to.
  341. func (client *Client) TryResume() {
  342. if client.resumeDetails == nil {
  343. return
  344. }
  345. server := client.server
  346. config := server.Config()
  347. oldnick := client.resumeDetails.OldNick
  348. timestamp := client.resumeDetails.Timestamp
  349. var timestampString string
  350. if !timestamp.IsZero() {
  351. timestampString = timestamp.UTC().Format(IRCv3TimestampFormat)
  352. }
  353. oldClient := server.clients.Get(oldnick)
  354. if oldClient == nil {
  355. client.Send(nil, server.name, "RESUME", "ERR", oldnick, client.t("Cannot resume connection, old client not found"))
  356. client.resumeDetails = nil
  357. return
  358. }
  359. oldNick := oldClient.Nick()
  360. oldNickmask := oldClient.NickMaskString()
  361. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  362. if !resumeAllowed {
  363. client.Send(nil, server.name, "RESUME", "ERR", oldnick, client.t("Cannot resume connection, old and new clients must have TLS"))
  364. client.resumeDetails = nil
  365. return
  366. }
  367. oldResumeToken := oldClient.ResumeToken()
  368. if oldResumeToken == "" || !utils.SecretTokensMatch(oldResumeToken, client.resumeDetails.PresentedToken) {
  369. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection, invalid resume token"))
  370. client.resumeDetails = nil
  371. return
  372. }
  373. err := server.clients.Resume(client, oldClient)
  374. if err != nil {
  375. client.resumeDetails = nil
  376. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection"))
  377. return
  378. }
  379. // this is a bit racey
  380. client.resumeDetails.ResumedAt = time.Now()
  381. client.nickTimer.Touch()
  382. // resume successful, proceed to copy client state (nickname, flags, etc.)
  383. // after this, the server thinks that `newClient` owns the nickname
  384. client.resumeDetails.OldClient = oldClient
  385. // transfer monitor stuff
  386. server.monitorManager.Resume(client, oldClient)
  387. // record the names, not the pointers, of the channels,
  388. // to avoid dumb annoying race conditions
  389. channels := oldClient.Channels()
  390. client.resumeDetails.Channels = make([]string, len(channels))
  391. for i, channel := range channels {
  392. client.resumeDetails.Channels[i] = channel.Name()
  393. }
  394. username := client.Username()
  395. hostname := client.Hostname()
  396. friends := make(ClientSet)
  397. oldestLostMessage := time.Now()
  398. // work out how much time, if any, is not covered by history buffers
  399. for _, channel := range channels {
  400. for _, member := range channel.Members() {
  401. friends.Add(member)
  402. lastDiscarded := channel.history.LastDiscarded()
  403. if lastDiscarded.Before(oldestLostMessage) {
  404. oldestLostMessage = lastDiscarded
  405. }
  406. }
  407. }
  408. privmsgMatcher := func(item history.Item) bool {
  409. return item.Type == history.Privmsg || item.Type == history.Notice
  410. }
  411. privmsgHistory := oldClient.history.Match(privmsgMatcher, 0)
  412. lastDiscarded := oldClient.history.LastDiscarded()
  413. if lastDiscarded.Before(oldestLostMessage) {
  414. oldestLostMessage = lastDiscarded
  415. }
  416. for _, item := range privmsgHistory {
  417. // TODO this is the nickmask, fix that
  418. sender := server.clients.Get(item.Nick)
  419. if sender != nil {
  420. friends.Add(sender)
  421. }
  422. }
  423. gap := lastDiscarded.Sub(timestamp)
  424. client.resumeDetails.HistoryIncomplete = gap > 0
  425. gapSeconds := int(gap.Seconds()) + 1 // round up to avoid confusion
  426. // send quit/resume messages to friends
  427. for friend := range friends {
  428. if friend.capabilities.Has(caps.Resume) {
  429. if timestamp.IsZero() {
  430. friend.Send(nil, oldNickmask, "RESUMED", username, hostname)
  431. } else {
  432. friend.Send(nil, oldNickmask, "RESUMED", username, hostname, timestampString)
  433. }
  434. } else {
  435. if client.resumeDetails.HistoryIncomplete {
  436. friend.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected (up to %d seconds of history lost)"), gapSeconds))
  437. } else {
  438. friend.Send(nil, oldNickmask, "QUIT", fmt.Sprintf(friend.t("Client reconnected")))
  439. }
  440. }
  441. }
  442. if client.resumeDetails.HistoryIncomplete {
  443. client.Send(nil, client.server.name, "RESUME", "WARN", fmt.Sprintf(client.t("Resume may have lost up to %d seconds of history"), gapSeconds))
  444. }
  445. client.Send(nil, client.server.name, "RESUME", "SUCCESS", oldNick)
  446. // after we send the rest of the registration burst, we'll try rejoining channels
  447. }
  448. func (client *Client) tryResumeChannels() {
  449. details := client.resumeDetails
  450. if details == nil {
  451. return
  452. }
  453. channels := make([]*Channel, len(details.Channels))
  454. for _, name := range details.Channels {
  455. channel := client.server.channels.Get(name)
  456. if channel == nil {
  457. continue
  458. }
  459. channel.Resume(client, details.OldClient, details.Timestamp)
  460. channels = append(channels, channel)
  461. }
  462. // replay direct PRIVSMG history
  463. if !details.Timestamp.IsZero() {
  464. now := time.Now()
  465. nick := client.Nick()
  466. items, complete := client.history.Between(details.Timestamp, now)
  467. for _, item := range items {
  468. var command string
  469. switch item.Type {
  470. case history.Privmsg:
  471. command = "PRIVMSG"
  472. case history.Notice:
  473. command = "NOTICE"
  474. default:
  475. continue
  476. }
  477. client.sendSplitMsgFromClientInternal(true, item.Time, item.Msgid, item.Nick, item.AccountName, nil, command, nick, item.Message)
  478. }
  479. if !complete {
  480. client.Send(nil, "HistServ", "NOTICE", nick, client.t("Some additional message history may have been lost"))
  481. }
  482. }
  483. details.OldClient.destroy(true)
  484. }
  485. // copy applicable state from oldClient to client as part of a resume
  486. func (client *Client) copyResumeData(oldClient *Client) {
  487. oldClient.stateMutex.RLock()
  488. flags := oldClient.flags
  489. history := oldClient.history
  490. nick := oldClient.nick
  491. nickCasefolded := oldClient.nickCasefolded
  492. vhost := oldClient.vhost
  493. account := oldClient.account
  494. accountName := oldClient.accountName
  495. skeleton := oldClient.skeleton
  496. oldClient.stateMutex.RUnlock()
  497. // copy all flags, *except* TLS (in the case that the admins enabled
  498. // resume over plaintext)
  499. hasTLS := client.flags.HasMode(modes.TLS)
  500. temp := modes.NewModeSet()
  501. temp.Copy(flags)
  502. temp.SetMode(modes.TLS, hasTLS)
  503. client.flags.Copy(temp)
  504. client.stateMutex.Lock()
  505. defer client.stateMutex.Unlock()
  506. // reuse the old client's history buffer
  507. client.history = history
  508. // copy other data
  509. client.nick = nick
  510. client.nickCasefolded = nickCasefolded
  511. client.vhost = vhost
  512. client.account = account
  513. client.accountName = accountName
  514. client.skeleton = skeleton
  515. client.updateNickMaskNoMutex()
  516. }
  517. // IdleTime returns how long this client's been idle.
  518. func (client *Client) IdleTime() time.Duration {
  519. client.stateMutex.RLock()
  520. defer client.stateMutex.RUnlock()
  521. return time.Since(client.atime)
  522. }
  523. // SignonTime returns this client's signon time as a unix timestamp.
  524. func (client *Client) SignonTime() int64 {
  525. return client.ctime.Unix()
  526. }
  527. // IdleSeconds returns the number of seconds this client's been idle.
  528. func (client *Client) IdleSeconds() uint64 {
  529. return uint64(client.IdleTime().Seconds())
  530. }
  531. // HasNick returns true if the client's nickname is set (used in registration).
  532. func (client *Client) HasNick() bool {
  533. client.stateMutex.RLock()
  534. defer client.stateMutex.RUnlock()
  535. return client.nick != "" && client.nick != "*"
  536. }
  537. // HasUsername returns true if the client's username is set (used in registration).
  538. func (client *Client) HasUsername() bool {
  539. client.stateMutex.RLock()
  540. defer client.stateMutex.RUnlock()
  541. return client.username != "" && client.username != "*"
  542. }
  543. func (client *Client) SetNames(username, realname string) error {
  544. usernameCasefolded, err := CasefoldName(username)
  545. if err != nil {
  546. return errInvalidUsername
  547. }
  548. client.stateMutex.Lock()
  549. defer client.stateMutex.Unlock()
  550. if client.username == "" {
  551. client.username = "~" + username
  552. client.usernameCasefolded = "~" + usernameCasefolded
  553. }
  554. if client.realname == "" {
  555. client.realname = realname
  556. }
  557. return nil
  558. }
  559. // HasRoleCapabs returns true if client has the given (role) capabilities.
  560. func (client *Client) HasRoleCapabs(capabs ...string) bool {
  561. oper := client.Oper()
  562. if oper == nil {
  563. return false
  564. }
  565. for _, capab := range capabs {
  566. if !oper.Class.Capabilities[capab] {
  567. return false
  568. }
  569. }
  570. return true
  571. }
  572. // ModeString returns the mode string for this client.
  573. func (client *Client) ModeString() (str string) {
  574. return "+" + client.flags.String()
  575. }
  576. // Friends refers to clients that share a channel with this client.
  577. func (client *Client) Friends(capabs ...caps.Capability) ClientSet {
  578. friends := make(ClientSet)
  579. // make sure that I have the right caps
  580. hasCaps := true
  581. for _, capab := range capabs {
  582. if !client.capabilities.Has(capab) {
  583. hasCaps = false
  584. break
  585. }
  586. }
  587. if hasCaps {
  588. friends.Add(client)
  589. }
  590. for _, channel := range client.Channels() {
  591. for _, member := range channel.Members() {
  592. // make sure they have all the required caps
  593. hasCaps = true
  594. for _, capab := range capabs {
  595. if !member.capabilities.Has(capab) {
  596. hasCaps = false
  597. break
  598. }
  599. }
  600. if hasCaps {
  601. friends.Add(member)
  602. }
  603. }
  604. }
  605. return friends
  606. }
  607. func (client *Client) SetOper(oper *Oper) {
  608. client.stateMutex.Lock()
  609. defer client.stateMutex.Unlock()
  610. client.oper = oper
  611. // operators typically get a vhost, update the nickmask
  612. client.updateNickMaskNoMutex()
  613. }
  614. // XXX: CHGHOST requires prefix nickmask to have original hostname,
  615. // this is annoying to do correctly
  616. func (client *Client) sendChghost(oldNickMask string, vhost string) {
  617. username := client.Username()
  618. for fClient := range client.Friends(caps.ChgHost) {
  619. fClient.sendFromClientInternal(false, time.Time{}, "", oldNickMask, client.AccountName(), nil, "CHGHOST", username, vhost)
  620. }
  621. }
  622. // choose the correct vhost to display
  623. func (client *Client) getVHostNoMutex() string {
  624. // hostserv vhost OR operclass vhost OR nothing (i.e., normal rdns hostmask)
  625. if client.vhost != "" {
  626. return client.vhost
  627. } else if client.oper != nil {
  628. return client.oper.Vhost
  629. } else {
  630. return ""
  631. }
  632. }
  633. // SetVHost updates the client's hostserv-based vhost
  634. func (client *Client) SetVHost(vhost string) (updated bool) {
  635. client.stateMutex.Lock()
  636. defer client.stateMutex.Unlock()
  637. updated = (client.vhost != vhost)
  638. client.vhost = vhost
  639. if updated {
  640. client.updateNickMaskNoMutex()
  641. }
  642. return
  643. }
  644. // updateNick updates `nick` and `nickCasefolded`.
  645. func (client *Client) updateNick(nick, nickCasefolded, skeleton string) {
  646. client.stateMutex.Lock()
  647. defer client.stateMutex.Unlock()
  648. client.nick = nick
  649. client.nickCasefolded = nickCasefolded
  650. client.skeleton = skeleton
  651. client.updateNickMaskNoMutex()
  652. }
  653. // updateNickMask updates the nickmask.
  654. func (client *Client) updateNickMask() {
  655. client.stateMutex.Lock()
  656. defer client.stateMutex.Unlock()
  657. client.updateNickMaskNoMutex()
  658. }
  659. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  660. func (client *Client) updateNickMaskNoMutex() {
  661. client.hostname = client.getVHostNoMutex()
  662. if client.hostname == "" {
  663. client.hostname = client.rawHostname
  664. }
  665. cfhostname, err := Casefold(client.hostname)
  666. if err != nil {
  667. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  668. cfhostname = client.hostname // YOLO
  669. }
  670. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  671. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, client.usernameCasefolded, cfhostname)
  672. }
  673. // AllNickmasks returns all the possible nickmasks for the client.
  674. func (client *Client) AllNickmasks() (masks []string) {
  675. client.stateMutex.RLock()
  676. nick := client.nickCasefolded
  677. username := client.usernameCasefolded
  678. rawHostname := client.rawHostname
  679. vhost := client.getVHostNoMutex()
  680. client.stateMutex.RUnlock()
  681. if len(vhost) > 0 {
  682. cfvhost, err := Casefold(vhost)
  683. if err == nil {
  684. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  685. }
  686. }
  687. var rawhostmask string
  688. cfrawhost, err := Casefold(rawHostname)
  689. if err == nil {
  690. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  691. masks = append(masks, rawhostmask)
  692. }
  693. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  694. if ipmask != rawhostmask {
  695. masks = append(masks, ipmask)
  696. }
  697. return
  698. }
  699. // LoggedIntoAccount returns true if this client is logged into an account.
  700. func (client *Client) LoggedIntoAccount() bool {
  701. return client.Account() != ""
  702. }
  703. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  704. func (client *Client) RplISupport(rb *ResponseBuffer) {
  705. translatedISupport := client.t("are supported by this server")
  706. nick := client.Nick()
  707. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  708. length := len(cachedTokenLine) + 2
  709. tokenline := make([]string, length)
  710. tokenline[0] = nick
  711. copy(tokenline[1:], cachedTokenLine)
  712. tokenline[length-1] = translatedISupport
  713. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  714. }
  715. }
  716. // Quit sets the given quit message for the client and tells the client to quit out.
  717. func (client *Client) Quit(message string) {
  718. client.stateMutex.Lock()
  719. alreadyQuit := client.isQuitting
  720. if !alreadyQuit {
  721. client.isQuitting = true
  722. client.quitMessage = message
  723. }
  724. client.stateMutex.Unlock()
  725. if alreadyQuit {
  726. return
  727. }
  728. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  729. quitLine, _ := quitMsg.Line()
  730. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  731. errorLine, _ := errorMsg.Line()
  732. client.socket.SetFinalData(quitLine + errorLine)
  733. }
  734. // destroy gets rid of a client, removes them from server lists etc.
  735. func (client *Client) destroy(beingResumed bool) {
  736. // allow destroy() to execute at most once
  737. client.stateMutex.Lock()
  738. isDestroyed := client.isDestroyed
  739. client.isDestroyed = true
  740. quitMessage := client.quitMessage
  741. nickMaskString := client.nickMaskString
  742. accountName := client.accountName
  743. client.stateMutex.Unlock()
  744. if isDestroyed {
  745. return
  746. }
  747. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  748. // a lot of RAM, so limit concurrency to avoid thrashing
  749. client.server.semaphores.ClientDestroy.Acquire()
  750. defer client.server.semaphores.ClientDestroy.Release()
  751. if beingResumed {
  752. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  753. } else {
  754. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  755. }
  756. // send quit/error message to client if they haven't been sent already
  757. client.Quit("Connection closed")
  758. if !beingResumed {
  759. client.server.whoWas.Append(client.WhoWas())
  760. }
  761. // remove from connection limits
  762. ipaddr := client.IP()
  763. // this check shouldn't be required but eh
  764. if ipaddr != nil {
  765. client.server.connectionLimiter.RemoveClient(ipaddr)
  766. }
  767. // alert monitors
  768. client.server.monitorManager.AlertAbout(client, false)
  769. // clean up monitor state
  770. client.server.monitorManager.RemoveAll(client)
  771. // clean up channels
  772. friends := make(ClientSet)
  773. for _, channel := range client.Channels() {
  774. if !beingResumed {
  775. channel.Quit(client)
  776. channel.history.Add(history.Item{
  777. Type: history.Quit,
  778. Nick: nickMaskString,
  779. AccountName: accountName,
  780. Message: utils.MakeSplitMessage(quitMessage, true),
  781. })
  782. }
  783. for _, member := range channel.Members() {
  784. friends.Add(member)
  785. }
  786. }
  787. friends.Remove(client)
  788. // clean up server
  789. if !beingResumed {
  790. client.server.clients.Remove(client)
  791. }
  792. // clean up self
  793. client.idletimer.Stop()
  794. client.nickTimer.Stop()
  795. client.server.accounts.Logout(client)
  796. client.socket.Close()
  797. // send quit messages to friends
  798. if !beingResumed {
  799. if client.Registered() {
  800. client.server.stats.ChangeTotal(-1)
  801. }
  802. if client.HasMode(modes.Invisible) {
  803. client.server.stats.ChangeInvisible(-1)
  804. }
  805. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  806. client.server.stats.ChangeOperators(-1)
  807. }
  808. for friend := range friends {
  809. if quitMessage == "" {
  810. quitMessage = "Exited"
  811. }
  812. friend.Send(nil, client.nickMaskString, "QUIT", quitMessage)
  813. }
  814. }
  815. if !client.exitedSnomaskSent {
  816. if beingResumed {
  817. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  818. } else {
  819. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  820. }
  821. }
  822. }
  823. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  824. // Adds account-tag to the line as well.
  825. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags Tags, command, target string, message utils.SplitMessage) {
  826. client.sendSplitMsgFromClientInternal(false, time.Time{}, msgid, from.NickMaskString(), from.AccountName(), tags, command, target, message)
  827. }
  828. func (client *Client) sendSplitMsgFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags Tags, command, target string, message utils.SplitMessage) {
  829. if client.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  830. client.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, target, message.Original)
  831. } else {
  832. for _, str := range message.Wrapped {
  833. client.sendFromClientInternal(blocking, serverTime, msgid, nickmask, accountName, tags, command, target, str)
  834. }
  835. }
  836. }
  837. // SendFromClient sends an IRC line coming from a specific client.
  838. // Adds account-tag to the line as well.
  839. func (client *Client) SendFromClient(msgid string, from *Client, tags Tags, command string, params ...string) error {
  840. return client.sendFromClientInternal(false, time.Time{}, msgid, from.NickMaskString(), from.AccountName(), tags, command, params...)
  841. }
  842. // helper to add a tag to `tags` (or create a new tag set if the current one is nil)
  843. func ensureTag(tags Tags, tagName, tagValue string) (result Tags) {
  844. if tags == nil {
  845. result = ircmsg.MakeTags(tagName, tagValue)
  846. } else {
  847. result = tags
  848. (*tags)[tagName] = ircmsg.MakeTagValue(tagValue)
  849. }
  850. return
  851. }
  852. // XXX this is a hack where we allow overriding the client's nickmask
  853. // this is to support CHGHOST, which requires that we send the *original* nickmask with the response
  854. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags Tags, command string, params ...string) error {
  855. // attach account-tag
  856. if client.capabilities.Has(caps.AccountTag) && accountName != "*" {
  857. tags = ensureTag(tags, "account", accountName)
  858. }
  859. // attach message-id
  860. if len(msgid) > 0 && client.capabilities.Has(caps.MessageTags) {
  861. tags = ensureTag(tags, "draft/msgid", msgid)
  862. }
  863. return client.sendInternal(blocking, serverTime, tags, nickmask, command, params...)
  864. }
  865. var (
  866. // these are all the output commands that MUST have their last param be a trailing.
  867. // this is needed because dumb clients like to treat trailing params separately from the
  868. // other params in messages.
  869. commandsThatMustUseTrailing = map[string]bool{
  870. "PRIVMSG": true,
  871. "NOTICE": true,
  872. RPL_WHOISCHANNELS: true,
  873. RPL_USERHOST: true,
  874. }
  875. )
  876. // SendRawMessage sends a raw message to the client.
  877. func (client *Client) SendRawMessage(message ircmsg.IrcMessage, blocking bool) error {
  878. // use dumb hack to force the last param to be a trailing param if required
  879. var usedTrailingHack bool
  880. if commandsThatMustUseTrailing[strings.ToUpper(message.Command)] && len(message.Params) > 0 {
  881. lastParam := message.Params[len(message.Params)-1]
  882. // to force trailing, we ensure the final param contains a space
  883. if !strings.Contains(lastParam, " ") {
  884. message.Params[len(message.Params)-1] = lastParam + " "
  885. usedTrailingHack = true
  886. }
  887. }
  888. // assemble message
  889. maxlenTags, maxlenRest := client.maxlens()
  890. line, err := message.LineMaxLenBytes(maxlenTags, maxlenRest)
  891. if err != nil {
  892. logline := fmt.Sprintf("Error assembling message for sending: %v\n%s", err, debug.Stack())
  893. client.server.logger.Error("internal", logline)
  894. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  895. line, _ := message.LineBytes()
  896. if blocking {
  897. client.socket.BlockingWrite(line)
  898. } else {
  899. client.socket.Write(line)
  900. }
  901. return err
  902. }
  903. // if we used the trailing hack, we need to strip the final space we appended earlier on
  904. if usedTrailingHack {
  905. copy(line[len(line)-3:], []byte{'\r', '\n'})
  906. line = line[:len(line)-1]
  907. }
  908. if client.server.logger.IsLoggingRawIO() {
  909. logline := string(line[:len(line)-2]) // strip "\r\n"
  910. client.server.logger.Debug("useroutput", client.nick, " ->", logline)
  911. }
  912. if blocking {
  913. return client.socket.BlockingWrite(line)
  914. } else {
  915. return client.socket.Write(line)
  916. }
  917. }
  918. func (client *Client) sendInternal(blocking bool, serverTime time.Time, tags Tags, prefix string, command string, params ...string) error {
  919. // attach server time
  920. if client.capabilities.Has(caps.ServerTime) {
  921. if serverTime.IsZero() {
  922. serverTime = time.Now()
  923. }
  924. tags = ensureTag(tags, "time", serverTime.UTC().Format(IRCv3TimestampFormat))
  925. }
  926. // send out the message
  927. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  928. client.SendRawMessage(message, blocking)
  929. return nil
  930. }
  931. // Send sends an IRC line to the client.
  932. func (client *Client) Send(tags Tags, prefix string, command string, params ...string) error {
  933. return client.sendInternal(false, time.Time{}, tags, prefix, command, params...)
  934. }
  935. // Notice sends the client a notice from the server.
  936. func (client *Client) Notice(text string) {
  937. limit := 400
  938. if client.capabilities.Has(caps.MaxLine) {
  939. limit = client.server.Limits().LineLen.Rest - 110
  940. }
  941. lines := utils.WordWrap(text, limit)
  942. // force blank lines to be sent if we receive them
  943. if len(lines) == 0 {
  944. lines = []string{""}
  945. }
  946. for _, line := range lines {
  947. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  948. }
  949. }
  950. func (client *Client) addChannel(channel *Channel) {
  951. client.stateMutex.Lock()
  952. client.channels[channel] = true
  953. client.stateMutex.Unlock()
  954. }
  955. func (client *Client) removeChannel(channel *Channel) {
  956. client.stateMutex.Lock()
  957. delete(client.channels, channel)
  958. client.stateMutex.Unlock()
  959. }
  960. // Ensures the client has a cryptographically secure resume token, and returns
  961. // its value. An error is returned if a token was previously assigned.
  962. func (client *Client) generateResumeToken() (token string, err error) {
  963. newToken := utils.GenerateSecretToken()
  964. client.stateMutex.Lock()
  965. defer client.stateMutex.Unlock()
  966. if client.resumeToken == "" {
  967. client.resumeToken = newToken
  968. } else {
  969. err = errResumeTokenAlreadySet
  970. }
  971. return client.resumeToken, err
  972. }
  973. // Records that the client has been invited to join an invite-only channel
  974. func (client *Client) Invite(casefoldedChannel string) {
  975. client.stateMutex.Lock()
  976. defer client.stateMutex.Unlock()
  977. if client.invitedTo == nil {
  978. client.invitedTo = make(map[string]bool)
  979. }
  980. client.invitedTo[casefoldedChannel] = true
  981. }
  982. // Checks that the client was invited to join a given channel
  983. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  984. client.stateMutex.Lock()
  985. defer client.stateMutex.Unlock()
  986. invited = client.invitedTo[casefoldedChannel]
  987. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  988. delete(client.invitedTo, casefoldedChannel)
  989. return
  990. }