mirror of https://github.com/fluffle/goirc
Merge remote-tracking branch 'fluffle/master'
Conflicts: README.md client.go client/connection.go
This commit is contained in:
commit
d961c92dd1
|
@ -9,6 +9,7 @@ GOFILES=\
|
||||||
connection.go\
|
connection.go\
|
||||||
commands.go\
|
commands.go\
|
||||||
handlers.go\
|
handlers.go\
|
||||||
|
line.go\
|
||||||
nickchan.go
|
nickchan.go
|
||||||
|
|
||||||
include $(GOROOT)/src/Make.pkg
|
include $(GOROOT)/src/Make.pkg
|
||||||
|
|
|
@ -10,6 +10,10 @@ import (
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
second = int64(1e9)
|
||||||
|
)
|
||||||
|
|
||||||
// An IRC connection is represented by this struct. Once connected, any errors
|
// An IRC connection is represented by this struct. Once connected, any errors
|
||||||
// encountered are piped down *Conn.Err; this channel is closed on disconnect.
|
// encountered are piped down *Conn.Err; this channel is closed on disconnect.
|
||||||
type Conn struct {
|
type Conn struct {
|
||||||
|
@ -32,6 +36,9 @@ type Conn struct {
|
||||||
out chan string
|
out chan string
|
||||||
connected bool
|
connected bool
|
||||||
|
|
||||||
|
// Control channels to goroutines
|
||||||
|
cSend, cLoop chan bool
|
||||||
|
|
||||||
// Error channel to transmit any fail back to the user
|
// Error channel to transmit any fail back to the user
|
||||||
Err chan os.Error
|
Err chan os.Error
|
||||||
|
|
||||||
|
@ -40,9 +47,15 @@ type Conn struct {
|
||||||
SSL bool
|
SSL bool
|
||||||
SSLConfig *tls.Config
|
SSLConfig *tls.Config
|
||||||
|
|
||||||
|
// Socket timeout, in seconds. Defaulted to 5m in New().
|
||||||
|
Timeout int64
|
||||||
|
|
||||||
// Set this to true to disable flood protection and false to re-enable
|
// Set this to true to disable flood protection and false to re-enable
|
||||||
Flood bool
|
Flood bool
|
||||||
|
|
||||||
|
// Internal counters for flood protection
|
||||||
|
badness, lastsent int64
|
||||||
|
|
||||||
// Function which returns a *time.Time for use as a timestamp
|
// Function which returns a *time.Time for use as a timestamp
|
||||||
Timestamp func() *time.Time
|
Timestamp func() *time.Time
|
||||||
|
|
||||||
|
@ -51,43 +64,38 @@ type Conn struct {
|
||||||
TSFormat string
|
TSFormat string
|
||||||
}
|
}
|
||||||
|
|
||||||
// We parse an incoming line into this struct. Line.Cmd is used as the trigger
|
|
||||||
// name for incoming event handlers, see *Conn.recv() for details.
|
|
||||||
// Raw =~ ":nick!user@host cmd args[] :text"
|
|
||||||
// Src == "nick!user@host"
|
|
||||||
// Cmd == e.g. PRIVMSG, 332
|
|
||||||
type Line struct {
|
|
||||||
Nick, Ident, Host, Src string
|
|
||||||
Cmd, Raw string
|
|
||||||
Args []string
|
|
||||||
Time *time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
// Creates a new IRC connection object, but doesn't connect to anything so
|
// 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.
|
// that you can add event handlers to it. See AddHandler() for details.
|
||||||
func New(nick, user, name string) *Conn {
|
func New(nick, user, name string) *Conn {
|
||||||
conn := new(Conn)
|
conn := &Conn{
|
||||||
|
in: make(chan *Line, 32),
|
||||||
|
out: make(chan string, 32),
|
||||||
|
Err: make(chan os.Error, 4),
|
||||||
|
cSend: make(chan bool),
|
||||||
|
cLoop: make(chan bool),
|
||||||
|
SSL: false,
|
||||||
|
SSLConfig: nil,
|
||||||
|
Timeout: 300,
|
||||||
|
Flood: false,
|
||||||
|
badness: 0,
|
||||||
|
lastsent: 0,
|
||||||
|
Timestamp: time.LocalTime,
|
||||||
|
TSFormat: "15:04:05",
|
||||||
|
}
|
||||||
conn.initialise()
|
conn.initialise()
|
||||||
conn.SSL = false
|
|
||||||
conn.SSLConfig = nil
|
|
||||||
conn.Me = conn.NewNick(nick, user, name, "")
|
|
||||||
conn.Timestamp = time.LocalTime
|
|
||||||
conn.TSFormat = "15:04:05"
|
|
||||||
conn.setupEvents()
|
conn.setupEvents()
|
||||||
|
conn.Me = conn.NewNick(nick, user, name, "")
|
||||||
return conn
|
return conn
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Per-connection state initialisation.
|
||||||
func (conn *Conn) initialise() {
|
func (conn *Conn) initialise() {
|
||||||
// allocate meh some memoraaaahh
|
|
||||||
conn.nicks = make(map[string]*Nick)
|
conn.nicks = make(map[string]*Nick)
|
||||||
conn.chans = make(map[string]*Channel)
|
conn.chans = make(map[string]*Channel)
|
||||||
conn.in = make(chan *Line, 32)
|
|
||||||
conn.out = make(chan string, 32)
|
|
||||||
conn.Err = make(chan os.Error, 4)
|
|
||||||
conn.io = nil
|
conn.io = nil
|
||||||
conn.sock = nil
|
conn.sock = nil
|
||||||
|
|
||||||
// if this is being called because we are reconnecting, conn.Me
|
// If this is being called because we are reconnecting, conn.Me
|
||||||
// will still have all the old channels referenced -- nuke them!
|
// will still have all the old channels referenced -- nuke them!
|
||||||
if conn.Me != nil {
|
if conn.Me != nil {
|
||||||
conn.Me = conn.NewNick(conn.Me.Nick, conn.Me.Ident, conn.Me.Name, "")
|
conn.Me = conn.NewNick(conn.Me.Nick, conn.Me.Ident, conn.Me.Name, "")
|
||||||
|
@ -110,18 +118,8 @@ func (conn *Conn) Connect(host string, pass ...string) os.Error {
|
||||||
if !hasPort(host) {
|
if !hasPort(host) {
|
||||||
host += ":6697"
|
host += ":6697"
|
||||||
}
|
}
|
||||||
// It's unfortunate that tls.Dial doesn't allow a tls.Config arg,
|
if s, err := tls.Dial("tcp", host, conn.SSLConfig); err == nil {
|
||||||
// so we simply replicate it here with the correct Config.
|
conn.sock = s
|
||||||
// http://codereview.appspot.com/2883041
|
|
||||||
if s, err := net.Dial("tcp", host); err == nil {
|
|
||||||
// Passing nil config => certs are validated.
|
|
||||||
c := tls.Client(s, conn.SSLConfig)
|
|
||||||
if err = c.Handshake(); err == nil {
|
|
||||||
conn.sock = c
|
|
||||||
} else {
|
|
||||||
s.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -140,7 +138,8 @@ func (conn *Conn) Connect(host string, pass ...string) os.Error {
|
||||||
conn.io = bufio.NewReadWriter(
|
conn.io = bufio.NewReadWriter(
|
||||||
bufio.NewReader(conn.sock),
|
bufio.NewReader(conn.sock),
|
||||||
bufio.NewWriter(conn.sock))
|
bufio.NewWriter(conn.sock))
|
||||||
conn.sock.SetTimeout(300000000000) // 5 minutes
|
conn.sock.SetTimeout(conn.Timeout * second)
|
||||||
|
conn.connected = true
|
||||||
go conn.send()
|
go conn.send()
|
||||||
go conn.recv()
|
go conn.recv()
|
||||||
|
|
||||||
|
@ -164,38 +163,15 @@ func hasPort(s string) bool {
|
||||||
return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
|
return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
|
||||||
}
|
}
|
||||||
|
|
||||||
// dispatch input from channel as \r\n terminated line to peer
|
// goroutine to pass data from output channel to write()
|
||||||
// flood controlled using hybrid's algorithm if conn.Flood is true
|
|
||||||
func (conn *Conn) send() {
|
func (conn *Conn) send() {
|
||||||
lastsent := time.Nanoseconds()
|
for {
|
||||||
var badness, linetime, second int64 = 0, 0, 1000000000
|
select {
|
||||||
for line := range conn.out {
|
case line := <-conn.out:
|
||||||
// Hybrid's algorithm allows for 2 seconds per line and an additional
|
conn.write(line)
|
||||||
// 1/120 of a second per character on that line.
|
case <-conn.cSend:
|
||||||
linetime = 2*second + int64(len(line))*second/120
|
// strobe on control channel, bail out
|
||||||
if !conn.Flood && conn.connected {
|
return
|
||||||
// No point in tallying up flood protection stuff until connected
|
|
||||||
if badness += linetime + lastsent - time.Nanoseconds(); badness < 0 {
|
|
||||||
// negative badness times are badness...
|
|
||||||
badness = int64(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lastsent = time.Nanoseconds()
|
|
||||||
|
|
||||||
// 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 badness > 10*second && !conn.Flood {
|
|
||||||
// so sleep for the current line's time value before sending it
|
|
||||||
time.Sleep(linetime)
|
|
||||||
}
|
|
||||||
if _, err := conn.io.WriteString(line + "\r\n"); err != nil {
|
|
||||||
conn.error("irc.send(): %s", err.String())
|
|
||||||
conn.shutdown()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
conn.io.Flush()
|
|
||||||
if conn.Debug {
|
|
||||||
fmt.Println(conn.Timestamp().Format(conn.TSFormat) + " -> " + line)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -204,70 +180,86 @@ func (conn *Conn) send() {
|
||||||
func (conn *Conn) recv() {
|
func (conn *Conn) recv() {
|
||||||
for {
|
for {
|
||||||
s, err := conn.io.ReadString('\n')
|
s, err := conn.io.ReadString('\n')
|
||||||
t := conn.Timestamp()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
conn.error("irc.recv(): %s", err.String())
|
conn.error("irc.recv(): %s", err.String())
|
||||||
conn.shutdown()
|
conn.shutdown()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
s = strings.Trim(s, "\r\n")
|
s = strings.Trim(s, "\r\n")
|
||||||
|
t := conn.Timestamp()
|
||||||
if conn.Debug {
|
if conn.Debug {
|
||||||
fmt.Println(t.Format(conn.TSFormat) + " <- " + s)
|
fmt.Println(t.Format(conn.TSFormat) + " <- " + s)
|
||||||
}
|
}
|
||||||
|
|
||||||
line := &Line{Raw: s, Time: t}
|
line := parseLine(s)
|
||||||
if s[0] == ':' {
|
line.Time = t
|
||||||
// remove a source and parse it
|
|
||||||
if idx := strings.Index(s, " "); idx != -1 {
|
|
||||||
line.Src, s = s[1:idx], s[idx+1:len(s)]
|
|
||||||
} else {
|
|
||||||
// pretty sure we shouldn't get here ...
|
|
||||||
line.Src = s[1:len(s)]
|
|
||||||
conn.in <- line
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// src can be the hostname of the irc server or a nick!user@host
|
|
||||||
line.Host = line.Src
|
|
||||||
nidx, uidx := strings.Index(line.Src, "!"), strings.Index(line.Src, "@")
|
|
||||||
if uidx != -1 && nidx != -1 {
|
|
||||||
line.Nick = line.Src[0:nidx]
|
|
||||||
line.Ident = line.Src[nidx+1 : uidx]
|
|
||||||
line.Host = line.Src[uidx+1 : len(line.Src)]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// now we're here, we've parsed a :nick!user@host or :server off
|
|
||||||
// s should contain "cmd args[] :text"
|
|
||||||
args := strings.Split(s, " :", 2)
|
|
||||||
if len(args) > 1 {
|
|
||||||
args = append(strings.Fields(args[0]), args[1])
|
|
||||||
} else {
|
|
||||||
args = strings.Fields(args[0])
|
|
||||||
}
|
|
||||||
line.Cmd = strings.ToUpper(args[0])
|
|
||||||
if len(args) > 1 {
|
|
||||||
line.Args = args[1:len(args)]
|
|
||||||
}
|
|
||||||
conn.in <- line
|
conn.in <- line
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// goroutine to dispatch events for lines received on input channel
|
||||||
func (conn *Conn) runLoop() {
|
func (conn *Conn) runLoop() {
|
||||||
for line := range conn.in {
|
for {
|
||||||
conn.dispatchEvent(line)
|
select {
|
||||||
|
case line := <-conn.in:
|
||||||
|
conn.dispatchEvent(line)
|
||||||
|
case <-conn.cLoop:
|
||||||
|
// strobe on control channel, bail out
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write a \r\n terminated line of output to the connected server,
|
||||||
|
// using Hybrid's algorithm to rate limit if conn.Flood is false.
|
||||||
|
func (conn *Conn) write(line string) {
|
||||||
|
if !conn.Flood {
|
||||||
|
conn.rateLimit(int64(len(line)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := conn.io.WriteString(line + "\r\n"); err != nil {
|
||||||
|
conn.error("irc.send(): %s", err.String())
|
||||||
|
conn.shutdown()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conn.io.Flush()
|
||||||
|
if conn.Debug {
|
||||||
|
fmt.Println(conn.Timestamp().Format(conn.TSFormat) + " -> " + line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Implement Hybrid's flood control algorithm to rate-limit outgoing lines.
|
||||||
|
func (conn *Conn) rateLimit(chars int64) {
|
||||||
|
// Hybrid's algorithm allows for 2 seconds per line and an additional
|
||||||
|
// 1/120 of a second per character on that line.
|
||||||
|
linetime := 2*second + chars*second/120
|
||||||
|
elapsed := time.Nanoseconds() - conn.lastsent
|
||||||
|
if conn.badness += linetime - elapsed; conn.badness < 0 {
|
||||||
|
// negative badness times are badness...
|
||||||
|
conn.badness = int64(0)
|
||||||
|
}
|
||||||
|
conn.lastsent = time.Nanoseconds()
|
||||||
|
// 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*second && !conn.Flood {
|
||||||
|
// so sleep for the current line's time value before sending it
|
||||||
|
time.Sleep(linetime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (conn *Conn) shutdown() {
|
func (conn *Conn) shutdown() {
|
||||||
close(conn.in)
|
// Guard against double-call of shutdown() if we get an error in send()
|
||||||
close(conn.out)
|
// as calling sock.Close() will cause recv() to recieve EOF in readstring()
|
||||||
close(conn.Err)
|
if conn.connected {
|
||||||
conn.connected = false
|
conn.connected = false
|
||||||
conn.sock.Close()
|
conn.sock.Close()
|
||||||
// reinit datastructures ready for next connection
|
conn.cSend <- true
|
||||||
// do this here rather than after runLoop()'s for due to race
|
conn.cLoop <- true
|
||||||
conn.initialise()
|
conn.dispatchEvent(&Line{Cmd: "DISCONNECTED"})
|
||||||
|
// reinit datastructures ready for next connection
|
||||||
|
// do this here rather than after runLoop()'s for due to race
|
||||||
|
conn.initialise()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dumps a load of information about the current state of the connection to a
|
// Dumps a load of information about the current state of the connection to a
|
||||||
|
|
|
@ -76,7 +76,6 @@ func (conn *Conn) h_PING(line *Line) {
|
||||||
// Handler to trigger a "CONNECTED" event on receipt of numeric 001
|
// Handler to trigger a "CONNECTED" event on receipt of numeric 001
|
||||||
func (conn *Conn) h_001(line *Line) {
|
func (conn *Conn) h_001(line *Line) {
|
||||||
// we're connected!
|
// we're connected!
|
||||||
conn.connected = true
|
|
||||||
conn.dispatchEvent(&Line{Cmd: "CONNECTED"})
|
conn.dispatchEvent(&Line{Cmd: "CONNECTED"})
|
||||||
// and we're being given our hostname (from the server's perspective)
|
// and we're being given our hostname (from the server's perspective)
|
||||||
t := line.Args[len(line.Args)-1]
|
t := line.Args[len(line.Args)-1]
|
||||||
|
@ -103,7 +102,7 @@ func (conn *Conn) h_433(line *Line) {
|
||||||
// if this is happening before we're properly connected (i.e. the nick
|
// if this is happening before we're properly connected (i.e. the nick
|
||||||
// we sent in the initial NICK command is in use) we will not receive
|
// we sent in the initial NICK command is in use) we will not receive
|
||||||
// a NICK message to confirm our change of nick, so ReNick here...
|
// a NICK message to confirm our change of nick, so ReNick here...
|
||||||
if !conn.connected && line.Args[1] == conn.Me.Nick {
|
if line.Args[1] == conn.Me.Nick {
|
||||||
conn.Me.ReNick(line.Args[1] + "_")
|
conn.Me.ReNick(line.Args[1] + "_")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,56 @@
|
||||||
|
package client
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// We parse an incoming line into this struct. Line.Cmd is used as the trigger
|
||||||
|
// name for incoming event handlers, see *Conn.recv() for details.
|
||||||
|
// Raw =~ ":nick!user@host cmd args[] :text"
|
||||||
|
// Src == "nick!user@host"
|
||||||
|
// Cmd == e.g. PRIVMSG, 332
|
||||||
|
type Line struct {
|
||||||
|
Nick, Ident, Host, Src string
|
||||||
|
Cmd, Raw string
|
||||||
|
Args []string
|
||||||
|
Time *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseLine(s string) *Line {
|
||||||
|
line := &Line{Raw: s}
|
||||||
|
if s[0] == ':' {
|
||||||
|
// remove a source and parse it
|
||||||
|
if idx := strings.Index(s, " "); idx != -1 {
|
||||||
|
line.Src, s = s[1:idx], s[idx+1:len(s)]
|
||||||
|
} else {
|
||||||
|
// pretty sure we shouldn't get here ...
|
||||||
|
line.Src = s[1:len(s)]
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
||||||
|
// src can be the hostname of the irc server or a nick!user@host
|
||||||
|
line.Host = line.Src
|
||||||
|
nidx, uidx := strings.Index(line.Src, "!"), strings.Index(line.Src, "@")
|
||||||
|
if uidx != -1 && nidx != -1 {
|
||||||
|
line.Nick = line.Src[0:nidx]
|
||||||
|
line.Ident = line.Src[nidx+1 : uidx]
|
||||||
|
line.Host = line.Src[uidx+1 : len(line.Src)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// now we're here, we've parsed a :nick!user@host or :server off
|
||||||
|
// s should contain "cmd args[] :text"
|
||||||
|
args := strings.Split(s, " :", 2)
|
||||||
|
if len(args) > 1 {
|
||||||
|
args = append(strings.Fields(args[0]), args[1])
|
||||||
|
} else {
|
||||||
|
args = strings.Fields(args[0])
|
||||||
|
}
|
||||||
|
line.Cmd = strings.ToUpper(args[0])
|
||||||
|
if len(args) > 1 {
|
||||||
|
line.Args = args[1:len(args)]
|
||||||
|
}
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue