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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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. "errors"
  8. "fmt"
  9. "log"
  10. "net"
  11. "runtime/debug"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/goshuirc/irc-go/ircfmt"
  17. "github.com/goshuirc/irc-go/ircmsg"
  18. ident "github.com/oragono/go-ident"
  19. "github.com/oragono/oragono/irc/sno"
  20. )
  21. const (
  22. // IdleTimeout is how long without traffic before a client's considered idle.
  23. IdleTimeout = time.Minute + time.Second*30
  24. // QuitTimeout is how long without traffic (after they're considered idle) that clients are killed.
  25. QuitTimeout = time.Minute
  26. // IdentTimeoutSeconds is how many seconds before our ident (username) check times out.
  27. IdentTimeoutSeconds = 5
  28. )
  29. var (
  30. // TimeoutStatedSeconds is how many seconds before clients are timed out (IdleTimeout plus QuitTimeout).
  31. TimeoutStatedSeconds = strconv.Itoa(int((IdleTimeout + QuitTimeout).Seconds()))
  32. // ErrNickAlreadySet is a weird error that's sent when the server's consistency has been compromised.
  33. ErrNickAlreadySet = errors.New("Nickname is already set")
  34. )
  35. // Client is an IRC client.
  36. type Client struct {
  37. account *ClientAccount
  38. atime time.Time
  39. authorized bool
  40. awayMessage string
  41. capabilities CapabilitySet
  42. capState CapState
  43. capVersion CapVersion
  44. certfp string
  45. channels ChannelSet
  46. class *OperClass
  47. ctime time.Time
  48. destroyMutex sync.Mutex
  49. exitedSnomaskSent bool
  50. flags map[Mode]bool
  51. hasQuit bool
  52. hops int
  53. hostname string
  54. idleTimer *time.Timer
  55. isDestroyed bool
  56. isQuitting bool
  57. monitoring map[string]bool
  58. nick string
  59. nickCasefolded string
  60. nickMaskCasefolded string
  61. nickMaskString string // cache for nickmask string since it's used with lots of replies
  62. operName string
  63. quitMessageSent bool
  64. quitMutex sync.Mutex
  65. quitTimer *time.Timer
  66. rawHostname string
  67. realname string
  68. registered bool
  69. saslInProgress bool
  70. saslMechanism string
  71. saslValue string
  72. server *Server
  73. socket *Socket
  74. timerMutex sync.Mutex
  75. username string
  76. vhost string
  77. whoisLine string
  78. }
  79. // NewClient returns a client with all the appropriate info setup.
  80. func NewClient(server *Server, conn net.Conn, isTLS bool) *Client {
  81. now := time.Now()
  82. socket := NewSocket(conn, server.MaxSendQBytes)
  83. go socket.RunSocketWriter()
  84. client := &Client{
  85. atime: now,
  86. authorized: server.password == nil,
  87. capabilities: make(CapabilitySet),
  88. capState: CapNone,
  89. capVersion: Cap301,
  90. channels: make(ChannelSet),
  91. ctime: now,
  92. flags: make(map[Mode]bool),
  93. monitoring: make(map[string]bool),
  94. server: server,
  95. socket: &socket,
  96. account: &NoAccount,
  97. nick: "*", // * is used until actual nick is given
  98. nickCasefolded: "*",
  99. nickMaskString: "*", // * is used until actual nick is given
  100. }
  101. if isTLS {
  102. client.flags[TLS] = true
  103. // error is not useful to us here anyways so we can ignore it
  104. client.certfp, _ = client.socket.CertFP()
  105. }
  106. if server.checkIdent {
  107. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  108. serverPort, _ := strconv.Atoi(serverPortString)
  109. if err != nil {
  110. log.Fatal(err)
  111. }
  112. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  113. clientPort, _ := strconv.Atoi(clientPortString)
  114. if err != nil {
  115. log.Fatal(err)
  116. }
  117. client.Notice("*** Looking up your username")
  118. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  119. if err == nil {
  120. username := resp.Identifier
  121. _, err := CasefoldName(username) // ensure it's a valid username
  122. if err == nil {
  123. client.Notice("*** Found your username")
  124. client.username = username
  125. // we don't need to updateNickMask here since nickMask is not used for anything yet
  126. } else {
  127. client.Notice("*** Got a malformed username, ignoring")
  128. }
  129. } else {
  130. client.Notice("*** Could not find your username")
  131. }
  132. }
  133. client.Touch()
  134. go client.run()
  135. return client
  136. }
  137. // IP returns the IP address of this client.
  138. func (client *Client) IP() net.IP {
  139. return net.ParseIP(IPString(client.socket.conn.RemoteAddr()))
  140. }
  141. // IPString returns the IP address of this client as a string.
  142. func (client *Client) IPString() string {
  143. ip := client.IP().String()
  144. if 0 < len(ip) && ip[0] == ':' {
  145. ip = "0" + ip
  146. }
  147. return ip
  148. }
  149. //
  150. // command goroutine
  151. //
  152. func (client *Client) maxlens() (int, int) {
  153. maxlenTags := 512
  154. maxlenRest := 512
  155. if client.capabilities[MessageTags] {
  156. maxlenTags = 4096
  157. }
  158. if client.capabilities[MaxLine] {
  159. if client.server.limits.LineLen.Tags > maxlenTags {
  160. maxlenTags = client.server.limits.LineLen.Tags
  161. }
  162. maxlenRest = client.server.limits.LineLen.Rest
  163. }
  164. return maxlenTags, maxlenRest
  165. }
  166. func (client *Client) run() {
  167. var err error
  168. var isExiting bool
  169. var line string
  170. var msg ircmsg.IrcMessage
  171. // Set the hostname for this client
  172. client.rawHostname = AddrLookupHostname(client.socket.conn.RemoteAddr())
  173. for {
  174. line, err = client.socket.Read()
  175. if err != nil {
  176. client.Quit("connection closed")
  177. break
  178. }
  179. maxlenTags, maxlenRest := client.maxlens()
  180. client.server.logger.Debug("userinput ", client.nick, "<- ", line)
  181. msg, err = ircmsg.ParseLineMaxLen(line, maxlenTags, maxlenRest)
  182. if err == ircmsg.ErrorLineIsEmpty {
  183. continue
  184. } else if err != nil {
  185. client.Quit("received malformed line")
  186. break
  187. }
  188. cmd, exists := Commands[msg.Command]
  189. if !exists {
  190. if len(msg.Command) > 0 {
  191. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, "Unknown command")
  192. } else {
  193. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", "No command given")
  194. }
  195. continue
  196. }
  197. isExiting = cmd.Run(client.server, client, msg)
  198. if isExiting || client.isQuitting {
  199. break
  200. }
  201. }
  202. // ensure client connection gets closed
  203. client.destroy()
  204. }
  205. //
  206. // idle, quit, timers and timeouts
  207. //
  208. // Active updates when the client was last 'active' (i.e. the user should be sitting in front of their client).
  209. func (client *Client) Active() {
  210. client.atime = time.Now()
  211. }
  212. // Touch marks the client as alive (as it it has a connection to us and we
  213. // can receive messages from it), and resets when we'll send the client a
  214. // keepalive PING.
  215. func (client *Client) Touch() {
  216. client.timerMutex.Lock()
  217. defer client.timerMutex.Unlock()
  218. if client.quitTimer != nil {
  219. client.quitTimer.Stop()
  220. }
  221. if client.idleTimer == nil {
  222. client.idleTimer = time.AfterFunc(IdleTimeout, client.connectionIdle)
  223. } else {
  224. client.idleTimer.Reset(IdleTimeout)
  225. }
  226. }
  227. // connectionIdle is run when the client has not sent us any data for a while,
  228. // sends the client a PING and starts the quit timeout.
  229. func (client *Client) connectionIdle() {
  230. client.timerMutex.Lock()
  231. defer client.timerMutex.Unlock()
  232. client.Send(nil, "", "PING", client.nick)
  233. if client.quitTimer == nil {
  234. client.quitTimer = time.AfterFunc(QuitTimeout, client.connectionTimeout)
  235. } else {
  236. client.quitTimer.Reset(QuitTimeout)
  237. }
  238. }
  239. // connectionTimeout runs after connectionIdle has been run, if we do not receive a
  240. // ping or any other activity back from the client. When this happens we assume the
  241. // connection has died and remove the client from the network.
  242. func (client *Client) connectionTimeout() {
  243. client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TimeoutStatedSeconds))
  244. client.isQuitting = true
  245. }
  246. //
  247. // server goroutine
  248. //
  249. // Register sets the client details as appropriate when entering the network.
  250. func (client *Client) Register() {
  251. if client.registered {
  252. return
  253. }
  254. client.registered = true
  255. client.Touch()
  256. client.updateNickMask()
  257. client.alertMonitors()
  258. }
  259. // IdleTime returns how long this client's been idle.
  260. func (client *Client) IdleTime() time.Duration {
  261. return time.Since(client.atime)
  262. }
  263. // SignonTime returns this client's signon time as a unix timestamp.
  264. func (client *Client) SignonTime() int64 {
  265. return client.ctime.Unix()
  266. }
  267. // IdleSeconds returns the number of seconds this client's been idle.
  268. func (client *Client) IdleSeconds() uint64 {
  269. return uint64(client.IdleTime().Seconds())
  270. }
  271. // HasNick returns true if the client's nickname is set (used in registration).
  272. func (client *Client) HasNick() bool {
  273. return client.nick != "" && client.nick != "*"
  274. }
  275. // HasUsername returns true if the client's username is set (used in registration).
  276. func (client *Client) HasUsername() bool {
  277. return client.username != "" && client.username != "*"
  278. }
  279. // HasCapabs returns true if client has the given (role) capabilities.
  280. func (client *Client) HasCapabs(capabs ...string) bool {
  281. if client.class == nil {
  282. return false
  283. }
  284. for _, capab := range capabs {
  285. if !client.class.Capabilities[capab] {
  286. return false
  287. }
  288. }
  289. return true
  290. }
  291. // ModeString returns the mode string for this client.
  292. func (client *Client) ModeString() (str string) {
  293. str = "+"
  294. for flag := range client.flags {
  295. str += flag.String()
  296. }
  297. return
  298. }
  299. // Friends refers to clients that share a channel with this client.
  300. func (client *Client) Friends(Capabilities ...Capability) ClientSet {
  301. friends := make(ClientSet)
  302. // make sure that I have the right caps
  303. hasCaps := true
  304. for _, Cap := range Capabilities {
  305. if !client.capabilities[Cap] {
  306. hasCaps = false
  307. break
  308. }
  309. }
  310. if hasCaps {
  311. friends.Add(client)
  312. }
  313. for channel := range client.channels {
  314. channel.membersMutex.RLock()
  315. for member := range channel.members {
  316. // make sure they have all the required caps
  317. for _, Cap := range Capabilities {
  318. if !member.capabilities[Cap] {
  319. continue
  320. }
  321. }
  322. friends.Add(member)
  323. }
  324. channel.membersMutex.RUnlock()
  325. }
  326. return friends
  327. }
  328. // updateNick updates the casefolded nickname.
  329. func (client *Client) updateNick() {
  330. casefoldedName, err := CasefoldName(client.nick)
  331. if err != nil {
  332. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
  333. debug.PrintStack()
  334. }
  335. client.nickCasefolded = casefoldedName
  336. }
  337. // updateNickMask updates the casefolded nickname and nickmask.
  338. func (client *Client) updateNickMask() {
  339. client.updateNick()
  340. if len(client.vhost) > 0 {
  341. client.hostname = client.vhost
  342. } else {
  343. client.hostname = client.rawHostname
  344. }
  345. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  346. nickMaskCasefolded, err := Casefold(client.nickMaskString)
  347. if err != nil {
  348. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
  349. debug.PrintStack()
  350. }
  351. client.nickMaskCasefolded = nickMaskCasefolded
  352. }
  353. // AllNickmasks returns all the possible nickmasks for the client.
  354. func (client *Client) AllNickmasks() []string {
  355. var masks []string
  356. var mask string
  357. var err error
  358. if len(client.vhost) > 0 {
  359. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.vhost))
  360. if err == nil {
  361. masks = append(masks, mask)
  362. }
  363. }
  364. mask, err = Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.rawHostname))
  365. if err == nil {
  366. masks = append(masks, mask)
  367. }
  368. mask2, err := Casefold(fmt.Sprintf("%s!%s@%s", client.nick, client.username, IPString(client.socket.conn.RemoteAddr())))
  369. if err == nil && mask2 != mask {
  370. masks = append(masks, mask2)
  371. }
  372. return masks
  373. }
  374. // SetNickname sets the very first nickname for the client.
  375. func (client *Client) SetNickname(nickname string) error {
  376. if client.HasNick() {
  377. client.server.logger.Error("nick", fmt.Sprintf("%s nickname already set, something is wrong with server consistency", client.nickMaskString))
  378. return ErrNickAlreadySet
  379. }
  380. err := client.server.clients.Add(client, nickname)
  381. if err == nil {
  382. client.nick = nickname
  383. client.updateNick()
  384. }
  385. return err
  386. }
  387. // ChangeNickname changes the existing nickname of the client.
  388. func (client *Client) ChangeNickname(nickname string) error {
  389. origNickMask := client.nickMaskString
  390. err := client.server.clients.Replace(client.nick, nickname, client)
  391. if err == nil {
  392. client.server.logger.Debug("nick", fmt.Sprintf("%s changed nickname to %s", client.nick, nickname))
  393. client.server.snomasks.Send(sno.LocalNicks, fmt.Sprintf(ircfmt.Unescape("$%s$r changed nickname to %s"), client.nick, nickname))
  394. client.server.whoWas.Append(client)
  395. client.nick = nickname
  396. client.updateNickMask()
  397. for friend := range client.Friends() {
  398. friend.Send(nil, origNickMask, "NICK", nickname)
  399. }
  400. }
  401. return err
  402. }
  403. // Quit sends the given quit message to the client (but does not destroy them).
  404. func (client *Client) Quit(message string) {
  405. client.quitMutex.Lock()
  406. defer client.quitMutex.Unlock()
  407. if !client.quitMessageSent {
  408. quitMsg := ircmsg.MakeMessage(nil, client.nickMaskString, "QUIT", message)
  409. quitLine, _ := quitMsg.Line()
  410. errorMsg := ircmsg.MakeMessage(nil, "", "ERROR", message)
  411. errorLine, _ := errorMsg.Line()
  412. client.socket.SetFinalData(quitLine + errorLine)
  413. client.quitMessageSent = true
  414. }
  415. }
  416. // destroy gets rid of a client, removes them from server lists etc.
  417. func (client *Client) destroy() {
  418. client.destroyMutex.Lock()
  419. defer client.destroyMutex.Unlock()
  420. if client.isDestroyed {
  421. return
  422. }
  423. client.server.logger.Debug("quit", fmt.Sprintf("%s is no longer on the server", client.nick))
  424. // send quit/error message to client if they haven't been sent already
  425. client.Quit("Connection closed")
  426. client.isDestroyed = true
  427. client.server.whoWas.Append(client)
  428. friends := client.Friends()
  429. friends.Remove(client)
  430. // remove from connection limits
  431. ipaddr := client.IP()
  432. // this check shouldn't be required but eh
  433. if ipaddr != nil {
  434. client.server.connectionLimitsMutex.Lock()
  435. client.server.connectionLimits.RemoveClient(ipaddr)
  436. client.server.connectionLimitsMutex.Unlock()
  437. }
  438. // remove from opers list
  439. _, exists := client.server.currentOpers[client]
  440. if exists {
  441. delete(client.server.currentOpers, client)
  442. }
  443. // alert monitors
  444. for _, mClient := range client.server.monitoring[client.nickCasefolded] {
  445. mClient.Send(nil, client.server.name, RPL_MONOFFLINE, mClient.nick, client.nick)
  446. }
  447. // remove my monitors
  448. client.clearMonitorList()
  449. // clean up channels
  450. client.server.channelJoinPartMutex.Lock()
  451. for channel := range client.channels {
  452. channel.Quit(client, &friends)
  453. }
  454. client.server.channelJoinPartMutex.Unlock()
  455. // clean up server
  456. client.server.clients.Remove(client)
  457. // clean up self
  458. if client.idleTimer != nil {
  459. client.idleTimer.Stop()
  460. }
  461. if client.quitTimer != nil {
  462. client.quitTimer.Stop()
  463. }
  464. client.socket.Close()
  465. // send quit messages to friends
  466. for friend := range friends {
  467. //TODO(dan): store quit message in user, if exists use that instead here
  468. friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
  469. }
  470. if !client.exitedSnomaskSent {
  471. client.server.snomasks.Send(sno.LocalQuits, fmt.Sprintf(ircfmt.Unescape("%s$r exited the network"), client.nick))
  472. }
  473. }
  474. // SendSplitMsgFromClient sends an IRC PRIVMSG/NOTICE coming from a specific client.
  475. // Adds account-tag to the line as well.
  476. func (client *Client) SendSplitMsgFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command, target string, message SplitMessage) {
  477. if client.capabilities[MaxLine] {
  478. client.SendFromClient(msgid, from, tags, command, target, message.ForMaxLine)
  479. } else {
  480. for _, str := range message.For512 {
  481. client.SendFromClient(msgid, from, tags, command, target, str)
  482. }
  483. }
  484. }
  485. // SendFromClient sends an IRC line coming from a specific client.
  486. // Adds account-tag to the line as well.
  487. func (client *Client) SendFromClient(msgid string, from *Client, tags *map[string]ircmsg.TagValue, command string, params ...string) error {
  488. // attach account-tag
  489. if client.capabilities[AccountTag] && from.account != &NoAccount {
  490. if tags == nil {
  491. tags = ircmsg.MakeTags("account", from.account.Name)
  492. } else {
  493. (*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
  494. }
  495. }
  496. // attach message-id
  497. if len(msgid) > 0 && client.capabilities[MessageIDs] {
  498. if tags == nil {
  499. tags = ircmsg.MakeTags("draft/msgid", msgid)
  500. } else {
  501. (*tags)["draft/msgid"] = ircmsg.MakeTagValue(msgid)
  502. }
  503. }
  504. return client.Send(tags, from.nickMaskString, command, params...)
  505. }
  506. var (
  507. // these are all the output commands that MUST have their last param be a trailing.
  508. // this is needed because silly clients like to treat trailing as separate from the
  509. // other params in messages.
  510. commandsThatMustUseTrailing = map[string]bool{
  511. "PRIVMSG": true,
  512. "NOTICE": true,
  513. RPL_WHOISCHANNELS: true,
  514. RPL_USERHOST: true,
  515. }
  516. )
  517. // Send sends an IRC line to the client.
  518. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  519. // attach server-time
  520. if client.capabilities[ServerTime] {
  521. t := time.Now().UTC().Format("2006-01-02T15:04:05.999Z")
  522. if tags == nil {
  523. tags = ircmsg.MakeTags("time", t)
  524. } else {
  525. (*tags)["time"] = ircmsg.MakeTagValue(t)
  526. }
  527. }
  528. // force trailing, if message requires it
  529. var usedTrailingHack bool
  530. if commandsThatMustUseTrailing[strings.ToUpper(command)] && len(params) > 0 {
  531. lastParam := params[len(params)-1]
  532. // to force trailing, we ensure the final param contains a space
  533. if !strings.Contains(lastParam, " ") {
  534. params[len(params)-1] = lastParam + " "
  535. usedTrailingHack = true
  536. }
  537. }
  538. // send out the message
  539. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  540. maxlenTags, maxlenRest := client.maxlens()
  541. line, err := message.LineMaxLen(maxlenTags, maxlenRest)
  542. if err != nil {
  543. // try not to fail quietly - especially useful when running tests, as a note to dig deeper
  544. // log.Println("Error assembling message:")
  545. // spew.Dump(message)
  546. // debug.PrintStack()
  547. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  548. line, _ := message.Line()
  549. client.socket.Write(line)
  550. return err
  551. }
  552. // is we used the trailing hack, we need to strip the final space we appended earlier
  553. if usedTrailingHack {
  554. line = line[:len(line)-3] + "\r\n"
  555. }
  556. client.server.logger.Debug("useroutput", client.nick, " ->", strings.TrimRight(line, "\r\n"))
  557. client.socket.Write(line)
  558. return nil
  559. }
  560. // Notice sends the client a notice from the server.
  561. func (client *Client) Notice(text string) {
  562. limit := 400
  563. if client.capabilities[MaxLine] {
  564. limit = client.server.limits.LineLen.Rest - 110
  565. }
  566. lines := wordWrap(text, limit)
  567. for _, line := range lines {
  568. client.Send(nil, client.server.name, "NOTICE", client.nick, line)
  569. }
  570. }