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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  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. isTor bool
  63. isQuitting bool
  64. languages []string
  65. loginThrottle connection_limits.GenericThrottle
  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 runs its goroutine.
  111. func RunNewClient(server *Server, conn clientConn) {
  112. now := time.Now()
  113. config := server.Config()
  114. fullLineLenLimit := ircmsg.MaxlenTagsFromClient + config.Limits.LineLen.Rest
  115. // give them 1k of grace over the limit:
  116. socket := NewSocket(conn.Conn, fullLineLenLimit+1024, config.Server.MaxSendQBytes)
  117. client := &Client{
  118. atime: now,
  119. capabilities: caps.NewSet(),
  120. capState: caps.NoneState,
  121. capVersion: caps.Cap301,
  122. channels: make(ChannelSet),
  123. ctime: now,
  124. flags: modes.NewModeSet(),
  125. isTor: conn.IsTor,
  126. languages: server.Languages().Default(),
  127. loginThrottle: connection_limits.GenericThrottle{
  128. Duration: config.Accounts.LoginThrottling.Duration,
  129. Limit: config.Accounts.LoginThrottling.MaxAttempts,
  130. },
  131. server: server,
  132. socket: socket,
  133. accountName: "*",
  134. nick: "*", // * is used until actual nick is given
  135. nickCasefolded: "*",
  136. nickMaskString: "*", // * is used until actual nick is given
  137. history: history.NewHistoryBuffer(config.History.ClientLength),
  138. }
  139. client.recomputeMaxlens()
  140. if conn.IsTLS {
  141. client.SetMode(modes.TLS, true)
  142. // error is not useful to us here anyways so we can ignore it
  143. client.certfp, _ = client.socket.CertFP()
  144. }
  145. if conn.IsTor {
  146. client.SetMode(modes.TLS, true)
  147. client.realIP = utils.IPv4LoopbackAddress
  148. client.rawHostname = config.Server.TorListeners.Vhost
  149. } else {
  150. remoteAddr := conn.Conn.RemoteAddr()
  151. client.realIP = utils.AddrToIP(remoteAddr)
  152. // Set the hostname for this client
  153. // (may be overridden by a later PROXY command from stunnel)
  154. client.rawHostname = utils.LookupHostname(client.realIP.String())
  155. if config.Server.CheckIdent && !utils.AddrIsUnix(remoteAddr) {
  156. client.doIdentLookup(conn.Conn)
  157. }
  158. }
  159. client.run()
  160. }
  161. func (client *Client) doIdentLookup(conn net.Conn) {
  162. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  163. if err != nil {
  164. client.server.logger.Error("internal", "bad server address", err.Error())
  165. return
  166. }
  167. serverPort, _ := strconv.Atoi(serverPortString)
  168. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  169. if err != nil {
  170. client.server.logger.Error("internal", "bad client address", err.Error())
  171. return
  172. }
  173. clientPort, _ := strconv.Atoi(clientPortString)
  174. client.Notice(client.t("*** Looking up your username"))
  175. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  176. if err == nil {
  177. err := client.SetNames(resp.Identifier, "", true)
  178. if err == nil {
  179. client.Notice(client.t("*** Found your username"))
  180. // we don't need to updateNickMask here since nickMask is not used for anything yet
  181. } else {
  182. client.Notice(client.t("*** Got a malformed username, ignoring"))
  183. }
  184. } else {
  185. client.Notice(client.t("*** Could not find your username"))
  186. }
  187. }
  188. func (client *Client) isAuthorized(config *Config) bool {
  189. saslSent := client.account != ""
  190. // PASS requirement
  191. if (config.Server.passwordBytes != nil) && !client.sentPassCommand && !(config.Accounts.SkipServerPassword && saslSent) {
  192. return false
  193. }
  194. // Tor connections may be required to authenticate with SASL
  195. if client.isTor && config.Server.TorListeners.RequireSasl && !saslSent {
  196. return false
  197. }
  198. // finally, enforce require-sasl
  199. return !config.Accounts.RequireSasl.Enabled || saslSent || utils.IPInNets(client.IP(), config.Accounts.RequireSasl.exemptedNets)
  200. }
  201. func (client *Client) resetFakelag() {
  202. var flc FakelagConfig = client.server.Config().Fakelag
  203. flc.Enabled = flc.Enabled && !client.HasRoleCapabs("nofakelag")
  204. client.fakelag.Initialize(flc)
  205. }
  206. // IP returns the IP address of this client.
  207. func (client *Client) IP() net.IP {
  208. client.stateMutex.RLock()
  209. defer client.stateMutex.RUnlock()
  210. if client.proxiedIP != nil {
  211. return client.proxiedIP
  212. }
  213. return client.realIP
  214. }
  215. // IPString returns the IP address of this client as a string.
  216. func (client *Client) IPString() string {
  217. ip := client.IP().String()
  218. if 0 < len(ip) && ip[0] == ':' {
  219. ip = "0" + ip
  220. }
  221. return ip
  222. }
  223. //
  224. // command goroutine
  225. //
  226. func (client *Client) recomputeMaxlens() int {
  227. maxlenRest := 512
  228. if client.capabilities.Has(caps.MaxLine) {
  229. maxlenRest = client.server.Limits().LineLen.Rest
  230. }
  231. atomic.StoreUint32(&client.maxlenRest, uint32(maxlenRest))
  232. return maxlenRest
  233. }
  234. // allow these negotiated length limits to be read without locks; this is a convenience
  235. // so that Client.Send doesn't have to acquire any Client locks
  236. func (client *Client) MaxlenRest() int {
  237. return int(atomic.LoadUint32(&client.maxlenRest))
  238. }
  239. func (client *Client) run() {
  240. var err error
  241. var isExiting bool
  242. var line string
  243. var msg ircmsg.IrcMessage
  244. defer func() {
  245. if r := recover(); r != nil {
  246. client.server.logger.Error("internal",
  247. fmt.Sprintf("Client caused panic: %v\n%s", r, debug.Stack()))
  248. if client.server.RecoverFromErrors() {
  249. client.server.logger.Error("internal", "Disconnecting client and attempting to recover")
  250. } else {
  251. panic(r)
  252. }
  253. }
  254. // ensure client connection gets closed
  255. client.destroy(false)
  256. }()
  257. client.idletimer.Initialize(client)
  258. client.nickTimer.Initialize(client)
  259. client.resetFakelag()
  260. firstLine := true
  261. for {
  262. maxlenRest := client.recomputeMaxlens()
  263. line, err = client.socket.Read()
  264. if err != nil {
  265. quitMessage := "connection closed"
  266. if err == errReadQ {
  267. quitMessage = "readQ exceeded"
  268. }
  269. client.Quit(quitMessage)
  270. break
  271. }
  272. if client.server.logger.IsLoggingRawIO() {
  273. client.server.logger.Debug("userinput", client.nick, "<- ", line)
  274. }
  275. // special-cased handling of PROXY protocol, see `handleProxyCommand` for details:
  276. if firstLine {
  277. firstLine = false
  278. if strings.HasPrefix(line, "PROXY") {
  279. err = handleProxyCommand(client.server, client, line)
  280. if err != nil {
  281. break
  282. } else {
  283. continue
  284. }
  285. }
  286. }
  287. msg, err = ircmsg.ParseLineStrict(line, true, maxlenRest)
  288. if err == ircmsg.ErrorLineIsEmpty {
  289. continue
  290. } else if err == ircmsg.ErrorLineTooLong {
  291. client.Send(nil, client.server.name, ERR_INPUTTOOLONG, client.nick, client.t("Input line too long"))
  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. // tryResume tries to resume if the client asked us to.
  326. func (client *Client) tryResume() (success bool) {
  327. server := client.server
  328. config := server.Config()
  329. defer func() {
  330. if !success {
  331. client.resumeDetails = nil
  332. }
  333. }()
  334. timestamp := client.resumeDetails.Timestamp
  335. var timestampString string
  336. if !timestamp.IsZero() {
  337. timestampString = timestamp.UTC().Format(IRCv3TimestampFormat)
  338. }
  339. oldClient := server.resumeManager.VerifyToken(client.resumeDetails.PresentedToken)
  340. if oldClient == nil {
  341. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection, token is not valid"))
  342. return
  343. }
  344. oldNick := oldClient.Nick()
  345. oldNickmask := oldClient.NickMaskString()
  346. resumeAllowed := config.Server.AllowPlaintextResume || (oldClient.HasMode(modes.TLS) && client.HasMode(modes.TLS))
  347. if !resumeAllowed {
  348. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection, old and new clients must have TLS"))
  349. return
  350. }
  351. if oldClient.isTor != client.isTor {
  352. client.Send(nil, server.name, "RESUME", "ERR", client.t("Cannot resume connection from Tor to non-Tor or vice versa"))
  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 map[string]string
  466. if serverTime {
  467. tags = map[string]string{"time": item.Time.Format(IRCv3TimestampFormat)}
  468. }
  469. rb.AddSplitMessageFromClient(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. // updateNickMaskNoMutex updates the casefolded nickname and nickmask, not acquiring any mutexes.
  653. func (client *Client) updateNickMaskNoMutex() {
  654. client.hostname = client.getVHostNoMutex()
  655. if client.hostname == "" {
  656. client.hostname = client.rawHostname
  657. }
  658. cfhostname, err := Casefold(client.hostname)
  659. if err != nil {
  660. client.server.logger.Error("internal", "hostname couldn't be casefolded", client.hostname, err.Error())
  661. cfhostname = client.hostname // YOLO
  662. }
  663. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  664. client.nickMaskCasefolded = fmt.Sprintf("%s!%s@%s", client.nickCasefolded, strings.ToLower(client.username), cfhostname)
  665. }
  666. // AllNickmasks returns all the possible nickmasks for the client.
  667. func (client *Client) AllNickmasks() (masks []string) {
  668. client.stateMutex.RLock()
  669. nick := client.nickCasefolded
  670. username := client.username
  671. rawHostname := client.rawHostname
  672. vhost := client.getVHostNoMutex()
  673. client.stateMutex.RUnlock()
  674. username = strings.ToLower(username)
  675. if len(vhost) > 0 {
  676. cfvhost, err := Casefold(vhost)
  677. if err == nil {
  678. masks = append(masks, fmt.Sprintf("%s!%s@%s", nick, username, cfvhost))
  679. }
  680. }
  681. var rawhostmask string
  682. cfrawhost, err := Casefold(rawHostname)
  683. if err == nil {
  684. rawhostmask = fmt.Sprintf("%s!%s@%s", nick, username, cfrawhost)
  685. masks = append(masks, rawhostmask)
  686. }
  687. ipmask := fmt.Sprintf("%s!%s@%s", nick, username, client.IPString())
  688. if ipmask != rawhostmask {
  689. masks = append(masks, ipmask)
  690. }
  691. return
  692. }
  693. // LoggedIntoAccount returns true if this client is logged into an account.
  694. func (client *Client) LoggedIntoAccount() bool {
  695. return client.Account() != ""
  696. }
  697. // RplISupport outputs our ISUPPORT lines to the client. This is used on connection and in VERSION responses.
  698. func (client *Client) RplISupport(rb *ResponseBuffer) {
  699. translatedISupport := client.t("are supported by this server")
  700. nick := client.Nick()
  701. for _, cachedTokenLine := range client.server.ISupport().CachedReply {
  702. length := len(cachedTokenLine) + 2
  703. tokenline := make([]string, length)
  704. tokenline[0] = nick
  705. copy(tokenline[1:], cachedTokenLine)
  706. tokenline[length-1] = translatedISupport
  707. rb.Add(nil, client.server.name, RPL_ISUPPORT, tokenline...)
  708. }
  709. }
  710. // Quit sets the given quit message for the client.
  711. // (You must ensure separately that destroy() is called, e.g., by returning `true` from
  712. // the command handler or calling it yourself.)
  713. func (client *Client) Quit(message string) {
  714. client.stateMutex.Lock()
  715. alreadyQuit := client.isQuitting
  716. if !alreadyQuit {
  717. client.isQuitting = true
  718. client.quitMessage = message
  719. }
  720. registered := client.registered
  721. prefix := client.nickMaskString
  722. client.stateMutex.Unlock()
  723. if alreadyQuit {
  724. return
  725. }
  726. var finalData []byte
  727. // #364: don't send QUIT lines to unregistered clients
  728. if registered {
  729. quitMsg := ircmsg.MakeMessage(nil, prefix, "QUIT", message)
  730. finalData, _ = quitMsg.LineBytesStrict(false, 512)
  731. }
  732. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  733. errorMsgBytes, _ := errorMsg.LineBytesStrict(false, 512)
  734. finalData = append(finalData, errorMsgBytes...)
  735. client.socket.SetFinalData(finalData)
  736. }
  737. // destroy gets rid of a client, removes them from server lists etc.
  738. func (client *Client) destroy(beingResumed bool) {
  739. // allow destroy() to execute at most once
  740. client.stateMutex.Lock()
  741. isDestroyed := client.isDestroyed
  742. client.isDestroyed = true
  743. quitMessage := client.quitMessage
  744. nickMaskString := client.nickMaskString
  745. accountName := client.accountName
  746. client.stateMutex.Unlock()
  747. if isDestroyed {
  748. return
  749. }
  750. // see #235: deduplicating the list of PART recipients uses (comparatively speaking)
  751. // a lot of RAM, so limit concurrency to avoid thrashing
  752. client.server.semaphores.ClientDestroy.Acquire()
  753. defer client.server.semaphores.ClientDestroy.Release()
  754. if beingResumed {
  755. client.server.logger.Debug("quit", fmt.Sprintf("%s is being resumed", client.nick))
  756. } else {
  757. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  758. }
  759. // send quit/error message to client if they haven't been sent already
  760. client.Quit("Connection closed")
  761. if !beingResumed {
  762. client.server.whoWas.Append(client.WhoWas())
  763. }
  764. // remove from connection limits
  765. if client.isTor {
  766. client.server.torLimiter.RemoveClient()
  767. } else {
  768. client.server.connectionLimiter.RemoveClient(client.IP())
  769. }
  770. client.server.resumeManager.Delete(client)
  771. // alert monitors
  772. client.server.monitorManager.AlertAbout(client, false)
  773. // clean up monitor state
  774. client.server.monitorManager.RemoveAll(client)
  775. // clean up channels
  776. friends := make(ClientSet)
  777. for _, channel := range client.Channels() {
  778. if !beingResumed {
  779. channel.Quit(client)
  780. channel.history.Add(history.Item{
  781. Type: history.Quit,
  782. Nick: nickMaskString,
  783. AccountName: accountName,
  784. Message: utils.MakeSplitMessage(quitMessage, true),
  785. })
  786. }
  787. for _, member := range channel.Members() {
  788. friends.Add(member)
  789. }
  790. }
  791. friends.Remove(client)
  792. // clean up server
  793. if !beingResumed {
  794. client.server.clients.Remove(client)
  795. }
  796. // clean up self
  797. client.idletimer.Stop()
  798. client.nickTimer.Stop()
  799. client.server.accounts.Logout(client)
  800. client.socket.Close()
  801. // send quit messages to friends
  802. if !beingResumed {
  803. if client.Registered() {
  804. client.server.stats.ChangeTotal(-1)
  805. }
  806. if client.HasMode(modes.Invisible) {
  807. client.server.stats.ChangeInvisible(-1)
  808. }
  809. if client.HasMode(modes.Operator) || client.HasMode(modes.LocalOperator) {
  810. client.server.stats.ChangeOperators(-1)
  811. }
  812. for friend := range friends {
  813. if quitMessage == "" {
  814. quitMessage = "Exited"
  815. }
  816. friend.Send(nil, client.nickMaskString, "QUIT", quitMessage)
  817. }
  818. }
  819. if !client.exitedSnomaskSent {
  820. if beingResumed {
  821. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r is resuming their connection, old client has been destroyed"), client.nick))
  822. } else {
  823. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  824. }
  825. }
  826. }
  827. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  828. // Adds account-tag to the line as well.
  829. func (client *Client) SendSplitMsgFromClient(from *Client, tags map[string]string, command, target string, message utils.SplitMessage) {
  830. client.sendSplitMsgFromClientInternal(false, time.Time{}, from.NickMaskString(), from.AccountName(), tags, command, target, message)
  831. }
  832. func (client *Client) sendSplitMsgFromClientInternal(blocking bool, serverTime time.Time, nickmask, accountName string, tags map[string]string, command, target string, message utils.SplitMessage) {
  833. if client.capabilities.Has(caps.MaxLine) || message.Wrapped == nil {
  834. client.sendFromClientInternal(blocking, serverTime, message.Msgid, nickmask, accountName, tags, command, target, message.Message)
  835. } else {
  836. for _, messagePair := range message.Wrapped {
  837. client.sendFromClientInternal(blocking, serverTime, messagePair.Msgid, nickmask, accountName, tags, command, target, messagePair.Message)
  838. }
  839. }
  840. }
  841. // SendFromClient sends an IRC line coming from a specific client.
  842. // Adds account-tag to the line as well.
  843. func (client *Client) SendFromClient(msgid string, from *Client, tags map[string]string, command string, params ...string) error {
  844. return client.sendFromClientInternal(false, time.Time{}, msgid, from.NickMaskString(), from.AccountName(), tags, command, params...)
  845. }
  846. // this is SendFromClient, but directly exposing nickmask and accountName,
  847. // for things like history replay and CHGHOST where they no longer (necessarily)
  848. // correspond to the current state of a client
  849. func (client *Client) sendFromClientInternal(blocking bool, serverTime time.Time, msgid string, nickmask, accountName string, tags map[string]string, command string, params ...string) error {
  850. msg := ircmsg.MakeMessage(tags, nickmask, command, params...)
  851. // attach account-tag
  852. if client.capabilities.Has(caps.AccountTag) && accountName != "*" {
  853. msg.SetTag("account", accountName)
  854. }
  855. // attach message-id
  856. if msgid != "" && client.capabilities.Has(caps.MessageTags) {
  857. msg.SetTag("draft/msgid", msgid)
  858. }
  859. // attach server-time
  860. if client.capabilities.Has(caps.ServerTime) {
  861. msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  862. }
  863. return client.SendRawMessage(msg, blocking)
  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[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.IndexByte(lastParam, ' ') == -1 {
  884. message.Params[len(message.Params)-1] = lastParam + " "
  885. usedTrailingHack = true
  886. }
  887. }
  888. // assemble message
  889. maxlenRest := client.MaxlenRest()
  890. line, err := message.LineBytesStrict(false, 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.LineBytesStrict(false, 0)
  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:], "\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. // Send sends an IRC line to the client.
  919. func (client *Client) Send(tags map[string]string, prefix string, command string, params ...string) error {
  920. msg := ircmsg.MakeMessage(tags, prefix, command, params...)
  921. if client.capabilities.Has(caps.ServerTime) && !msg.HasTag("time") {
  922. msg.SetTag("time", time.Now().UTC().Format(IRCv3TimestampFormat))
  923. }
  924. return client.SendRawMessage(msg, false)
  925. }
  926. // Notice sends the client a notice from the server.
  927. func (client *Client) Notice(text string) {
  928. limit := 400
  929. if client.capabilities.Has(caps.MaxLine) {
  930. limit = client.server.Limits().LineLen.Rest - 110
  931. }
  932. lines := utils.WordWrap(text, limit)
  933. // force blank lines to be sent if we receive them
  934. if len(lines) == 0 {
  935. lines = []string{""}
  936. }
  937. for _, line := range lines {
  938. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  939. }
  940. }
  941. func (client *Client) addChannel(channel *Channel) {
  942. client.stateMutex.Lock()
  943. client.channels[channel] = true
  944. client.stateMutex.Unlock()
  945. }
  946. func (client *Client) removeChannel(channel *Channel) {
  947. client.stateMutex.Lock()
  948. delete(client.channels, channel)
  949. client.stateMutex.Unlock()
  950. }
  951. // Records that the client has been invited to join an invite-only channel
  952. func (client *Client) Invite(casefoldedChannel string) {
  953. client.stateMutex.Lock()
  954. defer client.stateMutex.Unlock()
  955. if client.invitedTo == nil {
  956. client.invitedTo = make(map[string]bool)
  957. }
  958. client.invitedTo[casefoldedChannel] = true
  959. }
  960. // Checks that the client was invited to join a given channel
  961. func (client *Client) CheckInvited(casefoldedChannel string) (invited bool) {
  962. client.stateMutex.Lock()
  963. defer client.stateMutex.Unlock()
  964. invited = client.invitedTo[casefoldedChannel]
  965. // joining an invited channel "uses up" your invite, so you can't rejoin on kick
  966. delete(client.invitedTo, casefoldedChannel)
  967. return
  968. }