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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // Copyright (c) 2014-2015 Edmund Huber
  3. // Copyright (c) 2016- Daniel Oaks <daniel@danieloaks.net>
  4. // released under the MIT license
  5. package irc
  6. import (
  7. "fmt"
  8. "log"
  9. "net"
  10. "strconv"
  11. "time"
  12. "github.com/DanielOaks/girc-go/ircmsg"
  13. "github.com/DanielOaks/go-ident"
  14. )
  15. const (
  16. IDLE_TIMEOUT = time.Minute + time.Second*30 // how long before a client is considered idle
  17. QUIT_TIMEOUT = time.Minute // how long after idle before a client is kicked
  18. IdentTimeoutSeconds = 8
  19. )
  20. var (
  21. TIMEOUT_STATED_SECONDS = strconv.Itoa(int((IDLE_TIMEOUT + QUIT_TIMEOUT).Seconds()))
  22. )
  23. type Client struct {
  24. account *ClientAccount
  25. atime time.Time
  26. authorized bool
  27. awayMessage string
  28. capabilities CapabilitySet
  29. capState CapState
  30. certfp string
  31. channels ChannelSet
  32. ctime time.Time
  33. flags map[UserMode]bool
  34. isDestroyed bool
  35. isQuitting bool
  36. hasQuit bool
  37. hops uint
  38. hostname string
  39. idleTimer *time.Timer
  40. nick string
  41. nickCasefolded string
  42. nickMaskString string // cache for nickmask string since it's used with lots of replies
  43. nickMaskCasefolded string
  44. quitTimer *time.Timer
  45. realname string
  46. registered bool
  47. saslInProgress bool
  48. saslMechanism string
  49. saslValue string
  50. server *Server
  51. socket *Socket
  52. username string
  53. }
  54. func NewClient(server *Server, conn net.Conn, isTLS bool) *Client {
  55. now := time.Now()
  56. socket := NewSocket(conn)
  57. client := &Client{
  58. atime: now,
  59. authorized: server.password == nil,
  60. capState: CapNone,
  61. capabilities: make(CapabilitySet),
  62. channels: make(ChannelSet),
  63. ctime: now,
  64. flags: make(map[UserMode]bool),
  65. server: server,
  66. socket: &socket,
  67. account: &NoAccount,
  68. nick: "*", // * is used until actual nick is given
  69. nickCasefolded: "*",
  70. nickMaskString: "*", // * is used until actual nick is given
  71. }
  72. if isTLS {
  73. client.flags[TLS] = true
  74. // error is not useful to us here anyways so we can ignore it
  75. client.certfp, _ = client.socket.CertFP()
  76. }
  77. if server.checkIdent {
  78. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  79. serverPort, _ := strconv.Atoi(serverPortString)
  80. if err != nil {
  81. log.Fatal(err)
  82. }
  83. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  84. clientPort, _ := strconv.Atoi(clientPortString)
  85. if err != nil {
  86. log.Fatal(err)
  87. }
  88. client.Notice("*** Looking up your username")
  89. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  90. if err == nil {
  91. username := resp.Identifier
  92. _, err := CasefoldName(username) // ensure it's a valid username
  93. if err == nil {
  94. client.Notice("*** Found your username")
  95. client.username = username
  96. // we don't need to updateNickMask here since nickMask is not used for anything yet
  97. } else {
  98. client.Notice("*** Got a malformed username, ignoring")
  99. }
  100. } else {
  101. client.Notice("*** Could not find your username")
  102. }
  103. }
  104. client.Touch()
  105. go client.run()
  106. return client
  107. }
  108. //
  109. // command goroutine
  110. //
  111. func (client *Client) run() {
  112. var err error
  113. var isExiting bool
  114. var line string
  115. var msg ircmsg.IrcMessage
  116. // Set the hostname for this client
  117. client.hostname = AddrLookupHostname(client.socket.conn.RemoteAddr())
  118. //TODO(dan): Make this a socketreactor from ircbnc
  119. for {
  120. line, err = client.socket.Read()
  121. if err != nil {
  122. client.Quit("connection closed")
  123. break
  124. }
  125. msg, err = ircmsg.ParseLine(line)
  126. if err != nil {
  127. client.Quit("received malformed line")
  128. break
  129. }
  130. cmd, exists := Commands[msg.Command]
  131. if !exists {
  132. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, "Unknown command")
  133. continue
  134. }
  135. isExiting = cmd.Run(client.server, client, msg)
  136. if isExiting || client.isQuitting {
  137. break
  138. }
  139. }
  140. // ensure client connection gets closed
  141. client.destroy()
  142. }
  143. //
  144. // quit timer goroutine
  145. //
  146. func (client *Client) connectionTimeout() {
  147. client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TIMEOUT_STATED_SECONDS))
  148. client.isQuitting = true
  149. }
  150. //
  151. // idle timer goroutine
  152. //
  153. func (client *Client) connectionIdle() {
  154. client.server.idle <- client
  155. }
  156. //
  157. // server goroutine
  158. //
  159. func (client *Client) Active() {
  160. client.atime = time.Now()
  161. }
  162. func (client *Client) Touch() {
  163. if client.quitTimer != nil {
  164. client.quitTimer.Stop()
  165. }
  166. if client.idleTimer == nil {
  167. client.idleTimer = time.AfterFunc(IDLE_TIMEOUT, client.connectionIdle)
  168. } else {
  169. client.idleTimer.Reset(IDLE_TIMEOUT)
  170. }
  171. }
  172. func (client *Client) Idle() {
  173. client.Send(nil, "", "PING", client.nick)
  174. if client.quitTimer == nil {
  175. client.quitTimer = time.AfterFunc(QUIT_TIMEOUT, client.connectionTimeout)
  176. } else {
  177. client.quitTimer.Reset(QUIT_TIMEOUT)
  178. }
  179. }
  180. func (client *Client) Register() {
  181. if client.registered {
  182. return
  183. }
  184. client.registered = true
  185. client.Touch()
  186. }
  187. func (client *Client) IdleTime() time.Duration {
  188. return time.Since(client.atime)
  189. }
  190. func (client *Client) SignonTime() int64 {
  191. return client.ctime.Unix()
  192. }
  193. func (client *Client) IdleSeconds() uint64 {
  194. return uint64(client.IdleTime().Seconds())
  195. }
  196. func (client *Client) HasNick() bool {
  197. return client.nick != "" && client.nick != "*"
  198. }
  199. func (client *Client) HasUsername() bool {
  200. return client.username != "" && client.username != "*"
  201. }
  202. // <mode>
  203. func (c *Client) ModeString() (str string) {
  204. str = "+"
  205. for flag := range c.flags {
  206. str += flag.String()
  207. }
  208. return
  209. }
  210. func (c *Client) UserHost() string {
  211. return fmt.Sprintf("%s!%s@%s", c.nick, c.username, c.hostname)
  212. }
  213. func (c *Client) Id() string {
  214. return c.UserHost()
  215. }
  216. // Friends refers to clients that share a channel with this client.
  217. func (client *Client) Friends(Capabilities ...Capability) ClientSet {
  218. friends := make(ClientSet)
  219. friends.Add(client)
  220. for channel := range client.channels {
  221. for member := range channel.members {
  222. // make sure they have all the required caps
  223. for _, Cap := range Capabilities {
  224. if !member.capabilities[Cap] {
  225. continue
  226. }
  227. }
  228. friends.Add(member)
  229. }
  230. }
  231. return friends
  232. }
  233. func (client *Client) updateNickMask() {
  234. casefoldedName, err := CasefoldName(client.nick)
  235. if err != nil {
  236. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen.", client.nick))
  237. }
  238. client.nickCasefolded = casefoldedName
  239. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  240. nickMaskCasefolded, err := Casefold(client.nickMaskString)
  241. if err != nil {
  242. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen.", client.nickMaskString))
  243. }
  244. client.nickMaskCasefolded = nickMaskCasefolded
  245. }
  246. func (client *Client) SetNickname(nickname string) {
  247. if client.HasNick() {
  248. Log.error.Printf("%s nickname already set!", client.nickMaskString)
  249. return
  250. }
  251. client.nick = nickname
  252. client.updateNickMask()
  253. client.server.clients.Add(client)
  254. }
  255. func (client *Client) ChangeNickname(nickname string) {
  256. origNickMask := client.nickMaskString
  257. client.server.clients.Remove(client)
  258. client.server.whoWas.Append(client)
  259. client.nick = nickname
  260. client.updateNickMask()
  261. client.server.clients.Add(client)
  262. client.Send(nil, origNickMask, "NICK", nickname)
  263. for friend := range client.Friends() {
  264. friend.Send(nil, origNickMask, "NICK", nickname)
  265. }
  266. }
  267. func (client *Client) Reply(reply string) error {
  268. //TODO(dan): We'll be passing around real message objects instead of raw strings
  269. return client.socket.WriteLine(reply)
  270. }
  271. func (client *Client) Quit(message string) {
  272. client.Send(nil, client.nickMaskString, "QUIT", message)
  273. client.Send(nil, client.nickMaskString, "ERROR", message)
  274. }
  275. func (client *Client) destroy() {
  276. if client.isDestroyed {
  277. return
  278. }
  279. client.isDestroyed = true
  280. client.server.whoWas.Append(client)
  281. friends := client.Friends()
  282. friends.Remove(client)
  283. // clean up channels
  284. for channel := range client.channels {
  285. channel.Quit(client)
  286. }
  287. // clean up server
  288. client.server.clients.Remove(client)
  289. // clean up self
  290. if client.idleTimer != nil {
  291. client.idleTimer.Stop()
  292. }
  293. if client.quitTimer != nil {
  294. client.quitTimer.Stop()
  295. }
  296. client.socket.Close()
  297. for friend := range client.Friends() {
  298. //TODO(dan): store quit message in user, if exists use that instead here
  299. friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
  300. }
  301. }
  302. // SendFromClient sends an IRC line coming from a specific client.
  303. // Adds account-tag to the line as well.
  304. func (client *Client) SendFromClient(from *Client, tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  305. // attach account-tag
  306. if client.capabilities[AccountTag] && from.account != &NoAccount {
  307. if tags == nil {
  308. tags = ircmsg.MakeTags("account", from.account.Name)
  309. } else {
  310. (*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
  311. }
  312. }
  313. return client.Send(tags, prefix, command, params...)
  314. }
  315. // Send sends an IRC line to the client.
  316. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  317. // attach server-time
  318. if client.capabilities[ServerTime] {
  319. if tags == nil {
  320. tags = ircmsg.MakeTags("time", time.Now().Format("2006-01-02T15:04:05.999Z"))
  321. } else {
  322. (*tags)["time"] = ircmsg.MakeTagValue(time.Now().Format("2006-01-02T15:04:05.999Z"))
  323. }
  324. }
  325. // send out the message
  326. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  327. line, err := message.Line()
  328. if err != nil {
  329. // try not to fail quietly - especially useful when running tests, as a note to dig deeper
  330. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  331. line, _ := message.Line()
  332. client.socket.Write(line)
  333. return err
  334. }
  335. client.socket.Write(line)
  336. return nil
  337. }
  338. // Notice sends the client a notice from the server.
  339. func (client *Client) Notice(text string) {
  340. client.Send(nil, client.server.name, "NOTICE", client.nick, text)
  341. }