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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. The client may later send a PROXY
  117. // command from stunnel that sets the hostname to something more accurate.
  118. client.hostname = AddrLookupHostname(client.socket.conn.RemoteAddr())
  119. //TODO(dan): Make this a socketreactor from ircbnc
  120. for {
  121. line, err = client.socket.Read()
  122. if err != nil {
  123. client.Quit("connection closed")
  124. break
  125. }
  126. msg, err = ircmsg.ParseLine(line)
  127. if err != nil {
  128. client.Quit("received malformed line")
  129. break
  130. }
  131. cmd, exists := Commands[msg.Command]
  132. if !exists {
  133. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, "Unknown command")
  134. continue
  135. }
  136. isExiting = cmd.Run(client.server, client, msg)
  137. if isExiting || client.isQuitting {
  138. break
  139. }
  140. }
  141. // ensure client connection gets closed
  142. client.destroy()
  143. }
  144. //
  145. // quit timer goroutine
  146. //
  147. func (client *Client) connectionTimeout() {
  148. client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TIMEOUT_STATED_SECONDS))
  149. client.isQuitting = true
  150. }
  151. //
  152. // idle timer goroutine
  153. //
  154. func (client *Client) connectionIdle() {
  155. client.server.idle <- client
  156. }
  157. //
  158. // server goroutine
  159. //
  160. func (client *Client) Active() {
  161. client.atime = time.Now()
  162. }
  163. func (client *Client) Touch() {
  164. if client.quitTimer != nil {
  165. client.quitTimer.Stop()
  166. }
  167. if client.idleTimer == nil {
  168. client.idleTimer = time.AfterFunc(IDLE_TIMEOUT, client.connectionIdle)
  169. } else {
  170. client.idleTimer.Reset(IDLE_TIMEOUT)
  171. }
  172. }
  173. func (client *Client) Idle() {
  174. client.Send(nil, "", "PING", client.nick)
  175. if client.quitTimer == nil {
  176. client.quitTimer = time.AfterFunc(QUIT_TIMEOUT, client.connectionTimeout)
  177. } else {
  178. client.quitTimer.Reset(QUIT_TIMEOUT)
  179. }
  180. }
  181. func (client *Client) Register() {
  182. if client.registered {
  183. return
  184. }
  185. client.registered = true
  186. client.Touch()
  187. }
  188. func (client *Client) IdleTime() time.Duration {
  189. return time.Since(client.atime)
  190. }
  191. func (client *Client) SignonTime() int64 {
  192. return client.ctime.Unix()
  193. }
  194. func (client *Client) IdleSeconds() uint64 {
  195. return uint64(client.IdleTime().Seconds())
  196. }
  197. func (client *Client) HasNick() bool {
  198. return client.nick != "" && client.nick != "*"
  199. }
  200. func (client *Client) HasUsername() bool {
  201. return client.username != "" && client.username != "*"
  202. }
  203. // <mode>
  204. func (c *Client) ModeString() (str string) {
  205. str = "+"
  206. for flag := range c.flags {
  207. str += flag.String()
  208. }
  209. return
  210. }
  211. func (c *Client) UserHost() string {
  212. return fmt.Sprintf("%s!%s@%s", c.nick, c.username, c.hostname)
  213. }
  214. func (c *Client) Id() string {
  215. return c.UserHost()
  216. }
  217. // Friends refers to clients that share a channel with this client.
  218. func (client *Client) Friends(Capabilities ...Capability) ClientSet {
  219. friends := make(ClientSet)
  220. friends.Add(client)
  221. for channel := range client.channels {
  222. for member := range channel.members {
  223. // make sure they have all the required caps
  224. for _, Cap := range Capabilities {
  225. if !member.capabilities[Cap] {
  226. continue
  227. }
  228. }
  229. friends.Add(member)
  230. }
  231. }
  232. return friends
  233. }
  234. func (client *Client) updateNickMask() {
  235. casefoldedName, err := CasefoldName(client.nick)
  236. if err != nil {
  237. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen.", client.nick))
  238. }
  239. client.nickCasefolded = casefoldedName
  240. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  241. nickMaskCasefolded, err := Casefold(client.nickMaskString)
  242. if err != nil {
  243. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen.", client.nickMaskString))
  244. }
  245. client.nickMaskCasefolded = nickMaskCasefolded
  246. }
  247. func (client *Client) SetNickname(nickname string) {
  248. if client.HasNick() {
  249. Log.error.Printf("%s nickname already set!", client.nickMaskString)
  250. return
  251. }
  252. client.nick = nickname
  253. client.updateNickMask()
  254. client.server.clients.Add(client)
  255. }
  256. func (client *Client) ChangeNickname(nickname string) {
  257. origNickMask := client.nickMaskString
  258. client.server.clients.Remove(client)
  259. client.server.whoWas.Append(client)
  260. client.nick = nickname
  261. client.updateNickMask()
  262. client.server.clients.Add(client)
  263. client.Send(nil, origNickMask, "NICK", nickname)
  264. for friend := range client.Friends() {
  265. friend.Send(nil, origNickMask, "NICK", nickname)
  266. }
  267. }
  268. func (client *Client) Reply(reply string) error {
  269. //TODO(dan): We'll be passing around real message objects instead of raw strings
  270. return client.socket.WriteLine(reply)
  271. }
  272. func (client *Client) Quit(message string) {
  273. client.Send(nil, client.nickMaskString, "QUIT", message)
  274. client.Send(nil, client.nickMaskString, "ERROR", message)
  275. }
  276. func (client *Client) destroy() {
  277. if client.isDestroyed {
  278. return
  279. }
  280. client.isDestroyed = true
  281. client.server.whoWas.Append(client)
  282. friends := client.Friends()
  283. friends.Remove(client)
  284. // clean up channels
  285. for channel := range client.channels {
  286. channel.Quit(client)
  287. }
  288. // clean up server
  289. client.server.clients.Remove(client)
  290. // clean up self
  291. if client.idleTimer != nil {
  292. client.idleTimer.Stop()
  293. }
  294. if client.quitTimer != nil {
  295. client.quitTimer.Stop()
  296. }
  297. client.socket.Close()
  298. for friend := range client.Friends() {
  299. //TODO(dan): store quit message in user, if exists use that instead here
  300. friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
  301. }
  302. }
  303. // SendFromClient sends an IRC line coming from a specific client.
  304. // Adds account-tag to the line as well.
  305. func (client *Client) SendFromClient(from *Client, tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  306. // attach account-tag
  307. if client.capabilities[AccountTag] && from.account != &NoAccount {
  308. if tags == nil {
  309. tags = ircmsg.MakeTags("account", from.account.Name)
  310. } else {
  311. (*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
  312. }
  313. }
  314. return client.Send(tags, prefix, command, params...)
  315. }
  316. // Send sends an IRC line to the client.
  317. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  318. // attach server-time
  319. if client.capabilities[ServerTime] {
  320. if tags == nil {
  321. tags = ircmsg.MakeTags("time", time.Now().Format("2006-01-02T15:04:05.999Z"))
  322. } else {
  323. (*tags)["time"] = ircmsg.MakeTagValue(time.Now().Format("2006-01-02T15:04:05.999Z"))
  324. }
  325. }
  326. // send out the message
  327. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  328. line, err := message.Line()
  329. if err != nil {
  330. // try not to fail quietly - especially useful when running tests, as a note to dig deeper
  331. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  332. line, _ := message.Line()
  333. client.socket.Write(line)
  334. return err
  335. }
  336. client.socket.Write(line)
  337. return nil
  338. }
  339. // Notice sends the client a notice from the server.
  340. func (client *Client) Notice(text string) {
  341. client.Send(nil, client.server.name, "NOTICE", client.nick, text)
  342. }