-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathirc.go
More file actions
445 lines (400 loc) · 10.6 KB
/
irc.go
File metadata and controls
445 lines (400 loc) · 10.6 KB
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// SPDX-License-Identifier: MIT
//
// Copyright (c) 2025 Aaron LI
//
// IRC bot to fetch messages.
//
package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"fmt"
"log/slog"
"net"
"regexp"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
irc "github.com/fluffle/goirc/client"
ttlcache "github.com/liweitianux/dflybot/ttlcache"
)
const (
baseBackoff = 5 * time.Second
maxBackoff = 5 * time.Minute
pingFreq = 60 * time.Second
nickCheckFreq = 60 * time.Second
opmeLeeway = 60 * time.Second
)
type IrcConfig struct {
Nick string
Server string
Port uint16
SSL bool
Channels []struct {
Name string
OpMe map[string]string
}
}
type IrcBot struct {
config *IrcConfig
conn *irc.Conn
bus *Bus
cache *ttlcache.Cache
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewIrcBot(cfg *IrcConfig, bus *Bus) *IrcBot {
ic := irc.NewConfig(cfg.Nick)
ic.Server = net.JoinHostPort(cfg.Server, strconv.Itoa(int(cfg.Port)))
ic.Timeout = 30 * time.Second
ic.NewNick = func(old string) string { return old + "_" }
if cfg.SSL {
ic.SSL = true
ic.SSLConfig = &tls.Config{
ServerName: cfg.Server,
InsecureSkipVerify: true,
}
}
// NOTE: Clear PingFreq to disable the builtin PING loop as we'll also
// perform PINGs in startWatchdog().
ic.PingFreq = 0
conn := irc.Client(ic)
ibot := &IrcBot{
config: cfg,
conn: conn,
bus: bus,
cache: ttlcache.New(opmeLeeway*2, 0, nil),
}
conn.EnableStateTracking()
conn.HandleFunc(irc.CONNECTED, func(c *irc.Conn, _ *irc.Line) {
slog.Info("IRC connected", "server", c.Config().Server, "nick", c.Me().Nick)
for _, ch := range ibot.config.Channels {
c.Join(ch.Name)
slog.Info("IRC joined", "channel", ch.Name)
}
})
conn.HandleFunc(irc.DISCONNECTED, func(c *irc.Conn, _ *irc.Line) {
slog.Info("IRC disconnected", "server", c.Config().Server)
})
conn.HandleFunc(irc.PING, func(_ *irc.Conn, l *irc.Line) {
slog.Debug("IRC PING from server", "line", l.Raw)
})
conn.HandleFunc(irc.PRIVMSG, func(c *irc.Conn, l *irc.Line) {
slog.Debug("IRC received message", "target", l.Target(), "sender", l.Nick, "text", l.Text())
me := c.Me().Nick
re := regexp.MustCompile(`^@?` + me + `\s*[:,]?\s+`)
text := strings.TrimSpace(l.Text())
if loc := re.FindStringIndex(text); loc != nil {
text = text[loc[1]:]
}
if target := l.Target(); target == l.Nick {
// Private message to me.
ibot.tryCommand(text, target, l)
} else if !ibot.tryCommand(text, target, l) {
ibot.bus.Produce(Message{
Source: SourceIRC,
Timestamp: time.Now(),
From: l.Nick,
Target: target,
Text: text,
})
}
})
conn.HandleFunc(irc.QUIT, func(_ *irc.Conn, _ *irc.Line) {
ibot.tryRecoverNick()
})
conn.HandleFunc(irc.NICK, func(c *irc.Conn, l *irc.Line) {
if l.Nick != c.Me().Nick {
ibot.tryRecoverNick()
}
})
conn.HandleFunc(irc.ACTION, func(c *irc.Conn, l *irc.Line) {
slog.Debug("IRC received action", "target", l.Target(), "sender", l.Nick, "text", l.Text())
ibot.bus.Produce(Message{
Source: SourceIRC,
Timestamp: time.Now(),
Event: "ACTION",
From: l.Nick,
Target: l.Target(),
Text: l.Text(),
})
})
return ibot
}
func (b *IrcBot) tryCommand(text, target string, l *irc.Line) bool {
if !strings.HasPrefix(text, "!") {
return false
}
cmd, arg, _ := strings.Cut(strings.TrimPrefix(text, "!"), " ")
cmd = strings.ToLower(cmd)
arg = strings.TrimSpace(arg)
slog.Debug("IRC received command", "cmd", cmd, "arg", arg)
// TODO: more commands
switch cmd {
case "ping":
b.conn.Privmsg(target, "pong")
return true
case "opme":
if !strings.HasPrefix(target, "#") {
b.conn.Privmsg(target, "command opme only works in channel")
return true
}
ch := target
if !b.hasModeOp(ch) {
b.conn.Privmsg(ch, l.Nick+": I don't have the permission yet")
return true
}
b.handleOpMe(ch, l.Nick, arg)
return true
default:
b.conn.Privmsg(target, "unknown command: "+cmd)
slog.Warn("IRC unknown command", "cmd", cmd, "arg", arg)
return false
}
}
func (b *IrcBot) tryRecoverNick() {
nick := b.config.Nick
state := b.conn.StateTracker()
if me := state.Me().Nick; me == nick {
return
} else if state.GetNick(nick) == nil {
slog.Info("IRC tried to recover nick", "current", me, "wanted", nick)
b.conn.Nick(nick)
} else {
slog.Debug("IRC wanted nick not available", "nick", nick)
}
}
func (b *IrcBot) hasModeOp(ch string) bool {
state := b.conn.StateTracker()
channel := state.GetChannel(ch)
if channel == nil {
slog.Warn("IRC state tracker cannot find", "channel", ch)
return false
}
me := b.conn.Me().Nick
privs, ok := channel.Nicks[me]
if !ok {
slog.Warn("IRC privileges not found", "channel", ch, "me", me)
return false
}
slog.Debug("IRC bot mode info", "channel", ch, "me", me, "privileges", privs)
return privs.Op
}
func (b *IrcBot) handleOpMe(channel, nick, arg string) {
var creds map[string]string
for _, ch := range b.config.Channels {
if ch.Name == channel {
creds = ch.OpMe
break
}
}
if creds == nil {
b.conn.Privmsg(nick, "unsupported opme channel: "+channel)
return
}
// arg: <username>:<timestamp>:<hmac>
args := strings.Split(arg, ":")
if len(args) != 3 {
b.conn.Privmsg(nick, "invalid opme argument: "+arg)
return
}
username, timestamp, mac := args[0], args[1], strings.ToLower(args[2])
authID := username + ":" + timestamp
ts, err := strconv.ParseInt(timestamp, 10, 64)
if err != nil {
b.conn.Privmsg(nick, "invalid opme argument: "+arg)
slog.Debug("IRC opme timestamp invalid", "timestamp", timestamp)
return
}
d := time.Since(time.Unix(ts, 0))
if d.Abs() > opmeLeeway {
b.conn.Privmsg(nick, "invalid opme argument: "+arg)
slog.Debug("IRC opme timestamp out-of-range", "timestamp", timestamp)
return
}
// NOTE: The nick may be occupied by someone else, so don't require
// the sender has the exact nick as configured.
var macKey string
for n, k := range creds {
if n == username {
macKey = k
break
}
}
if macKey == "" {
b.conn.Privmsg(nick, "opme denied")
slog.Debug("IRC opme username invalid", "username", username)
return
}
h := hmac.New(sha256.New, []byte(macKey))
h.Write([]byte(authID))
expected := hex.EncodeToString(h.Sum(nil))
if expected != mac {
b.conn.Privmsg(nick, "opme denied")
slog.Debug("IRC opme mac invalid", "mac", mac, "expected", expected)
return
}
if _, exists := b.cache.Get(authID); exists {
b.conn.Privmsg(nick, "opme denied")
slog.Debug("IRC opme auth replayed", "authID", authID)
return
}
b.cache.Add(authID, struct{}{}, ttlcache.DefaultTTL)
b.conn.Mode(channel, "+o", nick)
slog.Info("IRC opme granted", "channel", channel, "nick", nick, "username", username)
}
func (b *IrcBot) Start() {
ctx, cancel := context.WithCancel(context.Background())
b.cancel = cancel
b.wg.Add(1)
go b.startWatchdog(ctx)
b.wg.Add(1)
go b.startNickCheck(ctx)
defer func() {
b.conn.Quit("shutting down; bye :P")
time.Sleep(500 * time.Millisecond) // wait a moment
b.conn.Close()
slog.Info("IRC bot closed")
b.wg.Done()
}()
b.wg.Add(1)
backoff := baseBackoff
for {
select {
case <-ctx.Done():
return
default:
}
server := b.conn.Config().Server
slog.Debug("IRC attempting to connect", "server", server)
if err := b.conn.Connect(); err != nil {
slog.Error("IRC connection failed", "server", server, "error", err, "backoff", backoff)
time.Sleep(backoff)
backoff *= 2
if backoff > maxBackoff {
backoff = maxBackoff
}
continue
}
backoff = baseBackoff
// Block until disconnected or context cancelled.
for {
if !b.conn.Connected() {
slog.Warn("IRC connection lost; reconnecting ...")
break
}
select {
case <-ctx.Done():
return
case <-time.After(1 * time.Second):
}
}
}
}
// The watchdog periodically pings the server to proactively detect the
// disconnection (e.g., network lost, laptop suspension) and then force a
// reconnection. This is needed because goirc doesn't support to disable the
// TCP keepalive and doesn't expose the underlying connection to archieve that.
// Without disabling TCP keepalive, I observed that goirc waited about 15
// minutes before detecting the disconnection.
//
// NOTE: Using PING might not work with some IRC servers, because the standard
// only defines the server->client PING but not the client->server PING.
func (b *IrcBot) startWatchdog(ctx context.Context) {
var lastPong atomic.Int64
remover := b.conn.HandleFunc(irc.PONG, func(_ *irc.Conn, l *irc.Line) {
slog.Debug("IRC PONG from server", "line", l.Raw)
lastPong.Store(time.Now().UnixNano())
})
defer func() {
remover.Remove()
b.wg.Done()
}()
timeout := time.Duration(1.5*pingFreq.Seconds()) * time.Second
ticker := time.NewTicker(pingFreq)
lastPong.Store(time.Now().UnixNano())
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
if !b.conn.Connected() {
lastPong.Store(time.Now().UnixNano())
continue // handled in Start() above
}
last := time.Unix(0, lastPong.Load())
if time.Since(last) >= timeout {
slog.Warn("IRC health check failed", "last_pong", last)
b.conn.Close()
lastPong.Store(time.Now().UnixNano())
continue
}
b.conn.Ping(fmt.Sprintf("healthcheck-%d", time.Now().UnixNano()))
slog.Debug("IRC sent PING to server")
}
}
}
func (b *IrcBot) startNickCheck(ctx context.Context) {
defer b.wg.Done()
ticker := time.NewTicker(nickCheckFreq)
for {
select {
case <-ctx.Done():
ticker.Stop()
return
case <-ticker.C:
if !b.conn.Connected() {
continue
}
b.tryRecoverNick()
}
}
}
func (b *IrcBot) Stop() {
b.cache.Close()
if b.cancel != nil {
b.cancel()
b.cancel = nil
}
b.wg.Wait()
slog.Info("IRC bot stopped")
}
func (b *IrcBot) Post(msg Message) {
if msg.Source == SourceIRC {
return // Ignore messages originated from self.
}
if b.conn == nil || !b.conn.Connected() {
slog.Error("IRC bot not started/connected")
return
}
state := b.conn.StateTracker()
if strings.HasPrefix(msg.Target, "#") {
if state.GetChannel(msg.Target) == nil {
slog.Warn("IRC bot not joined", "channel", msg.Target)
return
}
} else {
if state.GetNick(msg.Target) == nil {
slog.Warn("IRC bot not seen", "nick", msg.Target)
return
}
}
var from string
switch msg.Source {
case SourceIRC:
from = fmt.Sprintf("[IRC %s]💬 ", msg.From)
case SourceWebhook:
from = fmt.Sprintf("[Webhook %s]📢 ", msg.From)
default:
from = fmt.Sprintf("[❓ %s] ", msg.From)
}
text := from + msg.Text
b.conn.Privmsg(msg.Target, text)
slog.Debug("IRC bot posted message", "target", msg.Target, "text", text)
}