goirc/client/connection.go

439 lines
11 KiB
Go
Raw Normal View History

package client
import (
"bufio"
2010-08-30 11:16:20 +00:00
"crypto/tls"
2011-11-13 13:34:32 +00:00
"fmt"
"github.com/fluffle/goirc/logging"
"github.com/fluffle/goirc/state"
"io"
"net"
"strings"
"sync"
"time"
)
2011-08-21 12:57:47 +00:00
// An IRC connection is represented by this struct.
type Conn struct {
// For preventing races on (dis)connect.
2013-09-30 12:55:55 +00:00
mu sync.RWMutex
// Contains parameters that people can tweak to change client behaviour.
cfg *Config
// Handlers
2013-09-27 23:15:54 +00:00
intHandlers *hSet
2014-12-20 14:56:58 +00:00
fgHandlers *hSet
bgHandlers *hSet
2011-09-28 19:48:58 +00:00
// State tracker for nicks and channels
st state.Tracker
stRemovers []Remover
// I/O stuff to server
2014-10-12 17:22:31 +00:00
dialer *net.Dialer
2010-08-30 11:16:20 +00:00
sock net.Conn
io *bufio.ReadWriter
in chan *Line
out chan string
connected bool
// Control channel and WaitGroup for goroutines
die chan struct{}
wg sync.WaitGroup
// Internal counters for flood protection
badness time.Duration
lastsent time.Time
}
// Misc knobs to tweak client behaviour go in here
type Config struct {
// Set this to provide the Nick, Ident and Name for the client to use.
Me *state.Nick
// Hostname to connect to and optional connect password.
Server, Pass string
// Are we connecting via SSL? Do we care about certificate validity?
SSL bool
SSLConfig *tls.Config
2010-08-30 11:16:20 +00:00
2014-10-12 17:22:31 +00:00
// Local address to connect to the server.
LocalAddr string
// Replaceable function to customise the 433 handler's new nick
NewNick func(string) string
// Client->server ping frequency, in seconds. Defaults to 3m.
2012-06-06 16:12:07 +00:00
PingFreq time.Duration
// Set this to true to disable flood protection and false to re-enable
2010-08-30 11:16:20 +00:00
Flood bool
// Sent as the reply to a CTCP VERSION message
Version string
// Sent as the QUIT message.
QuitMessage string
// Configurable panic recovery for all handlers.
Recover func(*Conn, *Line)
// Split PRIVMSGs, NOTICEs and CTCPs longer than
// SplitLen characters over multiple lines.
SplitLen int
// Timeout, The amount of time in seconds until a timeout is triggered.
Timeout time.Duration
}
func NewConfig(nick string, args ...string) *Config {
cfg := &Config{
Me: &state.Nick{Nick: nick},
2013-02-17 23:55:39 +00:00
PingFreq: 3 * time.Minute,
NewNick: func(s string) string { return s + "_" },
2013-03-10 13:31:04 +00:00
Recover: (*Conn).LogPanic, // in dispatch.go
SplitLen: 450,
Timeout: 60 * time.Second,
}
cfg.Me.Ident = "goirc"
if len(args) > 0 && args[0] != "" {
cfg.Me.Ident = args[0]
}
cfg.Me.Name = "Powered by GoIRC"
if len(args) > 1 && args[1] != "" {
cfg.Me.Name = args[1]
}
cfg.Version = "Powered by GoIRC"
cfg.QuitMessage = "GoBye!"
return cfg
}
// Creates a new IRC connection object, but doesn't connect to anything so
// that you can add event handlers to it. See AddHandler() for details
func SimpleClient(nick string, args ...string) *Conn {
conn := Client(NewConfig(nick, args...))
return conn
}
func Client(cfg *Config) *Conn {
if cfg == nil {
cfg = NewConfig("__idiot__")
}
if cfg.Me == nil || cfg.Me.Nick == "" || cfg.Me.Ident == "" {
cfg.Me = &state.Nick{Nick: "__idiot__"}
cfg.Me.Ident = "goirc"
cfg.Me.Name = "Powered by GoIRC"
}
2014-10-12 17:22:31 +00:00
dialer := new(net.Dialer)
2014-12-20 18:39:44 +00:00
dialer.Timeout = cfg.Timeout
2014-10-12 17:22:31 +00:00
if cfg.LocalAddr != "" {
if !hasPort(cfg.LocalAddr) {
cfg.LocalAddr += ":0"
}
local, err := net.ResolveTCPAddr("tcp", cfg.LocalAddr)
if err == nil {
dialer.LocalAddr = local
} else {
logging.Error("irc.Client(): Cannot resolve local address %s: %s", cfg.LocalAddr, err)
}
}
conn := &Conn{
2013-09-27 23:15:54 +00:00
cfg: cfg,
2014-10-12 17:22:31 +00:00
dialer: dialer,
2013-09-27 23:15:54 +00:00
in: make(chan *Line, 32),
out: make(chan string, 32),
intHandlers: handlerSet(),
fgHandlers: handlerSet(),
bgHandlers: handlerSet(),
stRemovers: make([]Remover, 0, len(stHandlers)),
lastsent: time.Now(),
}
conn.addIntHandlers()
conn.initialise()
return conn
}
func (conn *Conn) Connected() bool {
2013-09-30 12:55:55 +00:00
conn.mu.RLock()
defer conn.mu.RUnlock()
return conn.connected
}
func (conn *Conn) Config() *Config {
return conn.cfg
}
2013-02-18 01:38:04 +00:00
func (conn *Conn) Me() *state.Nick {
conn.mu.RLock()
defer conn.mu.RUnlock()
if conn.st != nil {
return conn.st.Me()
}
2013-02-18 01:38:04 +00:00
return conn.cfg.Me
}
func (conn *Conn) StateTracker() state.Tracker {
return conn.st
}
func (conn *Conn) EnableStateTracking() {
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.st == nil {
n := conn.cfg.Me
conn.st = state.NewTracker(n.Nick)
conn.cfg.Me = conn.st.Me()
conn.cfg.Me.Ident = n.Ident
conn.cfg.Me.Name = n.Name
conn.addSTHandlers()
}
}
func (conn *Conn) DisableStateTracking() {
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.st != nil {
conn.cfg.Me = conn.st.Me()
conn.delSTHandlers()
conn.st.Wipe()
conn.st = nil
}
}
// Per-connection state initialisation.
func (conn *Conn) initialise() {
conn.io = nil
conn.sock = nil
conn.die = make(chan struct{})
if conn.st != nil {
conn.st.Wipe()
}
}
// Connect the IRC connection object to "host[:port]" which should be either
2010-08-30 11:16:20 +00:00
// a hostname or an IP address, with an optional port. To enable explicit SSL
// on the connection to the IRC server, set Conn.SSL to true before calling
// Connect(). The port will default to 6697 if ssl is enabled, and 6667
// otherwise. You can also provide an optional connect password.
func (conn *Conn) ConnectTo(host string, pass ...string) error {
conn.cfg.Server = host
if len(pass) > 0 {
conn.cfg.Pass = pass[0]
}
return conn.Connect()
}
func (conn *Conn) Connect() error {
conn.mu.Lock()
defer conn.mu.Unlock()
if conn.cfg.Server == "" {
return fmt.Errorf("irc.Connect(): cfg.Server must be non-empty")
}
if conn.connected {
return fmt.Errorf("irc.Connect(): Cannot connect to %s, already connected.", conn.cfg.Server)
}
if conn.cfg.SSL {
if !hasPort(conn.cfg.Server) {
conn.cfg.Server = net.JoinHostPort(conn.cfg.Server, "6697")
}
logging.Info("irc.Connect(): Connecting to %s with SSL.", conn.cfg.Server)
2014-10-12 17:22:31 +00:00
if s, err := tls.DialWithDialer(conn.dialer, "tcp", conn.cfg.Server, conn.cfg.SSLConfig); err == nil {
conn.sock = s
2010-08-30 11:16:20 +00:00
} else {
return err
2010-08-30 11:16:20 +00:00
}
} else {
if !hasPort(conn.cfg.Server) {
conn.cfg.Server = net.JoinHostPort(conn.cfg.Server, "6667")
}
logging.Info("irc.Connect(): Connecting to %s without SSL.", conn.cfg.Server)
2014-12-20 17:36:08 +00:00
if s, err := conn.dialer.Dial("tcp", conn.cfg.Server); err == nil {
conn.sock = s
} else {
return err
}
}
conn.connected = true
conn.postConnect(true)
conn.dispatch(&Line{Cmd: REGISTER, Time: time.Now()})
return nil
}
// Post-connection setup (for ease of testing)
func (conn *Conn) postConnect(start bool) {
conn.io = bufio.NewReadWriter(
bufio.NewReader(conn.sock),
bufio.NewWriter(conn.sock))
if start {
conn.wg.Add(3)
go conn.send()
go conn.recv()
go conn.runLoop()
if conn.cfg.PingFreq > 0 {
conn.wg.Add(1)
go conn.ping()
}
}
}
// copied from http.client for great justice
func hasPort(s string) bool {
return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
}
// goroutine to pass data from output channel to write()
func (conn *Conn) send() {
defer conn.wg.Done()
for {
select {
case line := <-conn.out:
conn.write(line)
case <-conn.die:
// control channel closed, bail out
return
2010-11-02 21:47:05 +00:00
}
}
}
// receive one \r\n terminated line from peer, parse and dispatch it
func (conn *Conn) recv() {
for {
s, err := conn.io.ReadString('\n')
if err != nil {
if err != io.EOF {
logging.Error("irc.recv(): %s", err.Error())
}
// We can't defer this, because shutdown() waits for it.
conn.wg.Done()
conn.shutdown()
return
}
s = strings.Trim(s, "\r\n")
logging.Debug("<- %s", s)
if line := ParseLine(s); line != nil {
2012-02-04 00:51:06 +00:00
line.Time = time.Now()
2011-07-27 20:15:09 +00:00
conn.in <- line
} else {
logging.Warn("irc.recv(): problems parsing line:\n %s", s)
2011-07-27 20:15:09 +00:00
}
}
}
// Repeatedly pings the server every PingFreq seconds (no matter what)
func (conn *Conn) ping() {
defer conn.wg.Done()
tick := time.NewTicker(conn.cfg.PingFreq)
for {
select {
case <-tick.C:
2013-03-08 01:43:33 +00:00
conn.Ping(fmt.Sprintf("%d", time.Now().UnixNano()))
case <-conn.die:
// control channel closed, bail out
tick.Stop()
return
}
}
}
// goroutine to dispatch events for lines received on input channel
func (conn *Conn) runLoop() {
defer conn.wg.Done()
for {
select {
case line := <-conn.in:
conn.dispatch(line)
case <-conn.die:
// control channel closed, bail out
return
}
}
}
// Write a \r\n terminated line of output to the connected server,
// using Hybrid's algorithm to rate limit if conn.cfg.Flood is false.
func (conn *Conn) write(line string) {
if !conn.cfg.Flood {
if t := conn.rateLimit(len(line)); t != 0 {
// sleep for the current line's time value before sending it
logging.Info("irc.rateLimit(): Flood! Sleeping for %.2f secs.",
t.Seconds())
<-time.After(t)
}
}
if _, err := conn.io.WriteString(line + "\r\n"); err != nil {
logging.Error("irc.send(): %s", err.Error())
conn.shutdown()
return
}
if err := conn.io.Flush(); err != nil {
logging.Error("irc.send(): %s", err.Error())
conn.shutdown()
return
}
logging.Debug("-> %s", line)
}
// Implement Hybrid's flood control algorithm to rate-limit outgoing lines.
func (conn *Conn) rateLimit(chars int) time.Duration {
// Hybrid's algorithm allows for 2 seconds per line and an additional
// 1/120 of a second per character on that line.
linetime := 2*time.Second + time.Duration(chars)*time.Second/120
2012-02-04 00:51:06 +00:00
elapsed := time.Now().Sub(conn.lastsent)
if conn.badness += linetime - elapsed; conn.badness < 0 {
// negative badness times are badness...
conn.badness = 0
}
2012-02-04 00:51:06 +00:00
conn.lastsent = time.Now()
// If we've sent more than 10 second's worth of lines according to the
// calculation above, then we're at risk of "Excess Flood".
if conn.badness > 10*time.Second {
return linetime
}
return 0
}
func (conn *Conn) shutdown() {
// Guard against double-call of shutdown() if we get an error in send()
// as calling sock.Close() will cause recv() to receive EOF in readstring()
conn.mu.Lock()
defer conn.mu.Unlock()
if !conn.connected {
return
}
logging.Info("irc.shutdown(): Disconnected from server.")
conn.connected = false
conn.sock.Close()
close(conn.die)
conn.wg.Wait()
// Dispatch after closing connection but before reinit
// so event handlers can still access state information.
conn.dispatch(&Line{Cmd: DISCONNECTED, Time: time.Now()})
// reinit datastructures ready for next connection
conn.initialise()
}
// Dumps a load of information about the current state of the connection to a
// string for debugging state tracking and other such things.
func (conn *Conn) String() string {
str := "GoIRC Connection\n"
str += "----------------\n\n"
if conn.Connected() {
str += "Connected to " + conn.cfg.Server + "\n\n"
} else {
str += "Not currently connected!\n\n"
}
str += conn.Me().String() + "\n"
if conn.st != nil {
str += conn.st.String() + "\n"
}
return str
}