-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathirc_callback.go
380 lines (333 loc) · 10.2 KB
/
irc_callback.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
// Copyright (c) 2024 Jerzy Dąbrowski
// Based on original work by Thomas Jager, 2009. All rights reserved.
//
// This project is a fork of the original go-ircevent library created by Thomas Jager.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided
// that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list of conditions,
// and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions,
// and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of the original authors nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package irc
import (
"context"
"net"
"reflect"
"runtime"
"strconv"
"strings"
"time"
)
// CallbackID is a tuple type for uniquely identifying callbacks.
type CallbackID struct {
EventCode string
ID int
}
// AddCallback registers a callback to a connection and event code.
// A callback is a function which takes only an Event pointer as a parameter.
// Valid event codes are all IRC/CTCP commands and error/response codes.
// To register a callback for all events, pass "*" as the event code.
// This function returns the ID of the registered callback for later management.
func (irc *Connection) AddCallback(eventcode string, callback func(*Event)) int {
eventcode = strings.ToUpper(eventcode)
irc.eventsMutex.Lock()
defer irc.eventsMutex.Unlock()
if irc.events == nil {
irc.events = make(map[string]map[int]func(*Event))
}
if _, ok := irc.events[eventcode]; !ok {
irc.events[eventcode] = make(map[int]func(*Event))
}
id := irc.idCounter
irc.idCounter++
irc.events[eventcode][id] = callback
return id
}
// RemoveCallback removes callback i (ID) from the given event code.
// This function returns true upon success, false if any error occurs.
func (irc *Connection) RemoveCallback(eventcode string, i int) bool {
eventcode = strings.ToUpper(eventcode)
irc.eventsMutex.Lock()
defer irc.eventsMutex.Unlock()
if event, ok := irc.events[eventcode]; ok {
if _, ok := event[i]; ok {
delete(event, i)
return true
}
irc.Log.Printf("Event found, but no callback found at id %d\n", i)
return false
}
irc.Log.Println("Event not found")
return false
}
// ClearCallback removes all callbacks from a given event code.
// It returns true if the given event code is found and cleared.
func (irc *Connection) ClearCallback(eventcode string) bool {
eventcode = strings.ToUpper(eventcode)
irc.eventsMutex.Lock()
defer irc.eventsMutex.Unlock()
if _, ok := irc.events[eventcode]; ok {
irc.events[eventcode] = make(map[int]func(*Event))
return true
}
irc.Log.Println("Event not found")
return false
}
// ReplaceCallback replaces callback i (ID) associated with a given event code with a new callback function.
func (irc *Connection) ReplaceCallback(eventcode string, i int, callback func(*Event)) {
eventcode = strings.ToUpper(eventcode)
irc.eventsMutex.Lock()
defer irc.eventsMutex.Unlock()
if event, ok := irc.events[eventcode]; ok {
if _, ok := event[i]; ok {
event[i] = callback
return
}
irc.Log.Printf("Event found, but no callback found at id %d\n", i)
return
}
irc.Log.Printf("Event not found. Use AddCallback\n")
}
// RunCallbacks executes all callbacks associated with a given event.
func (irc *Connection) RunCallbacks(event *Event) {
msg := event.Message()
if event.Code == "PRIVMSG" && len(msg) > 2 && msg[0] == '\x01' {
event.Code = "CTCP" // Unknown CTCP
if i := strings.LastIndex(msg, "\x01"); i > 0 {
msg = msg[1:i]
} else {
irc.Log.Printf("Invalid CTCP Message: %s\n", strconv.Quote(msg))
return
}
switch {
case msg == "VERSION":
event.Code = "CTCP_VERSION"
case msg == "TIME":
event.Code = "CTCP_TIME"
case strings.HasPrefix(msg, "PING"):
event.Code = "CTCP_PING"
case msg == "USERINFO":
event.Code = "CTCP_USERINFO"
case msg == "CLIENTINFO":
event.Code = "CTCP_CLIENTINFO"
case strings.HasPrefix(msg, "ACTION"):
event.Code = "CTCP_ACTION"
if len(msg) > 6 {
msg = msg[7:]
} else {
msg = ""
}
}
event.Arguments[len(event.Arguments)-1] = msg
}
irc.eventsMutex.Lock()
callbacks := make(map[int]func(*Event))
if eventCallbacks, ok := irc.events[event.Code]; ok {
for id, callback := range eventCallbacks {
callbacks[id] = callback
}
}
if allCallbacks, ok := irc.events["*"]; ok {
for id, callback := range allCallbacks {
callbacks[id] = callback
}
}
irc.eventsMutex.Unlock()
if irc.VerboseCallbackHandler {
irc.Log.Printf("%v (%v) >> %#v\n", event.Code, len(callbacks), event)
}
event.Ctx = context.Background()
if irc.CallbackTimeout != 0 {
var cancel context.CancelFunc
event.Ctx, cancel = context.WithTimeout(event.Ctx, irc.CallbackTimeout)
defer cancel()
}
done := make(chan int)
for id, callback := range callbacks {
go func(id int, done chan<- int, cb func(*Event), event *Event) {
start := time.Now()
cb(event)
select {
case done <- id:
case <-event.Ctx.Done():
irc.Log.Printf("Canceled callback %s finished in %s >> %#v\n",
getFunctionName(cb),
time.Since(start),
event,
)
}
}(id, done, callback, event)
}
for len(callbacks) > 0 {
select {
case jobID := <-done:
delete(callbacks, jobID)
case <-event.Ctx.Done():
timedOutCallbacks := []string{}
for _, cb := range callbacks {
timedOutCallbacks = append(timedOutCallbacks, getFunctionName(cb))
}
irc.Log.Printf("Timeout while waiting for %d callback(s) to finish (%s)\n",
len(callbacks),
strings.Join(timedOutCallbacks, ", "),
)
return
}
}
}
func getFunctionName(f func(*Event)) string {
return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
}
// setupCallbacks sets up some initial callbacks to handle the IRC/CTCP protocol.
func (irc *Connection) setupCallbacks() {
irc.events = make(map[string]map[int]func(*Event))
// Handle PING events
irc.AddCallback("PING", func(e *Event) {
irc.SendRaw("PONG :" + e.Message())
})
// Version handler
irc.AddCallback("CTCP_VERSION", func(e *Event) {
irc.SendRawf("NOTICE %s :\x01VERSION %s\x01", e.Nick, irc.Version)
})
// Userinfo handler
irc.AddCallback("CTCP_USERINFO", func(e *Event) {
irc.SendRawf("NOTICE %s :\x01USERINFO %s\x01", e.Nick, irc.user)
})
// Clientinfo handler
irc.AddCallback("CTCP_CLIENTINFO", func(e *Event) {
irc.SendRawf("NOTICE %s :\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\x01", e.Nick)
})
// Time handler
irc.AddCallback("CTCP_TIME", func(e *Event) {
ltime := time.Now()
irc.SendRawf("NOTICE %s :\x01TIME %s\x01", e.Nick, ltime.String())
})
// Ping handler
irc.AddCallback("CTCP_PING", func(e *Event) {
irc.SendRawf("NOTICE %s :\x01%s\x01", e.Nick, e.Message())
})
// Handle nickname in use (433)
irc.AddCallback("433", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
if irc.nickcurrent == "" {
irc.nickcurrent = irc.nick
}
irc.modifyNick()
irc.SendRawf("NICK %s", irc.nickcurrent)
}
})
// Handle unavailable resource (437)
irc.AddCallback("437", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
if irc.nickcurrent == "" {
irc.nickcurrent = irc.nick
}
irc.modifyNick()
irc.SendRawf("NICK %s", irc.nickcurrent)
}
})
// Handle no nickname given (431)
irc.AddCallback("431", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
if irc.nickcurrent == "" {
irc.nickcurrent = irc.nick
}
irc.modifyNick()
irc.SendRawf("NICK %s", irc.nickcurrent)
}
})
// Handle erroneous nickname (432)
irc.AddCallback("432", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
if irc.nickcurrent == "" {
irc.nickcurrent = irc.nick
}
// Add prefix 'Err' to try a different nickname
irc.nickcurrent = "Err" + irc.nickcurrent
irc.SendRawf("NICK %s", irc.nickcurrent)
}
})
// Handle nickname collision (436)
irc.AddCallback("436", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
if irc.nickcurrent == "" {
irc.nickcurrent = irc.nick
}
irc.modifyNick()
irc.SendRawf("NICK %s", irc.nickcurrent)
}
})
// Handle restricted nickname (484)
irc.AddCallback("484", func(e *Event) {
irc.Lock()
defer irc.Unlock()
if !irc.fullyConnected {
// Keep the current nickname and do not attempt to change it further
}
})
// Handle PONG responses
irc.AddCallback("PONG", func(e *Event) {
ns, _ := strconv.ParseInt(e.Message(), 10, 64)
delta := time.Duration(time.Now().UnixNano() - ns)
if irc.Debug {
irc.Log.Printf("Lag: %.3f s\n", delta.Seconds())
}
})
// Handle NICK changes fixed
irc.AddCallback("NICK", func(e *Event) {
if e.Nick == irc.nickcurrent {
irc.Lock()
irc.nickcurrent = e.Message()
irc.nick = e.Message()
irc.Unlock()
}
})
// Set fullyConnected to true on successful connection (001)
irc.AddCallback("001", func(e *Event) {
irc.Lock()
irc.nickcurrent = e.Arguments[0]
irc.fullyConnected = true
irc.Unlock()
})
// DCC Chat support
irc.addDCCChatCallback()
}
// modifyNick modifies the current nickname to try a different one.
func (irc *Connection) modifyNick() {
if len(irc.nickcurrent) > 8 {
irc.nickcurrent = "_" + irc.nickcurrent
} else {
irc.nickcurrent = irc.nickcurrent + "_"
}
}
// DCC chat support
func (irc *Connection) addDCCChatCallback() {
irc.AddCallback("CTCP_DCC", func(e *Event) {
if len(e.Arguments) < 5 || e.Arguments[1] != "CHAT" {
return
}
nick := e.Nick
ip := net.ParseIP(e.Arguments[3])
port, _ := strconv.Atoi(e.Arguments[4])
go irc.handleIncomingDCCChat(nick, ip, port)
})
}