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

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