-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
399 lines (358 loc) · 8.74 KB
/
net.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package ircb
import (
"bufio"
"crypto/tls"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
diamond "github.com/aerth/diamond/lib"
"github.com/boltdb/bolt"
)
var version = "ircb v0.0.9"
// Connection will be divided into:
// Client
// Connection
//
type Connection struct {
Log *log.Logger
HTTPClient *http.Client // customize user agent, proxy, tls, redirects, etc
CommandMap map[string]Command // map of command names to Command functions
MasterMap map[string]Command // map of master command names to Command functions
diamond *diamond.System // can be nil
config *Config // current config
boltdb *bolt.DB // opened database
conn io.ReadWriteCloser
since time.Time // since connected to server
masterauth time.Time // auth and auth timeout
reader *bufio.Reader
maplock sync.Mutex // guards (both) command map writes
connected bool
joined bool
quiet bool
}
// NewConnection returns an unconnected client from the given config
func (config *Config) NewConnection() *Connection {
if config.Database == "" {
config.Database = "bolt.db"
}
c := new(Connection)
c.config = config
c.since = time.Now()
// TODO: custom client for user agent, proxy support
c.HTTPClient = http.DefaultClient
c.HTTPClient.Timeout = time.Second * 3
c.CommandMap = DefaultCommandMap()
c.MasterMap = DefaultMasterMap()
if config.Verbose {
c.Log = log.New(os.Stderr, "", log.Lshortfile)
} else {
c.Log = log.New(os.Stderr, "", log.Ltime)
}
return c
}
func (cfg *Config) dialtls() (*tls.Conn, error) {
return tls.Dial("tcp", cfg.Host, &tls.Config{
InsecureSkipVerify: cfg.InvalidSSL,
})
}
// Connect dials the host
func (c *Connection) Connect() (err error) {
if !c.connected {
c.connected = true
defer func(c *Connection) {
c.connected = false
c.Close()
}(c)
if c.config.Diamond {
if c.config.DiamondSocket == "" {
c.config.DiamondSocket = "control.socket"
}
c.diamond, err = diamond.New(c.config.DiamondSocket)
if err != nil {
return err
}
c.diamond.Config.Kickable = true
c.diamond.SetRunlevel(0, func() error {
return c.Close()
})
c.diamond.SetRunlevel(1, func() error { return nil })
c.diamond.Runlevel(1)
}
c.boltdb, err = loadDatabase(c.config.Database)
if err != nil {
return err
}
// dial direct
c.Log.Println(version)
c.Log.Println("connecting...")
fmt.Printf("%s\n", c.MarshalConfig())
if c.config.UseSSL {
c.conn, err = c.config.dialtls()
} else {
c.conn, err = net.Dial("tcp", c.config.Host)
}
if err != nil {
return err
}
err = c.initialconnect()
if err != nil {
return err
}
c.Log.Println("connected.")
return c.readerwriter()
}
return fmt.Errorf("already connected")
}
// Diamond returns ircb's diamond system, will be nil if not connected or not configured with 'Diamond: true'
func (c *Connection) Diamond() *diamond.System {
return c.diamond
}
// Database returns ircb's database system, will be nil if not connected
func (c *Connection) Database() *bolt.DB {
return c.boltdb
}
// Close all connections and databases, remove diamond.socket
func (c *Connection) Close() error {
if c == nil {
return nil
}
if c.boltdb != nil {
err1 := c.boltdb.Close()
if err1 != nil {
c.Log.Println(err1)
}
}
os.Remove("diamond.socket")
if c.conn != nil {
_, err := c.conn.Write([]byte(fmt.Sprintf("QUIT :%s\r\n", version)))
if err != nil {
c.Log.Println(err)
}
if c != nil && c.conn != nil {
return c.conn.Close()
}
}
return nil
}
// Write to irc connection, adding '\r\n'
func (c *Connection) Write(b []byte) (n int, err error) {
if strings.TrimSpace(string(b)) == "" || len(b) < 4 {
return 0, fmt.Errorf("write too small")
}
if string(b[len(b)-2:]) != "\r\n" {
b = append(b, "\r\n"...)
}
str := string(b)
if c.quiet && strings.Contains(str, "PRIVMSG") {
if c.config.Verbose {
c.Log.Println("MUTED:", str)
}
return
}
if c.config.Verbose {
c.Log.Println("SEND", str)
}
return c.conn.Write(b)
}
// MasterCheck sends a private message to NickServ to authenticate master user
//
// -1 no auth mode
// 0 default, freenode and oragono ACC style
// 1 STATUS style
//
func (c *Connection) MasterCheck() {
switch c.config.AuthMode {
case -1:
// no auth mode
c.Log.Println("WARNING:", "Authentication Disabled.")
c.masterauth = time.Now()
default:
// freenode and oragono style
_, err := c.conn.Write([]byte("" +
"PRIVMSG NickServ :ACC " + strings.Split(c.config.Master, ":")[0] + "\r\n"))
if err != nil {
c.Log.Printf("auth error: %b", err)
}
case 1:
// STATUS style
_, err := c.conn.Write([]byte("" +
"PRIVMSG NickServ :STATUS " + strings.Split(c.config.Master, ":")[0] + "\r\n"))
if err != nil {
c.Log.Printf("auth error: %b", err)
}
}
}
// SendMaster sends formatted text to master user
func (c *Connection) SendMaster(format string, i ...interface{}) {
if strings.TrimSpace(format) == "" {
return
}
reply := IRC{
To: strings.Split(c.config.Master, ":")[0],
Message: fmt.Sprintf(format, i...),
}
c.Send(reply)
}
// Send IRC message (uses To and Message fields)
func (c *Connection) Send(irc IRC) {
irc.Message = strings.TrimSuffix(irc.Message, "\n")
if strings.Contains(irc.Message, "\n") {
messages := strings.Split(irc.Message, "\n")
for _, v := range messages {
if strings.TrimSpace(v) == "" {
continue
}
line := IRC{
To: irc.To,
Message: v,
}
c.Send(line)
<-time.After(time.Second)
}
return
}
e := irc.Encode()
c.Log.Printf(">%q", string(e))
if len(e) < 512 {
_, err := c.Write(e)
if err != nil {
c.Log.Println(err)
}
return
}
var line string
for i, r := range []rune(irc.Message) {
line = line + string(r)
if i > 0 && (i+1)%500 == 0 {
msg := IRC{
To: irc.To,
Message: line,
}
c.Write(msg.Encode())
line = ""
}
}
}
func (c *Connection) initialconnect() error {
b := make([]byte, 512)
_, err := c.conn.Read(b)
if err != nil {
return err
}
c.Log.Println(string(b))
_, err = c.conn.Write([]byte(fmt.Sprintf("NICK %s\r\n", c.config.Nick)))
if err != nil {
return err
}
_, err = c.conn.Write([]byte(fmt.Sprintf("USER %s 0.0.0.0 0.0.0.0 :%s\r\n", c.config.Nick, c.config.Nick)))
if err != nil {
return err
}
_, err = c.conn.Write([]byte(fmt.Sprintf("MODE %s :%s", c.config.Nick, "+i\r\n")))
if err != nil {
return err
}
return nil
}
// read until read error
func (c *Connection) readerwriter() error {
logfile, err := openlogfile()
if err != nil {
return err
}
defer logfile.Close()
defer c.Log.SetOutput(os.Stderr)
mw := io.MultiWriter(os.Stderr, logfile)
c.Log.SetOutput(mw)
logfile.Write([]byte(fmt.Sprintf("log started: %s\n", time.Now().String())))
logfile.Sync()
c.Log.Println("reading from net")
defer c.Log.Println("reader stopping")
c.reader = bufio.NewReaderSize(c.conn, 512)
for {
msg, err := c.reader.ReadString('\n')
if err != nil {
return err
}
if c.config.Verbose {
c.Log.Printf("read: %q", msg)
logfile.Sync()
}
// handle PING
if strings.HasPrefix(msg, "PING") {
pong := []byte(strings.Replace(msg, "PING", "PONG", -1))
_, err = c.Write(pong)
if err != nil {
c.Log.Println(err)
}
continue
}
msg = strings.TrimPrefix(msg, ":")
// parse
cfg := *c.config
irc := cfg.Parse(msg)
// numeric 'verb'
if _, err := strconv.Atoi(irc.Verb); err == nil {
if verbIntHandler(c, irc) {
continue
}
}
switch irc.Verb {
default:
c.Log.Println("new verb", irc.Verb, irc.Message)
if c.config.Verbose {
c.Log.Println(irc)
}
continue
case "QUIT", "PART", "NICK", "JOIN":
continue
case "NOTICE":
// :NickServ!NickServ@services. NOTICE mastername :mustangsally ACC 3
switch irc.ReplyTo {
case "NickServ":
switch c.config.AuthMode {
default:
if irc.Raw == fmt.Sprintf(formatauth, c.config.Nick, strings.Split(c.config.Master, ":")[0]) {
c.masterauth = time.Now()
}
case -1:
c.masterauth = time.Now()
case 1:
if irc.Message == fmt.Sprintf(formatauth2, strings.Split(c.config.Master, ":")[0]) {
c.masterauth = time.Now()
}
}
default:
c.Log.Println("NOTICE", irc.ReplyTo, irc.Message)
}
case "MODE":
c.Log.Printf("NEW MODE: %q", irc.Message)
if !c.joined {
for _, ch := range strings.Split(c.config.Channels, ",") {
if ch != "" {
c.Log.Println("Joining channel:", ch)
c.Write([]byte(fmt.Sprintf("JOIN %s", ch)))
}
}
c.joined = true
c.Log.Println("Starting normal operation")
c.SendMaster("hello, master")
}
case "PRIVMSG":
// maybe master command
if irc.ReplyTo == strings.Split(c.config.Master, ":")[0] {
if privmsgMasterHandler(c, irc) {
continue
}
}
privmsgHandler(c, irc)
}
}
}