-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathirc.go
314 lines (280 loc) · 7.41 KB
/
irc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package goirc
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"regexp"
"strings"
"time"
)
const (
IRC_READ_CHUNK = 4096
IRC_READ_ALL = 0
IRC_TIMEOUT = "3s"
)
var (
pingRegex = regexp.MustCompile("^PING :([\\w.]+)$")
chanNames = regexp.MustCompile("^:[\\w.]+ \\d+ \\w+ #?\\w+ :.+$")
serverMsg = regexp.MustCompile("^\\w+\\.\\w+\\.\\w+\\. .+$")
pings int64 = 0
)
type Irc struct {
server string
port int
nick string
real string
host string
sys string
user string
channels []string
password string
reconnect bool
conn *net.TCPConn
}
/*
NewIrc creates a new Irc struct from a JSON configuration file. Required fields are:
* server: specifies the IRC server to connect to
* user: username on the server
* nick: nickname to use on the server
* real: real name
* sys: system name
* channels: a string or list of strings specifying channels to connect to
*/
func NewIrc(filename string) (cfg *Irc, err error) {
var jsonByte []byte
var jsonCfg map[string]interface{}
if jsonByte, err = ioutil.ReadFile(filename); err != nil {
return
}
err = json.Unmarshal(jsonByte, &jsonCfg)
if err != nil {
fmt.Println("[!] error unmarshalling JSON: ", err.Error())
return
} else {
// TODO: this really needs to be cleaned up
cfg = new(Irc)
if server, ok := jsonCfg["server"]; ok {
cfg.server = server.(string)
}
if port, ok := jsonCfg["port"]; ok {
cfg.port = port.(int)
}
if nick, ok := jsonCfg["nick"]; ok {
cfg.nick = nick.(string)
}
if real, ok := jsonCfg["real"]; ok {
cfg.real = real.(string)
}
if host, ok := jsonCfg["host"]; ok {
cfg.host = host.(string)
}
if sys, ok := jsonCfg["sys"]; ok {
cfg.sys = sys.(string)
}
if password, ok := jsonCfg["password"]; ok {
cfg.password = password.(string)
}
if user, ok := jsonCfg["user"]; ok {
cfg.user = user.(string)
}
if channels, ok := jsonCfg["channels"]; ok {
switch v := channels.(type) {
case string:
cfg.channels = append(cfg.channels, v)
fmt.Println(cfg.channels)
case []interface{}:
for _, ch := range channels.([]interface{}) {
cfg.channels = append(cfg.channels, ch.(string))
}
}
}
if reconn, ok := jsonCfg["reconnect"]; ok {
cfg.reconnect = reconn.(bool)
}
if cfg.port == 0 {
cfg.port = 6667
}
if cfg.real == "" {
cfg.real = "GoKyle IRC client"
}
if cfg.server == "" || cfg.user == "" || cfg.nick == "" ||
cfg.real == "" || cfg.sys == "" || len(cfg.channels) == 0 {
err = fmt.Errorf("invalid configuration file")
}
}
return
}
// Connect carries out the IRC connection, including identification and
// channel joining.
func (irc *Irc) Connect() (connected bool, err error) {
var ircServer *net.TCPAddr
connected = false
/* TODO: provide ipv6 support */
if ircServer, err = net.ResolveTCPAddr("tcp", irc.ConnStr()); err != nil {
fmt.Printf("[!] couldn't connect to %s: %s\n", irc.ConnStr(),
err.Error())
return
} else if irc.conn, err = net.DialTCP("tcp", nil, ircServer); err != nil {
fmt.Printf("[!] couldn't dial out: %s\n", err.Error())
return
}
if _, err = irc.Recv(IRC_READ_CHUNK, false); err != nil {
fmt.Printf("[!] no response from server: %s\n", err.Error())
return
}
fmt.Println("[+] sending nick")
if err = irc.Send("NICK " + irc.nick); err != nil {
fmt.Printf("[!] error setting nick: %s\n", err.Error())
return
}
fmt.Println("[+] sending user")
if err = irc.Send(irc.userline()); err != nil {
fmt.Printf("[!] error setting user: %s\n", err.Error())
return
}
if _, err = irc.Recv(IRC_READ_CHUNK, true); err != nil {
fmt.Printf("[!] read error: %s\n", err.Error())
return
}
fmt.Println("[+] identifying")
if err = irc.identify(); err != nil {
fmt.Printf("[!] error identifying: %s\n", err.Error())
return
}
fmt.Println("[+] join channels:")
for _, ch := range irc.channels {
fmt.Printf("\t[*] %s\n", ch)
if err = irc.Send("JOIN " + ch); err != nil {
fmt.Printf("[!] error join channel %s: %s\n",
ch, err.Error())
return
} else {
irc.Msg(ch, "hello")
}
}
connected = true
return
}
// Send is a wrapper around the TCPConn.Write that adds proper line endings to strings.
func (irc *Irc) Send(msg string) (err error) {
_, err = irc.conn.Write(ircbytes(msg))
return
}
// Recv listens for incoming messages. Two constants have been provided for
// use: IRC_READ_CHUNK should be used in almost all cases, as it listens for
// a fixed size message; IRC_READ_ALL will read until the connection closes.
// The block parameter, if false, will set a timeout on the socket (this
// timeout can be changed by modifying the constant IRC_TIMEOUT), resetting
// the socket to blocking mode after the receive.
func (irc *Irc) Recv(size int, block bool) (reply string, err error) {
buf := make([]byte, size)
if !block {
dur, _ := time.ParseDuration(IRC_TIMEOUT)
timeo := time.Now().Add(dur)
irc.conn.SetDeadline(timeo)
}
if size == 0 {
buf, err = ioutil.ReadAll(irc.conn)
} else {
_, err = irc.conn.Read(buf)
}
if err != nil {
if err == io.EOF {
fmt.Println("[+] connection closed.")
irc.Quit(0)
} else if err != nil && timeout(err) {
fmt.Println("[-] timeout: resetting err")
err = nil
}
}
reply = strings.TrimFunc(string(buf), TrimReply)
irc.conn.SetDeadline(time.Unix(0, 0))
return
}
// ConnStr returns a host:port string from the Irc fields.
func (irc *Irc) ConnStr() string {
return fmt.Sprintf("%s:%d", irc.server, irc.port)
}
// Disconnect sends a disconnect command to the IRC server.
func (irc *Irc) Disconnect() error {
if irc.conn == nil {
return nil
}
err := irc.Send("QUIT")
if err != nil {
fmt.Println("[!] disconnect error: ", err.Error())
return err
}
return err
}
// Pong sends a ping reply to the server.
func (irc *Irc) Pong(daemon string) {
pings++
fmt.Printf("PONG #%d -> %s \n", pings, daemon)
irc.Send("PONG " + daemon)
}
// Reply is a helper function to send a reply.
func (irc *Irc) Reply(sender string, message string) (err error) {
err = irc.Msg(sender, message)
return
}
// Message sends a PRIVMSG.
func (irc *Irc) Msg(to string, message string) (err error) {
pm := fmt.Sprintf("PRIVMSG %s :%s", to, message)
return irc.Send(pm)
}
// Quit disconnects and exits the IRC interface.
func (irc *Irc) Quit(ret int) {
irc.Disconnect()
os.Exit(ret)
}
// ircbytes converts the text to a byte slice with the standard IRC line
// endings.
func ircbytes(text string) (msg []byte) {
msg = []byte(fmt.Sprintf("%s\r\n", text))
return
}
// userline returns an appropriate USER line for connecting to an IRC
// server.
func (irc *Irc) userline() string {
return fmt.Sprintf("USER %s %s %s %s", irc.user, irc.host,
irc.sys, irc.real)
}
// timeout determines whether an error is a timeout
func timeout(err error) bool {
timeoRe := regexp.MustCompile("i/o timeout")
if timeoRe.MatchString(err.Error()) {
return true
}
return false
}
// identify returns an identification string.
func (irc *Irc) identify() error {
if irc.password == "" {
return nil
}
ident := fmt.Sprintf("IDENTIFY %s %s", irc.user, irc.password)
err := irc.Msg("NickServ", ident)
return err
}
// TrimReply is a trim function for use with the reply returned from
// the socket read.
func TrimReply(r rune) bool {
switch r {
case ' ':
return true
case '\t':
return true
case '\n':
return true
case '\r':
return true
case '\x00':
return true
default:
return false
}
}