Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

client.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 = 8
  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. client.Send(nil, client.server.name, ERR_UNKNOWNCOMMAND, client.nick, msg.Command, "Unknown command")
  145. continue
  146. }
  147. isExiting = cmd.Run(client.server, client, msg)
  148. if isExiting || client.isQuitting {
  149. break
  150. }
  151. }
  152. // ensure client connection gets closed
  153. client.destroy()
  154. }
  155. //
  156. // quit timer goroutine
  157. //
  158. func (client *Client) connectionTimeout() {
  159. client.Quit(fmt.Sprintf("Ping timeout: %s seconds", TIMEOUT_STATED_SECONDS))
  160. client.isQuitting = true
  161. }
  162. //
  163. // idle timer goroutine
  164. //
  165. func (client *Client) connectionIdle() {
  166. client.server.idle <- client
  167. }
  168. //
  169. // server goroutine
  170. //
  171. // Active marks the client as 'active' (i.e. the user should be there).
  172. func (client *Client) Active() {
  173. client.atime = time.Now()
  174. }
  175. // Touch marks the client as alive.
  176. func (client *Client) Touch() {
  177. if client.quitTimer != nil {
  178. client.quitTimer.Stop()
  179. }
  180. if client.idleTimer == nil {
  181. client.idleTimer = time.AfterFunc(IDLE_TIMEOUT, client.connectionIdle)
  182. } else {
  183. client.idleTimer.Reset(IDLE_TIMEOUT)
  184. }
  185. }
  186. // Idle resets the timeout handlers and sends the client a PING.
  187. func (client *Client) Idle() {
  188. client.Send(nil, "", "PING", client.nick)
  189. if client.quitTimer == nil {
  190. client.quitTimer = time.AfterFunc(QUIT_TIMEOUT, client.connectionTimeout)
  191. } else {
  192. client.quitTimer.Reset(QUIT_TIMEOUT)
  193. }
  194. }
  195. // Register sets the client details as appropriate when entering the network.
  196. func (client *Client) Register() {
  197. if client.registered {
  198. return
  199. }
  200. client.registered = true
  201. client.Touch()
  202. client.updateNickMask()
  203. client.alertMonitors()
  204. }
  205. // IdleTime returns how long this client's been idle.
  206. func (client *Client) IdleTime() time.Duration {
  207. return time.Since(client.atime)
  208. }
  209. // SignonTime returns this client's signon time as a unix timestamp.
  210. func (client *Client) SignonTime() int64 {
  211. return client.ctime.Unix()
  212. }
  213. // IdleSeconds returns the number of seconds this client's been idle.
  214. func (client *Client) IdleSeconds() uint64 {
  215. return uint64(client.IdleTime().Seconds())
  216. }
  217. // HasNick returns true if the client's nickname is set (used in registration).
  218. func (client *Client) HasNick() bool {
  219. return client.nick != "" && client.nick != "*"
  220. }
  221. // HasNick returns true if the client's username is set (used in registration).
  222. func (client *Client) HasUsername() bool {
  223. return client.username != "" && client.username != "*"
  224. }
  225. // HasCapabs returns true if client has the given (role) capabilities.
  226. func (client *Client) HasCapabs(capabs ...string) bool {
  227. if client.class == nil {
  228. return false
  229. }
  230. for _, capab := range capabs {
  231. if !client.class.Capabilities[capab] {
  232. return false
  233. }
  234. }
  235. return true
  236. }
  237. // <mode>
  238. func (c *Client) ModeString() (str string) {
  239. str = "+"
  240. for flag := range c.flags {
  241. str += flag.String()
  242. }
  243. return
  244. }
  245. // Friends refers to clients that share a channel with this client.
  246. func (client *Client) Friends(Capabilities ...Capability) ClientSet {
  247. friends := make(ClientSet)
  248. // make sure that I have the right caps
  249. hasCaps := true
  250. for _, Cap := range Capabilities {
  251. if !client.capabilities[Cap] {
  252. hasCaps = false
  253. break
  254. }
  255. }
  256. if hasCaps {
  257. friends.Add(client)
  258. }
  259. for channel := range client.channels {
  260. for member := range channel.members {
  261. // make sure they have all the required caps
  262. for _, Cap := range Capabilities {
  263. if !member.capabilities[Cap] {
  264. continue
  265. }
  266. }
  267. friends.Add(member)
  268. }
  269. }
  270. return friends
  271. }
  272. // updateNick updates the casefolded nickname.
  273. func (client *Client) updateNick() {
  274. casefoldedName, err := CasefoldName(client.nick)
  275. if err != nil {
  276. log.Println(fmt.Sprintf("ERROR: Nick [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nick))
  277. debug.PrintStack()
  278. }
  279. client.nickCasefolded = casefoldedName
  280. }
  281. // updateNickMask updates the casefolded nickname and nickmask.
  282. func (client *Client) updateNickMask() {
  283. client.updateNick()
  284. if len(client.vhost) > 0 {
  285. client.hostname = client.vhost
  286. } else {
  287. client.hostname = client.rawHostname
  288. }
  289. client.nickMaskString = fmt.Sprintf("%s!%s@%s", client.nick, client.username, client.hostname)
  290. nickMaskCasefolded, err := Casefold(client.nickMaskString)
  291. if err != nil {
  292. log.Println(fmt.Sprintf("ERROR: Nickmask [%s] couldn't be casefolded... this should never happen. Printing stacktrace.", client.nickMaskString))
  293. debug.PrintStack()
  294. }
  295. client.nickMaskCasefolded = nickMaskCasefolded
  296. }
  297. // SetNickname sets the very first nickname for the client.
  298. func (client *Client) SetNickname(nickname string) {
  299. if client.HasNick() {
  300. Log.error.Printf("%s nickname already set!", client.nickMaskString)
  301. return
  302. }
  303. client.nick = nickname
  304. client.updateNick()
  305. client.server.clients.Add(client)
  306. }
  307. // ChangeNickname changes the existing nickname of the client.
  308. func (client *Client) ChangeNickname(nickname string) {
  309. origNickMask := client.nickMaskString
  310. client.server.clients.Remove(client)
  311. client.server.whoWas.Append(client)
  312. client.nick = nickname
  313. client.updateNickMask()
  314. client.server.clients.Add(client)
  315. for friend := range client.Friends() {
  316. friend.Send(nil, origNickMask, "NICK", nickname)
  317. }
  318. }
  319. func (client *Client) Quit(message string) {
  320. client.Send(nil, client.nickMaskString, "QUIT", message)
  321. client.Send(nil, client.nickMaskString, "ERROR", message)
  322. }
  323. // destroy gets rid of a client, removes them from server lists etc.
  324. func (client *Client) destroy() {
  325. if client.isDestroyed {
  326. return
  327. }
  328. client.isDestroyed = true
  329. client.server.whoWas.Append(client)
  330. friends := client.Friends()
  331. friends.Remove(client)
  332. // remove from connection limits
  333. ipaddr := net.ParseIP(IPString(client.socket.conn.RemoteAddr()))
  334. // this check shouldn't be required but eh
  335. if ipaddr != nil {
  336. client.server.connectionLimitsMutex.Lock()
  337. client.server.connectionLimits.RemoveClient(ipaddr)
  338. client.server.connectionLimitsMutex.Unlock()
  339. }
  340. // remove from opers list
  341. _, exists := client.server.currentOpers[client]
  342. if exists {
  343. delete(client.server.currentOpers, client)
  344. }
  345. // alert monitors
  346. for _, mClient := range client.server.monitoring[client.nickCasefolded] {
  347. mClient.Send(nil, client.server.name, RPL_MONOFFLINE, mClient.nick, client.nick)
  348. }
  349. // remove my monitors
  350. client.clearMonitorList()
  351. // clean up channels
  352. for channel := range client.channels {
  353. channel.Quit(client)
  354. }
  355. // clean up server
  356. client.server.clients.Remove(client)
  357. // clean up self
  358. if client.idleTimer != nil {
  359. client.idleTimer.Stop()
  360. }
  361. if client.quitTimer != nil {
  362. client.quitTimer.Stop()
  363. }
  364. client.socket.Close()
  365. for friend := range client.Friends() {
  366. //TODO(dan): store quit message in user, if exists use that instead here
  367. friend.Send(nil, client.nickMaskString, "QUIT", "Exited")
  368. }
  369. }
  370. // SendFromClient sends an IRC line coming from a specific client.
  371. // Adds account-tag to the line as well.
  372. func (client *Client) SendFromClient(from *Client, tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  373. // attach account-tag
  374. if client.capabilities[AccountTag] && from.account != &NoAccount {
  375. if tags == nil {
  376. tags = ircmsg.MakeTags("account", from.account.Name)
  377. } else {
  378. (*tags)["account"] = ircmsg.MakeTagValue(from.account.Name)
  379. }
  380. }
  381. return client.Send(tags, prefix, command, params...)
  382. }
  383. // Send sends an IRC line to the client.
  384. func (client *Client) Send(tags *map[string]ircmsg.TagValue, prefix string, command string, params ...string) error {
  385. // attach server-time
  386. if client.capabilities[ServerTime] {
  387. if tags == nil {
  388. tags = ircmsg.MakeTags("time", time.Now().Format("2006-01-02T15:04:05.999Z"))
  389. } else {
  390. (*tags)["time"] = ircmsg.MakeTagValue(time.Now().Format("2006-01-02T15:04:05.999Z"))
  391. }
  392. }
  393. // send out the message
  394. message := ircmsg.MakeMessage(tags, prefix, command, params...)
  395. line, err := message.Line()
  396. if err != nil {
  397. // try not to fail quietly - especially useful when running tests, as a note to dig deeper
  398. // log.Println("Error assembling message:")
  399. // spew.Dump(message)
  400. message = ircmsg.MakeMessage(nil, client.server.name, ERR_UNKNOWNERROR, "*", "Error assembling message for sending")
  401. line, _ := message.Line()
  402. client.socket.Write(line)
  403. return err
  404. }
  405. client.socket.Write(line)
  406. return nil
  407. }
  408. // Notice sends the client a notice from the server.
  409. func (client *Client) Notice(text string) {
  410. client.Send(nil, client.server.name, "NOTICE", client.nick, text)
  411. }