Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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