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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. "runtime/debug"
  11. "strconv"
  12. "time"
  13. "github.com/DanielOaks/girc-go/ircmsg"
  14. "github.com/DanielOaks/go-ident"
  15. )
  16. const (
  17. IDLE_TIMEOUT = time.Minute + time.Second*30 // how long before a client is considered idle
  18. QUIT_TIMEOUT = time.Minute // how long after idle before a client is kicked
  19. IdentTimeoutSeconds = 5
  20. )
  21. var (
  22. TIMEOUT_STATED_SECONDS = strconv.Itoa(int((IDLE_TIMEOUT + QUIT_TIMEOUT).Seconds()))
  23. )
  24. // Client is an IRC client.
  25. type Client struct {
  26. account *ClientAccount
  27. atime time.Time
  28. authorized bool
  29. awayMessage string
  30. capabilities CapabilitySet
  31. capState CapState
  32. capVersion CapVersion
  33. certfp string
  34. channels ChannelSet
  35. class *OperClass
  36. ctime time.Time
  37. flags map[UserMode]bool
  38. isDestroyed bool
  39. isQuitting bool
  40. hasQuit bool
  41. hops int
  42. hostname string
  43. rawHostname string
  44. vhost string
  45. idleTimer *time.Timer
  46. monitoring map[string]bool
  47. nick string
  48. nickCasefolded string
  49. nickMaskString string // cache for nickmask string since it's used with lots of replies
  50. nickMaskCasefolded string
  51. operName string
  52. quitTimer *time.Timer
  53. realname string
  54. registered bool
  55. saslInProgress bool
  56. saslMechanism string
  57. saslValue string
  58. server *Server
  59. socket *Socket
  60. username string
  61. whoisLine string
  62. }
  63. // NewClient returns a client with all the appropriate info setup.
  64. func NewClient(server *Server, conn net.Conn, isTLS bool) *Client {
  65. now := time.Now()
  66. socket := NewSocket(conn)
  67. client := &Client{
  68. atime: now,
  69. authorized: server.password == nil,
  70. capabilities: make(CapabilitySet),
  71. capState: CapNone,
  72. capVersion: Cap301,
  73. channels: make(ChannelSet),
  74. ctime: now,
  75. flags: make(map[UserMode]bool),
  76. monitoring: make(map[string]bool),
  77. server: server,
  78. socket: &socket,
  79. account: &NoAccount,
  80. nick: "*", // * is used until actual nick is given
  81. nickCasefolded: "*",
  82. nickMaskString: "*", // * is used until actual nick is given
  83. }
  84. if isTLS {
  85. client.flags[TLS] = true
  86. // error is not useful to us here anyways so we can ignore it
  87. client.certfp, _ = client.socket.CertFP()
  88. }
  89. if server.checkIdent {
  90. _, serverPortString, err := net.SplitHostPort(conn.LocalAddr().String())
  91. serverPort, _ := strconv.Atoi(serverPortString)
  92. if err != nil {
  93. log.Fatal(err)
  94. }
  95. clientHost, clientPortString, err := net.SplitHostPort(conn.RemoteAddr().String())
  96. clientPort, _ := strconv.Atoi(clientPortString)
  97. if err != nil {
  98. log.Fatal(err)
  99. }
  100. client.Notice("*** Looking up your username")
  101. resp, err := ident.Query(clientHost, serverPort, clientPort, IdentTimeoutSeconds)
  102. if err == nil {
  103. username := resp.Identifier
  104. _, err := CasefoldName(username) // ensure it's a valid username
  105. if err == nil {
  106. client.Notice("*** Found your username")
  107. client.username = username
  108. // we don't need to updateNickMask here since nickMask is not used for anything yet
  109. } else {
  110. client.Notice("*** Got a malformed username, ignoring")
  111. }
  112. } else {
  113. client.Notice("*** Could not find your username")
  114. }
  115. }
  116. client.Touch()
  117. go client.run()
  118. return client
  119. }
  120. //
  121. // command goroutine
  122. //
  123. func (client *Client) run() {
  124. var err error
  125. var isExiting bool
  126. var line string
  127. var msg ircmsg.IrcMessage
  128. // Set the hostname for this client
  129. client.rawHostname = AddrLookupHostname(client.socket.conn.RemoteAddr())
  130. //TODO(dan): Make this a socketreactor from ircbnc
  131. for {
  132. line, err = client.socket.Read()
  133. if err != nil {
  134. client.Quit("connection closed")
  135. break
  136. }
  137. msg, err = ircmsg.ParseLine(line)
  138. if err != nil {
  139. client.Quit("received malformed line")
  140. break
  141. }
  142. cmd, exists := Commands[msg.Command]
  143. if !exists {
  144. if len(msg.Command) > 0 {
  145. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, "Unknown command")
  146. } else {
  147. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, "lastcmd", "No command given")
  148. }
  149. continue
  150. }
  151. isExiting = cmd.Run(client.server, client, msg)
  152. if isExiting || client.isQuitting {
  153. break
  154. }
  155. }
  156. // ensure client connection gets closed
  157. client.destroy()
  158. }
  159. //
  160. // quit timer goroutine
  161. //
  162. func (client *Client) connectionTimeout() {
  163. client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TIMEOUT_STATED_SECONDS))
  164. client.isQuitting = true
  165. }
  166. //
  167. // idle timer goroutine
  168. //
  169. func (client *Client) connectionIdle() {
  170. client.server.idle <- client
  171. }
  172. //
  173. // server goroutine
  174. //
  175. // Active marks the client as 'active' (i.e. the user should be there).
  176. func (client *Client) Active() {
  177. client.atime = time.Now()
  178. }
  179. // Touch marks the client as alive.
  180. func (client *Client) Touch() {
  181. if client.quitTimer != nil {
  182. client.quitTimer.Stop()
  183. }
  184. if client.idleTimer == nil {
  185. client.idleTimer = time.AfterFunc(IDLE_TIMEOUT, client.connectionIdle)
  186. } else {
  187. client.idleTimer.Reset(IDLE_TIMEOUT)
  188. }
  189. }
  190. // Idle resets the timeout handlers and sends the client a PING.
  191. func (client *Client) Idle() {
  192. client.Send(nil, "", "PING", client.nick)
  193. if client.quitTimer == nil {
  194. client.quitTimer = time.AfterFunc(QUIT_TIMEOUT, client.connectionTimeout)
  195. } else {
  196. client.quitTimer.Reset(QUIT_TIMEOUT)
  197. }
  198. }
  199. // Register sets the client details as appropriate when entering the network.
  200. func (client *Client) Register() {
  201. if client.registered {
  202. return
  203. }
  204. client.registered = true
  205. client.Touch()
  206. client.updateNickMask()
  207. client.alertMonitors()
  208. }
  209. // IdleTime returns how long this client's been idle.
  210. func (client *Client) IdleTime() time.Duration {
  211. return time.Since(client.atime)
  212. }
  213. // SignonTime returns this client's signon time as a unix timestamp.
  214. func (client *Client) SignonTime() int64 {
  215. return client.ctime.Unix()
  216. }
  217. // IdleSeconds returns the number of seconds this client's been idle.
  218. func (client *Client) IdleSeconds() uint64 {
  219. return uint64(client.IdleTime().Seconds())
  220. }
  221. // HasNick returns true if the client's nickname is set (used in registration).
  222. func (client *Client) HasNick() bool {
  223. return client.nick != "" && client.nick != "*"
  224. }
  225. // HasNick returns true if the client's username is set (used in registration).
  226. func (client *Client) HasUsername() bool {
  227. return client.username != "" && client.username != "*"
  228. }
  229. // HasCapabs returns true if client has the given (role) capabilities.
  230. func (client *Client) HasCapabs(capabs ...string) bool {
  231. if client.class == nil {
  232. return false
  233. }
  234. for _, capab := range capabs {
  235. if !client.class.Capabilities[capab] {
  236. return false
  237. }
  238. }
  239. return true
  240. }
  241. // <mode>
  242. func (c *Client) ModeString() (str string) {
  243. str = "+"
  244. for flag := range c.flags {
  245. str += flag.String()
  246. }
  247. return
  248. }
  249. // Friends refers to clients that share a channel with this client.
  250. func (client *Client) Friends(Capabilities ...Capability) ClientSet {
  251. friends := make(ClientSet)
  252. // make sure that I have the right caps
  253. hasCaps := true
  254. for _, Cap := range Capabilities {
  255. if !client.capabilities[Cap] {
  256. hasCaps = false
  257. break
  258. }
  259. }
  260. if hasCaps {
  261. friends.Add(client)
  262. }
  263. for channel := range client.channels {
  264. for member := range channel.members {
  265. // make sure they have all the required caps
  266. for _, Cap := range Capabilities {
  267. if !member.capabilities[Cap] {
  268. continue
  269. }
  270. }
  271. friends.Add(member)
  272. }
  273. }
  274. return friends
  275. }
  276. // updateNick updates the casefolded nickname.
  277. func (client *Client) updateNick() {
  278. casefoldedName, err := CasefoldName(client.nick)
  279. if err != nil {
  280. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
  281. debug.PrintStack()
  282. }
  283. client.nickCasefolded = casefoldedName
  284. }
  285. // updateNickMask updates the casefolded nickname and nickmask.
  286. func (client *Client) updateNickMask() {
  287. client.updateNick()
  288. if len(client.vhost) > 0 {
  289. client.hostname = client.vhost
  290. } else {
  291. client.hostname = client.rawHostname
  292. }
  293. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  294. nickMaskCasefolded, err := Casefold(client.nickMaskString)
  295. if err != nil {
  296. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
  297. debug.PrintStack()
  298. }
  299. client.nickMaskCasefolded = nickMaskCasefolded
  300. }
  301. // SetNickname sets the very first nickname for the client.
  302. func (client *Client) SetNickname(nickname string) {
  303. if client.HasNick() {
  304. Log.error.Printf("%s nickname already set!", client.nickMaskString)
  305. return
  306. }
  307. client.nick = nickname
  308. client.updateNick()
  309. client.server.clients.Add(client)
  310. }
  311. // ChangeNickname changes the existing nickname of the client.
  312. func (client *Client) ChangeNickname(nickname string) {
  313. origNickMask := client.nickMaskString
  314. client.server.clients.Remove(client)
  315. client.server.whoWas.Append(client)
  316. client.nick = nickname
  317. client.updateNickMask()
  318. client.server.clients.Add(client)
  319. for friend := range client.Friends() {
  320. friend.Send(nil, origNickMask, "NICK", nickname)
  321. }
  322. }
  323. func (client *Client) Quit(message string) {
  324. client.Send(nil, client.nickMaskString, "QUIT", message)
  325. client.Send(nil, client.nickMaskString, "ERROR", message)
  326. }
  327. // destroy gets rid of a client, removes them from server lists etc.
  328. func (client *Client) destroy() {
  329. if client.isDestroyed {
  330. return
  331. }
  332. client.isDestroyed = true
  333. client.server.whoWas.Append(client)
  334. friends := client.Friends()
  335. friends.Remove(client)
  336. // remove from connection limits
  337. ipaddr := net.ParseIP(IPString(client.socket.conn.RemoteAddr()))
  338. // this check shouldn't be required but eh
  339. if ipaddr != nil {
  340. client.server.connectionLimitsMutex.Lock()
  341. client.server.connectionLimits.RemoveClient(ipaddr)
  342. client.server.connectionLimitsMutex.Unlock()
  343. }
  344. // remove from opers list
  345. _, exists := client.server.currentOpers[client]
  346. if exists {
  347. delete(client.server.currentOpers, client)
  348. }
  349. // alert monitors
  350. for _, mClient := range client.server.monitoring[client.nickCasefolded] {
  351. mClient.Send(nil, client.server.name, RPL_MONOFFLINE, mClient.nick, client.nick)
  352. }
  353. // remove my monitors
  354. client.clearMonitorList()
  355. // clean up channels
  356. for channel := range client.channels {
  357. channel.Quit(client)
  358. }
  359. // clean up server
  360. client.server.clients.Remove(client)
  361. // clean up self
  362. if client.idleTimer != nil {
  363. client.idleTimer.Stop()
  364. }
  365. if client.quitTimer != nil {
  366. client.quitTimer.Stop()
  367. }
  368. client.socket.Close()
  369. for friend := range client.Friends() {
  370. //TODO(dan): store quit message in user, if exists use that instead here
  371. friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
  372. }
  373. }
  374. // SendFromClient sends an IRC line coming from a specific client.
  375. // Adds account-tag to the line as well.
  376. func (client *Client) SendFromClient(from *Client, tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  377. // attach account-tag
  378. if client.capabilities[AccountTag] && from.account != &NoAccount {
  379. if tags == nil {
  380. tags = ircmsg.MakeTags("account", from.account.Name)
  381. } else {
  382. (*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
  383. }
  384. }
  385. return client.Send(tags, prefix, command, params...)
  386. }
  387. // Send sends an IRC line to the client.
  388. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  389. // attach server-time
  390. if client.capabilities[ServerTime] {
  391. if tags == nil {
  392. tags = ircmsg.MakeTags("time", time.Now().Format("2006-01-02T15:04:05.999Z"))
  393. } else {
  394. (*tags)["time"] = ircmsg.MakeTagValue(time.Now().Format("2006-01-02T15:04:05.999Z"))
  395. }
  396. }
  397. // send out the message
  398. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  399. line, err := message.Line()
  400. if err != nil {
  401. // try not to fail quietly - especially useful when running tests, as a note to dig deeper
  402. // log.Println("Error assembling message:")
  403. // spew.Dump(message)
  404. // debug.PrintStack()
  405. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  406. line, _ := message.Line()
  407. client.socket.Write(line)
  408. return err
  409. }
  410. client.socket.Write(line)
  411. return nil
  412. }
  413. // Notice sends the client a notice from the server.
  414. func (client *Client) Notice(text string) {
  415. client.Send(nil, client.server.name, "NOTICE", client.nick, text)
  416. }