go-ircevent/irc.go

474 lines
12 KiB
Go
Raw Normal View History

2012-11-05 22:46:47 +00:00
// Copyright 2009 Thomas Jager <mail@jager.no> All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
2014-02-14 11:06:09 +00:00
/*
2014-02-16 13:20:13 +00:00
This package provides an event based IRC client library. It allows to
register callbacks for the events you need to handle. Its features
include handling standard CTCP, reconnecting on errors and detecting
2014-02-14 11:06:09 +00:00
stones servers.
2014-02-14 14:03:52 +00:00
Details of the IRC protocol can be found in the following RFCs:
https://tools.ietf.org/html/rfc1459
https://tools.ietf.org/html/rfc2810
https://tools.ietf.org/html/rfc2811
https://tools.ietf.org/html/rfc2812
https://tools.ietf.org/html/rfc2813
2014-02-14 15:13:17 +00:00
The details of the client-to-client protocol (CTCP) can be found here: http://www.irchelp.org/irchelp/rfc/ctcpspec.html
2014-02-14 11:06:09 +00:00
*/
2012-11-05 22:46:47 +00:00
package irc
import (
"bufio"
2015-07-31 05:34:19 +00:00
"bytes"
"crypto/tls"
"errors"
2012-11-05 22:46:47 +00:00
"fmt"
"log"
"net"
"os"
2014-02-16 10:41:38 +00:00
"strconv"
2012-11-05 22:46:47 +00:00
"strings"
"time"
)
const (
VERSION = "go-ircevent v2.1"
2012-11-05 22:46:47 +00:00
)
var ErrDisconnected = errors.New("Disconnect Called")
2014-02-14 13:51:57 +00:00
// Read data from a connection. To be used as a goroutine.
2012-11-05 23:39:31 +00:00
func (irc *Connection) readLoop() {
defer irc.Done()
br := bufio.NewReaderSize(irc.socket, 512)
2012-03-22 03:50:21 +00:00
errChan := irc.ErrorChan()
for {
select {
case <-irc.end:
return
default:
// Set a read deadline based on the combined timeout and ping frequency
// We should ALWAYS have received a response from the server within the timeout
// after our own pings
if irc.socket != nil {
irc.socket.SetReadDeadline(time.Now().Add(irc.Timeout + irc.PingFreq))
}
msg, err := br.ReadString('\n')
// We got past our blocking read, so bin timeout
if irc.socket != nil {
var zero time.Time
irc.socket.SetReadDeadline(zero)
}
2012-03-22 03:50:21 +00:00
if err != nil {
errChan <- err
2015-11-14 13:10:39 +00:00
return
}
if irc.Debug {
irc.Log.Printf("<-- %s\n", strings.TrimSpace(msg))
}
irc.lastMessage = time.Now()
2015-07-31 05:34:19 +00:00
event, err := parseToEvent(msg)
event.Connection = irc
if err == nil {
/* XXX: len(args) == 0: args should be empty */
irc.RunCallbacks(event)
2012-11-05 22:46:47 +00:00
}
2015-07-31 05:34:19 +00:00
}
}
}
2015-07-31 05:34:19 +00:00
//Parse raw irc messages
func parseToEvent(msg string) (*Event, error) {
2015-07-31 11:03:48 +00:00
msg = strings.TrimSuffix(msg, "\n") //Remove \r\n
msg = strings.TrimSuffix(msg, "\r")
2015-07-31 05:34:19 +00:00
event := &Event{Raw: msg}
if len(msg) < 5 {
return nil, errors.New("Malformed msg from server")
}
if msg[0] == ':' {
if i := strings.Index(msg, " "); i > -1 {
event.Source = msg[1:i]
msg = msg[i+1 : len(msg)]
} else {
return nil, errors.New("Malformed msg from server")
}
if i, j := strings.Index(event.Source, "!"), strings.Index(event.Source, "@"); i > -1 && j > -1 && i < j {
event.Nick = event.Source[0:i]
event.User = event.Source[i+1 : j]
event.Host = event.Source[j+1 : len(event.Source)]
2012-11-05 22:46:47 +00:00
}
}
2015-07-31 05:34:19 +00:00
split := strings.SplitN(msg, " :", 2)
args := strings.Split(split[0], " ")
event.Code = strings.ToUpper(args[0])
event.Arguments = args[1:]
if len(split) > 1 {
event.Arguments = append(event.Arguments, split[1])
}
return event, nil
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Loop to write to a connection. To be used as a goroutine.
2012-11-05 23:39:31 +00:00
func (irc *Connection) writeLoop() {
defer irc.Done()
errChan := irc.ErrorChan()
for {
select {
case <-irc.end:
return
2015-11-14 13:10:39 +00:00
case b, ok := <-irc.pwrite:
if !ok || b == "" || irc.socket == nil {
return
}
if irc.Debug {
irc.Log.Printf("--> %s\n", strings.TrimSpace(b))
}
// Set a write deadline based on the time out
irc.socket.SetWriteDeadline(time.Now().Add(irc.Timeout))
_, err := irc.socket.Write([]byte(b))
// Past blocking write, bin timeout
var zero time.Time
irc.socket.SetWriteDeadline(zero)
if err != nil {
errChan <- err
return
}
2012-11-05 22:46:47 +00:00
}
}
return
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Pings the server if we have not received any messages for 5 minutes
// to keep the connection alive. To be used as a goroutine.
2012-11-05 23:39:31 +00:00
func (irc *Connection) pingLoop() {
defer irc.Done()
ticker := time.NewTicker(1 * time.Minute) // Tick every minute for monitoring
ticker2 := time.NewTicker(irc.PingFreq) // Tick at the ping frequency.
2012-11-05 22:46:47 +00:00
for {
select {
case <-ticker.C:
//Ping if we haven't received anything from the server within the keep alive period
if time.Since(irc.lastMessage) >= irc.KeepAlive {
2012-11-05 23:39:31 +00:00
irc.SendRawf("PING %d", time.Now().UnixNano())
2012-11-05 22:46:47 +00:00
}
case <-ticker2.C:
//Ping at the ping frequency
2012-11-05 23:39:31 +00:00
irc.SendRawf("PING %d", time.Now().UnixNano())
2012-11-05 22:46:47 +00:00
//Try to recapture nickname if it's not as configured.
2012-11-05 23:39:31 +00:00
if irc.nick != irc.nickcurrent {
irc.nickcurrent = irc.nick
irc.SendRawf("NICK %s", irc.nick)
2012-11-05 22:46:47 +00:00
}
case <-irc.end:
ticker.Stop()
ticker2.Stop()
2012-11-11 09:51:14 +00:00
return
2012-11-05 22:46:47 +00:00
}
}
}
2014-02-14 13:51:57 +00:00
// Main loop to control the connection.
func (irc *Connection) Loop() {
errChan := irc.ErrorChan()
2015-11-14 13:10:39 +00:00
for !irc.quit {
err := <-errChan
2014-06-21 14:30:15 +00:00
irc.Log.Printf("Error, disconnected: %s\n", err)
2015-11-14 13:10:39 +00:00
for !irc.quit {
2014-06-21 14:30:15 +00:00
if err = irc.Reconnect(); err != nil {
irc.Log.Printf("Error while reconnecting: %s\n", err)
2015-11-14 13:10:39 +00:00
time.Sleep(60 * time.Second)
} else {
errChan = irc.ErrorChan()
break
}
}
}
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:29:56 +00:00
// Quit the current connection and disconnect from the server
2014-02-14 13:51:57 +00:00
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.1.6
2012-11-05 22:46:47 +00:00
func (irc *Connection) Quit() {
quit := "QUIT"
if irc.QuitMessage != "" {
quit = fmt.Sprintf("QUIT :%s", irc.QuitMessage)
}
irc.SendRaw(quit)
irc.stopped = true
2015-11-14 13:10:39 +00:00
irc.quit = true
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Use the connection to join a given channel.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.2.1
2012-11-05 22:46:47 +00:00
func (irc *Connection) Join(channel string) {
irc.pwrite <- fmt.Sprintf("JOIN %s\r\n", channel)
}
2014-02-14 13:51:57 +00:00
// Leave a given channel.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.2.2
2012-11-05 22:46:47 +00:00
func (irc *Connection) Part(channel string) {
irc.pwrite <- fmt.Sprintf("PART %s\r\n", channel)
}
2014-02-14 13:51:57 +00:00
// Send a notification to a nickname. This is similar to Privmsg but must not receive replies.
2014-02-14 13:29:56 +00:00
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.4.2
2012-11-05 22:46:47 +00:00
func (irc *Connection) Notice(target, message string) {
irc.pwrite <- fmt.Sprintf("NOTICE %s :%s\r\n", target, message)
}
2014-02-14 13:51:57 +00:00
// Send a formated notification to a nickname.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.4.2
2012-11-11 09:37:52 +00:00
func (irc *Connection) Noticef(target, format string, a ...interface{}) {
irc.Notice(target, fmt.Sprintf(format, a...))
}
2014-04-25 04:56:30 +00:00
// Send (action) message to a target (channel or nickname).
// No clear RFC on this one...
func (irc *Connection) Action(target, message string) {
irc.pwrite <- fmt.Sprintf("PRIVMSG %s :\001ACTION %s\001\r\n", target, message)
2014-04-25 04:56:30 +00:00
}
2014-10-07 20:29:22 +00:00
// Send formatted (action) message to a target (channel or nickname).
func (irc *Connection) Actionf(target, format string, a ...interface{}) {
irc.Action(target, fmt.Sprintf(format, a...))
}
2014-02-14 13:51:57 +00:00
// Send (private) message to a target (channel or nickname).
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.4.1
2012-11-05 22:46:47 +00:00
func (irc *Connection) Privmsg(target, message string) {
irc.pwrite <- fmt.Sprintf("PRIVMSG %s :%s\r\n", target, message)
}
2014-02-14 13:51:57 +00:00
// Send formated string to specified target (channel or nickname).
2012-11-11 09:37:52 +00:00
func (irc *Connection) Privmsgf(target, format string, a ...interface{}) {
irc.Privmsg(target, fmt.Sprintf(format, a...))
}
2015-07-21 22:41:16 +00:00
// Kick <user> from <channel> with <msg>. For no message, pass empty string ("")
func (irc *Connection) Kick(user, channel, msg string) {
var cmd bytes.Buffer
cmd.WriteString(fmt.Sprintf("KICK %s %s", channel, user))
if msg != "" {
cmd.WriteString(fmt.Sprintf(" :%s", msg))
}
cmd.WriteString("\r\n")
irc.pwrite <- cmd.String()
}
// Kick all <users> from <channel> with <msg>. For no message, pass
// empty string ("")
func (irc *Connection) MultiKick(users []string, channel string, msg string) {
var cmd bytes.Buffer
cmd.WriteString(fmt.Sprintf("KICK %s %s", channel, strings.Join(users, ",")))
2015-07-21 22:41:16 +00:00
if msg != "" {
cmd.WriteString(fmt.Sprintf(" :%s", msg))
}
cmd.WriteString("\r\n")
irc.pwrite <- cmd.String()
}
2014-02-14 13:51:57 +00:00
// Send raw string.
2012-11-05 22:46:47 +00:00
func (irc *Connection) SendRaw(message string) {
irc.pwrite <- message + "\r\n"
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Send raw formated string.
2012-11-05 22:46:47 +00:00
func (irc *Connection) SendRawf(format string, a ...interface{}) {
irc.SendRaw(fmt.Sprintf(format, a...))
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Set (new) nickname.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.1.2
2013-03-13 11:53:08 +00:00
func (irc *Connection) Nick(n string) {
irc.nick = n
irc.SendRawf("NICK %s", n)
}
2014-02-14 13:29:56 +00:00
// Determine nick currently used with the connection.
2012-11-05 22:46:47 +00:00
func (irc *Connection) GetNick() string {
return irc.nickcurrent
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:51:57 +00:00
// Query information about a particular nickname.
2014-02-14 13:29:56 +00:00
// RFC 1459: https://tools.ietf.org/html/rfc1459#section-4.5.2
func (irc *Connection) Whois(nick string) {
irc.SendRawf("WHOIS %s", nick)
}
2014-02-14 13:51:57 +00:00
// Query information about a given nickname in the server.
2014-02-14 13:29:56 +00:00
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.5.1
func (irc *Connection) Who(nick string) {
irc.SendRawf("WHO %s", nick)
}
2014-02-14 13:51:57 +00:00
// Set different modes for a target (channel or nickname).
2014-02-14 13:29:56 +00:00
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.2.3
func (irc *Connection) Mode(target string, modestring ...string) {
if len(modestring) > 0 {
mode := strings.Join(modestring, " ")
irc.SendRawf("MODE %s %s", target, mode)
return
}
irc.SendRawf("MODE %s", target)
}
func (irc *Connection) ErrorChan() chan error {
return irc.Error
}
2014-10-24 01:17:58 +00:00
// Returns true if the connection is connected to an IRC server.
func (irc *Connection) Connected() bool {
return !irc.stopped
}
2014-02-16 13:20:13 +00:00
// A disconnect sends all buffered messages (if possible),
// stops all goroutines and then closes the socket.
func (irc *Connection) Disconnect() {
for event := range irc.events {
irc.ClearCallback(event)
}
2015-07-31 06:30:21 +00:00
if irc.end != nil {
close(irc.end)
}
irc.end = nil
2015-07-31 06:30:21 +00:00
if irc.pwrite != nil {
close(irc.pwrite)
}
2012-11-05 22:46:47 +00:00
irc.Wait()
2015-07-31 19:33:36 +00:00
if irc.socket != nil {
irc.socket.Close()
}
irc.socket = nil
irc.ErrorChan() <- ErrDisconnected
}
2012-03-22 03:50:21 +00:00
2014-02-14 13:29:56 +00:00
// Reconnect to a server using the current connection.
func (irc *Connection) Reconnect() error {
if irc.end != nil {
close(irc.end)
}
irc.end = nil
irc.Wait() //make sure that wait group is cleared ensuring that all spawned goroutines have completed
irc.end = make(chan struct{})
return irc.Connect(irc.Server)
2012-11-05 22:46:47 +00:00
}
2014-02-14 13:29:56 +00:00
// Connect to a given server using the current connection configuration.
// This function also takes care of identification if a password is provided.
// RFC 1459 details: https://tools.ietf.org/html/rfc1459#section-4.1
func (irc *Connection) Connect(server string) error {
irc.Server = server
// mark Server as stopped since there can be an error during connect
irc.stopped = true
// make sure everything is ready for connection
if len(irc.Server) == 0 {
return errors.New("empty 'server'")
}
if strings.Count(irc.Server, ":") != 1 {
return errors.New("wrong number of ':' in address")
}
if strings.Index(irc.Server, ":") == 0 {
return errors.New("hostname is missing")
}
if strings.Index(irc.Server, ":") == len(irc.Server)-1 {
return errors.New("port missing")
}
2014-02-16 10:41:38 +00:00
// check for valid range
ports := strings.Split(irc.Server, ":")[1]
2014-02-16 10:41:38 +00:00
port, err := strconv.Atoi(ports)
2014-02-16 13:20:13 +00:00
if err != nil {
2014-02-16 10:41:38 +00:00
return errors.New("extracting port failed")
}
if !((port >= 0) && (port <= 65535)) {
return errors.New("port number outside valid range")
}
2014-02-16 13:20:13 +00:00
if irc.Log == nil {
return errors.New("'Log' points to nil")
}
2014-02-16 13:20:13 +00:00
if len(irc.nick) == 0 {
return errors.New("empty 'nick'")
}
2014-02-16 13:20:13 +00:00
if len(irc.user) == 0 {
return errors.New("empty 'user'")
}
2012-11-07 20:55:33 +00:00
if irc.UseTLS {
dialer := &net.Dialer{Timeout: irc.Timeout}
irc.socket, err = tls.DialWithDialer(dialer, "tcp", irc.Server, irc.TLSConfig)
} else {
irc.socket, err = net.DialTimeout("tcp", irc.Server, irc.Timeout)
}
2012-11-05 22:46:47 +00:00
if err != nil {
return err
}
irc.stopped = false
irc.Log.Printf("Connected to %s (%s)\n", irc.Server, irc.socket.RemoteAddr())
irc.pwrite = make(chan string, 10)
irc.Error = make(chan error, 2)
irc.Add(3)
go irc.readLoop()
go irc.writeLoop()
go irc.pingLoop()
if len(irc.Password) > 0 {
irc.pwrite <- fmt.Sprintf("PASS %s\r\n", irc.Password)
2012-11-05 22:46:47 +00:00
}
irc.pwrite <- fmt.Sprintf("NICK %s\r\n", irc.nick)
irc.pwrite <- fmt.Sprintf("USER %s 0.0.0.0 0.0.0.0 :%s\r\n", irc.user, irc.user)
2012-11-05 22:46:47 +00:00
return nil
}
2014-02-14 13:29:56 +00:00
// Create a connection with the (publicly visible) nickname and username.
2014-02-16 13:20:13 +00:00
// The nickname is later used to address the user. Returns nil if nick
// or user are empty.
2012-11-05 22:46:47 +00:00
func IRC(nick, user string) *Connection {
// catch invalid values
2014-02-16 13:20:13 +00:00
if len(nick) == 0 {
return nil
}
2014-02-16 13:20:13 +00:00
if len(user) == 0 {
return nil
}
irc := &Connection{
nick: nick,
nickcurrent: nick,
user: user,
Log: log.New(os.Stdout, "", log.LstdFlags),
end: make(chan struct{}),
Version: VERSION,
KeepAlive: 4 * time.Minute,
Timeout: 1 * time.Minute,
PingFreq: 15 * time.Minute,
QuitMessage: "",
}
2012-11-05 22:46:47 +00:00
irc.setupCallbacks()
return irc
}