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

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