girc-atomic/client.go

677 lines
19 KiB
Go
Raw Normal View History

2017-02-06 07:45:31 +00:00
// Copyright (c) Liam Stanley <me@liamstanley.io>. All rights reserved. Use
// of this source code is governed by the MIT license that can be found in
// the LICENSE file.
2016-11-13 08:30:43 +00:00
package girc
import (
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
2016-12-10 09:14:03 +00:00
"strings"
"sync"
2016-11-13 08:30:43 +00:00
"time"
"golang.org/x/net/context"
2016-11-13 08:30:43 +00:00
)
// Client contains all of the information necessary to run a single IRC
// client.
2016-11-13 08:30:43 +00:00
type Client struct {
// Config represents the configuration
Config Config
// Events is a buffer of events waiting to be processed.
Events chan *Event
2016-11-14 11:59:08 +00:00
2016-11-19 01:11:13 +00:00
// state represents the throw-away state for the irc session.
2016-11-14 11:59:08 +00:00
state *state
// initTime represents the creation time of the client.
initTime time.Time
2016-11-19 01:11:13 +00:00
2017-02-12 03:51:05 +00:00
// Handlers is a handler which manages internal and external handlers.
Handlers *Caller
// CTCP is a handler which manages internal and external CTCP handlers.
2017-02-13 12:52:29 +00:00
CTCP *CTCP
Commands *Commands
2016-11-19 01:11:13 +00:00
// conn is a net.Conn reference to the IRC server.
conn *ircConn
// tries represents the internal reconnect count to the IRC server.
tries int
// reconnecting is true if the client is reconnecting, used so multiple
// threads aren't trying to reconnect at the same time.
reconnecting bool
// cmux is the mux used for connections/disconnections from the server,
// so multiple threads aren't trying to connect at the same time, and
// vice versa.
cmux sync.Mutex
// debug is used if a writer is supplied for Client.Config.Debugger.
debug *log.Logger
// closeRead is the function which sends a close to the readLoop function
// context.
closeRead context.CancelFunc
// closeExec is the function which sends a close to the execLoop function
// context.
closeExec context.CancelFunc
// closeLoop is the function which sends a close to the Loop function
// context.
closeLoop context.CancelFunc
2016-11-13 08:30:43 +00:00
}
// Config contains configuration options for an IRC client
type Config struct {
// Server is a host/ip of the server you want to connect to.
Server string
// Port is the port that will be used during server connection.
Port int
// Password is the server password used to authenticate.
Password string
// Nick is an rfc-valid nickname used during connect.
Nick string
// User is the username/ident to use on connect. Ignored if identd server
// is used.
User string
// Name is the "realname" that's used during connect.
Name string
// Proxy is a proxy based address, used during the dial process when
// connecting to the server. Currently, x/net/proxy only supports socks5,
// however you can add your own proxy functionality using:
// proxy.RegisterDialerType
//
// Examples of how Proxy may be used:
// socks5://localhost:8080
// socks5://1.2.3.4:8888
// customProxy://example.com:8000
//
Proxy string
// Bind is used to bind to a specific host or port during the dial
// process when connecting to the server. This can be a hostname, however
// it must resolve to an IPv4/IPv6 address bindable on your system.
// Otherwise, you can simply use a IPv4/IPv6 address directly.
Bind string
// If we should connect via SSL. See TLSConfig to set your own TLS
// configuration.
SSL bool
// TLSConfig is an optional user-supplied tls configuration, used during
// socket creation to the server. SSL must be enabled for this to be used.
TLSConfig *tls.Config
2017-02-07 11:12:30 +00:00
// Retries is the number of times the client will attempt to reconnect
// to the server after the last disconnect.
2017-02-07 11:12:30 +00:00
Retries int
// AllowFlood allows the client to bypass the rate limit of outbound
// messages.
AllowFlood bool
// Debugger is an optional, user supplied location to log the raw lines
// sent from the server, or other useful debug logs. Defaults to
// ioutil.Discard. For quick debugging, this could be set to os.Stdout.
Debugger io.Writer
// RecoverFunc is called when a handler throws a panic. If RecoverFunc is
2017-02-13 09:42:45 +00:00
// set, the panic will be considered recovered, otherwise the client will
// panic. Set this to DefaultRecoverHandler if you don't want the client
// to panic, however you don't want to handle the panic yourself.
2017-02-13 06:27:57 +00:00
// DefaultRecoverHandler will log the panic to Debugger or os.Stdout if
// Debugger is unset.
RecoverFunc func(c *Client, e *HandlerError)
2017-01-06 14:00:29 +00:00
// SupportedCaps are the IRCv3 capabilities you would like the client to
// support. Only use this if DisableTracking and DisableCapTracking are
// not enabled, otherwise you will need to handle CAP negotiation yourself.
2017-01-19 11:58:08 +00:00
// The keys value gets passed to the server if supported.
SupportedCaps map[string][]string
// Version is the application version information that will be used in
// response to a CTCP VERSION, if default CTCP replies have not been
// overwritten or a VERSION handler was already supplied.
Version string
// ReconnectDelay is the a duration of time to delay before attempting a
2017-02-13 09:43:30 +00:00
// reconnection. Defaults to 10s (minimum of 5s). This is ignored if
// Reconnect() is called directly.
ReconnectDelay time.Duration
2017-02-08 08:08:13 +00:00
// HandleError if supplied, is called when one is disconnected from the
// server, with a given error.
HandleError func(error)
// disableTracking disables all channel and user-level tracking. Useful
// for highly embedded scripts with single purposes.
disableTracking bool
// disableCapTracking disables all network/server capability tracking.
// This includes determining what feature the IRC server supports, what
2017-01-06 14:00:29 +00:00
// the "NETWORK=" variables are, and other useful stuff. DisableTracking
// cannot be enabled if you want to also tracking capabilities.
disableCapTracking bool
// disableNickCollision disables the clients auto-response to nickname
// collisions. For example, if "test" is already in use, or is blocked by
// the network/a service, the client will try and use "test_", then it
// will attempt "test__", "test___", and so on.
disableNickCollision bool
2016-11-13 08:30:43 +00:00
}
// ErrNotConnected is returned if a method is used when the client isn't
// connected.
2016-12-07 00:42:00 +00:00
var ErrNotConnected = errors.New("client is not connected to server")
// ErrAlreadyConnecting implies that a connection attempt is already happening.
var ErrAlreadyConnecting = errors.New("a connection attempt is already occurring")
2017-02-13 08:11:50 +00:00
// ErrDisconnected is called when Config.Retries is less than 1, and we
// non-intentionally disconnected from the server.
2017-02-08 08:08:13 +00:00
var ErrDisconnected = errors.New("unexpectedly disconnected")
// ErrInvalidTarget should be returned if the target which you are
// attempting to send an event to is invalid or doesn't match RFC spec.
type ErrInvalidTarget struct {
Target string
}
func (e *ErrInvalidTarget) Error() string { return "invalid target: " + e.Target }
// New creates a new IRC client with the specified server, name and config.
2016-11-13 08:30:43 +00:00
func New(config Config) *Client {
c := &Client{
Config: config,
Events: make(chan *Event, 100), // buffer 100 events max.
CTCP: newCTCP(),
initTime: time.Now(),
2016-11-13 08:30:43 +00:00
}
2017-02-13 12:52:29 +00:00
c.Commands = &Commands{c: c}
if c.Config.Debugger == nil {
2017-02-13 06:27:57 +00:00
c.debug = log.New(ioutil.Discard, "", 0)
} else {
c.debug = log.New(c.Config.Debugger, "debug:", log.Ltime|log.Lshortfile)
c.debug.Print("initializing debugging")
}
// Setup the caller.
2017-02-12 03:51:05 +00:00
c.Handlers = newCaller(c.debug)
2016-12-09 10:37:01 +00:00
// Give ourselves a new state.
c.state = newState()
2016-12-09 10:37:01 +00:00
// Register builtin handlers.
2017-02-12 04:54:42 +00:00
c.registerBuiltins()
2016-11-13 08:30:43 +00:00
// Register default CTCP responses.
c.CTCP.addDefaultHandlers()
return c
2016-11-13 08:30:43 +00:00
}
2017-02-12 19:31:57 +00:00
// String returns a brief description of the current client state.
func (c *Client) String() string {
var connected bool
if c.conn != nil {
connected = c.conn.connected
}
return fmt.Sprintf(
2017-02-12 19:39:20 +00:00
"<Client init:%q handlers:%d connected:%t reconnecting:%t tries:%d>",
2017-02-12 19:31:57 +00:00
c.initTime.String(), c.Handlers.Len(), connected, c.reconnecting, c.tries,
)
}
2016-11-13 08:30:43 +00:00
// Connect attempts to connect to the given IRC server
func (c *Client) Connect() error {
// Clean up any old running stuff.
c.cleanup(false)
// We want to be the only one handling connects/disconnects right now.
c.cmux.Lock()
defer c.cmux.Unlock()
// Reset the state.
2016-11-14 11:59:08 +00:00
c.state = newState()
2016-11-13 08:30:43 +00:00
2017-02-12 07:06:09 +00:00
// Validate info, and actually make the connection.
c.debug.Printf("connecting to %s...", c.Server())
2017-02-12 07:06:09 +00:00
conn, err := newConn(c.Config, c.Server())
if err != nil {
return err
2016-11-13 08:30:43 +00:00
}
c.conn = conn
// Send a virtual event allowing hooks for successful socket connection.
c.Events <- &Event{Command: INITIALIZED, Trailing: c.Server()}
2017-02-13 10:38:18 +00:00
var events []*Event
// Passwords first.
if c.Config.Password != "" {
events = append(events, &Event{Command: PASS, Params: []string{c.Config.Password}})
}
// Then nickname.
events = append(events, &Event{Command: NICK, Params: []string{c.Config.Nick}})
// Then username and realname.
if c.Config.Name == "" {
c.Config.Name = c.Config.User
}
events = append(events, &Event{Command: USER, Params: []string{c.Config.User, "+iw", "*"}, Trailing: c.Config.Name})
for i := 0; i < len(events); i++ {
if err := c.write(events[i]); err != nil {
2016-11-13 08:30:43 +00:00
return err
}
}
// List the IRCv3 capabilities, specifically with the max protocol we
// support.
if err := c.listCAP(); err != nil {
return err
}
// Consider the connection a success at this point.
c.tries = 0
c.reconnecting = false
2016-11-13 08:30:43 +00:00
// Start read loop to process messages from the server.
var rctx, ectx context.Context
rctx, c.closeRead = context.WithCancel(context.Background())
ectx, c.closeRead = context.WithCancel(context.Background())
go c.readLoop(rctx)
go c.execLoop(ectx)
2016-11-13 08:30:43 +00:00
return nil
}
2017-02-13 08:11:50 +00:00
// reconnect is the internal wrapper for reconnecting to the IRC server (if
// requested.)
func (c *Client) reconnect(remoteInvoked bool) (err error) {
if c.reconnecting {
return ErrDisconnected
}
c.reconnecting = true
defer func() {
c.reconnecting = false
}()
c.cleanup(false)
2016-11-19 16:13:49 +00:00
2017-02-13 09:43:30 +00:00
if c.Config.ReconnectDelay < (5 * time.Second) {
c.Config.ReconnectDelay = 5 * time.Second
}
2016-11-13 09:16:01 +00:00
if c.Config.Retries < 1 && !remoteInvoked {
2017-02-08 08:08:13 +00:00
return ErrDisconnected
}
if !remoteInvoked {
// Delay so we're not slaughtering the server with a bunch of
// connections.
c.debug.Printf("reconnecting to %s in %s", c.Server(), c.Config.ReconnectDelay)
time.Sleep(c.Config.ReconnectDelay)
}
2016-11-13 08:30:43 +00:00
for err = c.Connect(); err != nil && c.tries < c.Config.Retries; c.tries++ {
c.debug.Printf("reconnecting to %s in %s (%d tries)", c.Server(), c.Config.ReconnectDelay, c.tries)
time.Sleep(c.Config.ReconnectDelay)
}
2016-11-13 08:30:43 +00:00
if err != nil {
// Too many errors at this point.
c.cleanup(false)
2016-11-13 08:30:43 +00:00
}
return err
}
2017-02-13 08:11:50 +00:00
// Reconnect checks to make sure we want to, and then attempts to reconnect
// to the server. This will ignore the reconnect delay.
func (c *Client) Reconnect() error {
return c.reconnect(true)
2016-11-13 08:30:43 +00:00
}
// cleanup is used to close out all threads used by the client, like read and
// write loops.
func (c *Client) cleanup(all bool) {
c.cmux.Lock()
// Close any connections they have open.
if c.conn != nil {
c.conn.Close()
}
if c.closeRead != nil {
c.closeRead()
}
if c.closeExec != nil {
c.closeExec()
}
if all {
if c.closeLoop != nil {
c.closeLoop()
}
}
c.cmux.Unlock()
}
// quit is the underlying wrapper to quit from the network and cleanup.
func (c *Client) quit(sendMessage bool) {
if sendMessage {
c.Send(&Event{Command: QUIT, Trailing: "disconnecting..."})
}
c.Events <- &Event{Command: DISCONNECTED, Trailing: c.Server()}
c.cleanup(false)
}
// Quit disconnects from the server.
func (c *Client) Quit() {
c.quit(true)
}
2017-02-13 08:11:50 +00:00
// QuitWithMessage disconnects from the server with a given message.
func (c *Client) QuitWithMessage(message string) {
c.Send(&Event{Command: QUIT, Trailing: message})
c.quit(false)
}
// Stop exits the clients main loop and any other goroutines created by
// the client itself. This does not include handlers, as they will run for
// any incoming events prior to when Stop() or Quit() was called, until the
// event queue is empty and execution has completed for those handlers. This
// means that you are responsible to ensure that your handlers due not
// execute forever. Use Client.Quit() first if you want to disconnect the
// client from the server/connection gracefully.
func (c *Client) Stop() {
c.quit(false)
c.Events <- &Event{Command: STOPPED, Trailing: c.Server()}
}
2016-11-19 15:55:36 +00:00
// readLoop sets a timeout of 300 seconds, and then attempts to read from the
// IRC server. If there is an error, it calls Reconnect.
func (c *Client) readLoop(ctx context.Context) {
var event *Event
var err error
2016-11-13 08:30:43 +00:00
for {
select {
case <-ctx.Done():
return
default:
c.conn.setTimeout(300 * time.Second)
event, err = c.conn.Decode()
if err != nil {
2017-02-08 08:08:13 +00:00
// Attempt a reconnect (if applicable). If it fails, send
// the error to c.Config.HandleError to be dealt with, if
// the handler exists.
err = c.reconnect(false)
if err != nil && c.Config.HandleError != nil {
c.Config.HandleError(err)
}
return
}
if event == nil {
continue
}
c.Events <- event
2016-11-13 08:30:43 +00:00
}
}
}
func (c *Client) execLoop(ctx context.Context) {
2016-11-13 08:30:43 +00:00
for {
select {
2016-11-13 10:27:53 +00:00
case event := <-c.Events:
2017-02-12 03:51:05 +00:00
c.RunHandlers(event)
case <-ctx.Done():
return
2016-11-13 08:30:43 +00:00
}
}
}
// Loop reads from the events channel and sends the events to be handled for
// every message it receives.
func (c *Client) Loop() {
var ctx context.Context
ctx, c.closeLoop = context.WithCancel(context.Background())
<-ctx.Done()
}
// DisableTracking disables all channel and user-level tracking, and clears
// all internal handlers. Useful for highly embedded scripts with single
// purposes. This cannot be un-done.
func (c *Client) DisableTracking() {
c.debug.Print("disabling tracking")
c.Config.disableTracking = true
c.Handlers.clearInternal()
c.state.mu.Lock()
c.state.channels = nil
c.state.mu.Unlock()
c.registerBuiltins()
}
// DisableCapTracking disables all network/server capability tracking, and
// clears all internal handlers. This includes determining what feature the
// IRC server supports, what the "NETWORK=" variables are, and other useful
// stuff. DisableTracking() cannot be called if you want to also track
// capabilities.
func (c *Client) DisableCapTracking() {
// No need to mess with internal handlers. That should already be
// handled by the clear in Client.DisableTracking().
if c.Config.disableCapTracking {
return
}
c.debug.Print("disabling CAP tracking")
c.Config.disableCapTracking = true
c.Handlers.clearInternal()
c.registerBuiltins()
}
// DisableNickCollision disables the clients auto-response to nickname
// collisions. For example, if "test" is already in use, or is blocked by the
// network/a service, the client will try and use "test_", then it will
// attempt "test__", "test___", and so on.
func (c *Client) DisableNickCollision() {
c.debug.Print("disabling nick collision prevention")
c.Config.disableNickCollision = true
c.Handlers.clearInternal()
c.state.mu.Lock()
c.state.channels = nil
c.state.mu.Unlock()
c.registerBuiltins()
}
2016-12-13 15:24:51 +00:00
// Server returns the string representation of host+port pair for net.Conn.
func (c *Client) Server() string {
return fmt.Sprintf("%s:%d", c.Config.Server, c.Config.Port)
2016-12-13 15:24:51 +00:00
}
// Lifetime returns the amount of time that has passed since the client was
// created.
func (c *Client) Lifetime() time.Duration {
return time.Since(c.initTime)
}
2017-02-12 03:51:05 +00:00
// Send sends an event to the server. Use Client.RunHandlers() if you are
// simply looking to trigger handlers with an event.
2016-12-13 15:24:51 +00:00
func (c *Client) Send(event *Event) error {
if !c.Config.AllowFlood {
<-time.After(c.conn.rate(event.Len()))
}
return c.write(event)
}
// write is the lower level function to write an event.
func (c *Client) write(event *Event) error {
c.conn.lastWrite = time.Now()
2016-12-13 15:24:51 +00:00
// log the event
if !event.Sensitive {
c.debug.Print("> ", StripRaw(event.String()))
2016-12-13 15:24:51 +00:00
}
return c.conn.Encode(event)
2016-12-13 15:24:51 +00:00
}
// Uptime is the time at which the client successfully connected to the
// server.
func (c *Client) Uptime() (up *time.Time, err error) {
if !c.IsConnected() {
return nil, ErrNotConnected
}
up = c.conn.connTime
2016-12-13 15:24:51 +00:00
return up, nil
}
// ConnSince is the duration that has past since the client successfully
// connected to the server.
func (c *Client) ConnSince() (since *time.Duration, err error) {
if !c.IsConnected() {
return nil, ErrNotConnected
}
timeSince := time.Since(*c.conn.connTime)
2016-12-13 15:24:51 +00:00
return &timeSince, nil
}
// IsConnected returns true if the client is connected to the server.
func (c *Client) IsConnected() (connected bool) {
if c.conn == nil {
return false
}
return c.conn.connected
2016-11-13 08:30:43 +00:00
}
// GetNick returns the current nickname of the active connection. Returns
// empty string if tracking is disabled.
func (c *Client) GetNick() (nick string) {
if c.Config.disableTracking {
panic("GetNick() used when tracking is disabled")
}
2016-12-10 11:43:26 +00:00
c.state.mu.RLock()
2016-11-14 11:59:08 +00:00
if c.state.nick == "" {
nick = c.Config.Nick
} else {
nick = c.state.nick
2016-11-13 08:30:43 +00:00
}
2016-12-10 11:43:26 +00:00
c.state.mu.RUnlock()
2016-11-13 08:30:43 +00:00
return nick
2016-11-13 08:30:43 +00:00
}
// Channels returns the active list of channels that the client is in.
// Panics if tracking is disabled.
func (c *Client) Channels() []string {
if c.Config.disableTracking {
panic("Channels() used when tracking is disabled")
}
channels := make([]string, len(c.state.channels))
2016-12-10 11:43:26 +00:00
c.state.mu.RLock()
var i int
for channel := range c.state.channels {
channels[i] = channel
i++
}
2016-12-10 11:43:26 +00:00
c.state.mu.RUnlock()
2016-11-13 08:30:43 +00:00
return channels
2016-11-13 08:30:43 +00:00
}
// IsInChannel returns true if the client is in channel. Panics if tracking
// is disabled.
2016-12-10 09:14:03 +00:00
func (c *Client) IsInChannel(channel string) bool {
if c.Config.disableTracking {
panic("Channels() used when tracking is disabled")
}
2016-12-10 11:43:26 +00:00
c.state.mu.RLock()
2016-12-10 09:14:03 +00:00
_, inChannel := c.state.channels[strings.ToLower(channel)]
2016-12-10 11:43:26 +00:00
c.state.mu.RUnlock()
2016-12-10 09:14:03 +00:00
return inChannel
}
// GetServerOption retrieves a server capability setting that was retrieved
2017-01-06 13:53:41 +00:00
// during client connection. This is also known as ISUPPORT (or RPL_PROTOCTL).
// Will panic if used when tracking has been disabled. Examples of usage:
//
// nickLen, success := GetServerOption("MAXNICKLEN")
//
2017-02-06 08:53:05 +00:00
func (c *Client) GetServerOption(key string) (result string, ok bool) {
if c.Config.disableTracking {
panic("GetServerOption() used when tracking is disabled")
}
c.state.mu.Lock()
2017-02-06 08:53:05 +00:00
result, ok = c.state.serverOptions[key]
c.state.mu.Unlock()
2017-02-06 08:53:05 +00:00
return result, ok
}
// ServerName returns the server host/name that the server itself identifies
// as. May be empty if the server does not support RPL_MYINFO. Will panic if
// used when tracking has been disabled.
func (c *Client) ServerName() (name string) {
if c.Config.disableTracking {
2017-01-06 13:53:41 +00:00
panic("ServerName() used when tracking is disabled")
}
name, _ = c.GetServerOption("SERVER")
return name
}
// NetworkName returns the network identifier. E.g. "EsperNet", "ByteIRC".
2017-01-06 13:53:41 +00:00
// May be empty if the server does not support RPL_ISUPPORT (or RPL_PROTOCTL).
// Will panic if used when tracking has been disabled.
func (c *Client) NetworkName() (name string) {
if c.Config.disableTracking {
2017-01-06 13:53:41 +00:00
panic("NetworkName() used when tracking is disabled")
}
name, _ = c.GetServerOption("NETWORK")
return name
}
// ServerVersion returns the server software version, if the server has
// supplied this information during connection. May be empty if the server
// does not support RPL_MYINFO. Will panic if used when tracking has been
// disabled.
func (c *Client) ServerVersion() (version string) {
if c.Config.disableTracking {
2017-01-06 13:53:41 +00:00
panic("ServerVersion() used when tracking is disabled")
}
version, _ = c.GetServerOption("VERSION")
return version
}
// ServerMOTD returns the servers message of the day, if the server has sent
2017-01-06 13:53:41 +00:00
// it upon connect. Will panic if used when tracking has been disabled.
func (c *Client) ServerMOTD() (motd string) {
if c.Config.disableTracking {
2017-01-06 13:53:41 +00:00
panic("ServerMOTD() used when tracking is disabled")
}
c.state.mu.Lock()
motd = c.state.motd
c.state.mu.Unlock()
return motd
}