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

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