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

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