-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
437 lines (386 loc) · 11.4 KB
/
main.go
File metadata and controls
437 lines (386 loc) · 11.4 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
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"marmithon/command"
"marmithon/config"
"marmithon/identd"
"marmithon/metrics"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
hbot "github.com/whyrusleeping/hellabot"
"golang.org/x/net/proxy"
log15 "gopkg.in/inconshreveable/log15.v2"
)
// Flags for passing arguments to the program
var configFile = flag.String("config", "production.toml", "path to config file")
// core holds the command environment (bot connection and db)
var core *command.Core
// cmdList holds our command list, which tells the bot what to respond to.
var cmdList *command.List
// CommandTrigger passes all incoming messages to the commandList parser.
var CommandTrigger = hbot.Trigger{
Condition: func(bot *hbot.Bot, m *hbot.Message) bool {
return m.Command == "PRIVMSG"
},
Action: func(bot *hbot.Bot, m *hbot.Message) bool {
if m := metrics.Get(); m != nil {
m.IncMessagesReceived()
}
cmdList.Process(bot, m)
return false
},
}
// MetricsTrigger tracks all messages for metrics
var MetricsTrigger = hbot.Trigger{
Condition: func(bot *hbot.Bot, m *hbot.Message) bool {
return true
},
Action: func(bot *hbot.Bot, m *hbot.Message) bool {
met := metrics.Get()
if met != nil {
// Track channel joins
if m.Command == "JOIN" && m.Name == bot.Nick {
met.AddChannel(m.To)
}
// Track channel parts
if m.Command == "PART" && m.Name == bot.Nick {
met.RemoveChannel(m.To)
}
}
return false
},
}
// Main method
func main() {
flag.Parse()
if err := run(); err != nil {
log.Fatalf("Erreur fatale: %v", err)
}
}
func run() error {
conf, err := config.FromFile(*configFile)
if err != nil {
return err
}
if err := config.ValidateConfig(conf); err != nil {
return err
}
// Initialize metrics if enabled
var met *metrics.Metrics
var metricsSrv *metrics.Server
if conf.MetricsEnabled {
met = metrics.Init()
metricsSrv = metrics.NewServer(conf.MetricsPort)
if err := metricsSrv.Start(); err != nil {
return fmt.Errorf("failed to start metrics server: %w", err)
}
defer metricsSrv.Stop()
log.Printf("Metrics enabled on port %s", conf.MetricsPort)
}
// Start identd server if enabled
var identdSrv *identd.Server
if conf.IdentdEnabled {
identdSrv = identd.New(conf.IdentdPort, conf.IdentdUsername)
if err := identdSrv.Start(); err != nil {
return fmt.Errorf("failed to start identd server: %w", err)
}
defer identdSrv.Stop()
log.Printf("Identd enabled on port %s with username %s", conf.IdentdPort, conf.IdentdUsername)
}
// Determine data directory with fallback
dataDir := "/data"
if err := os.MkdirAll(dataDir, 0755); err != nil {
log.Printf("Cannot create %s directory, falling back to /tmp: %v", dataDir, err)
dataDir = "/tmp"
if err := os.MkdirAll(dataDir, 0755); err != nil {
return fmt.Errorf("erreur lors de la création du répertoire de fallback %s: %w", dataDir, err)
}
}
// Initialize the seen database
dbPath := dataDir + "/seen.db"
if err := command.InitSeenDB(dbPath); err != nil {
return fmt.Errorf("erreur lors de l'initialisation de la base seen: %w", err)
}
defer func() {
if err := command.CloseSeenDB(); err != nil {
log.Printf("Erreur lors de la fermeture de la base de données: %v", err)
}
}()
// Initialize core with config (bot will be set later)
core = &command.Core{Config: &conf}
setupCommands()
// Setup signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Run bot with reconnection logic (always enabled)
return runWithReconnect(conf, sigChan, met)
}
func createBot(conf config.Config) (*hbot.Bot, error) {
options := func(bot *hbot.Bot) {
bot.SSL = conf.SSL
if conf.ServerPassword != "" {
bot.Password = conf.ServerPassword
}
bot.Channels = conf.Channels
// Route through SOCKS5 proxy if configured
if conf.ProxyAddress != "" {
dialer, err := proxy.SOCKS5("tcp", conf.ProxyAddress, nil, proxy.Direct)
if err != nil {
log.Printf("Failed to create SOCKS5 dialer: %v (falling back to direct)", err)
return
}
bot.Dial = func(network, addr string) (net.Conn, error) {
return dialer.Dial(network, addr)
}
log.Printf("Using SOCKS5 proxy at %s", conf.ProxyAddress)
}
}
bot, err := hbot.NewBot(conf.Server, conf.Nick, options)
if err != nil {
return nil, err
}
return bot, nil
}
func createAndStartBot(conf config.Config, met *metrics.Metrics) (*hbot.Bot, error) {
bot, err := createBot(conf)
if err != nil {
return nil, err
}
// Update the bot reference in the existing core
core.Bot = bot
bot.AddTrigger(CommandTrigger)
if met != nil {
bot.AddTrigger(MetricsTrigger)
}
bot.Logger.SetHandler(log15.StdoutHandler)
if met != nil {
met.SetConnected(true)
}
return bot, nil
}
// shutdownBot performs a graceful shutdown of the IRC bot
func shutdownBot(bot *hbot.Bot, channels []string) {
if bot == nil {
return
}
// Say goodbye to all channels
for _, channel := range channels {
bot.Msg(channel, "Ah ! Je meurs !")
}
time.Sleep(500 * time.Millisecond) // Let the message send
// Send QUIT before closing to properly disconnect from IRC
bot.Send("QUIT :Bot shutting down")
time.Sleep(500 * time.Millisecond) // Give server time to process QUIT
bot.Close()
}
// discoverServer queries the healthcheck API and updates conf.Server and conf.SSL.
// Returns true if discovery succeeded, false if falling back to static config.
func discoverServer(conf *config.Config) bool {
if conf.ServerDiscoveryURL == "" {
return false
}
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(conf.ServerDiscoveryURL)
if err != nil {
log.Printf("Server discovery failed (using fallback %s): %v", conf.Server, err)
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("Server discovery returned %d (using fallback %s)", resp.StatusCode, conf.Server)
return false
}
var result struct {
Host string `json:"host"`
Port int `json:"port"`
SSL bool `json:"ssl"`
Score float64 `json:"score"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
log.Printf("Server discovery parse error (using fallback %s): %v", conf.Server, err)
return false
}
server := fmt.Sprintf("%s:%d", result.Host, result.Port)
log.Printf("Server discovery: %s (ssl=%v, score=%.1f)", server, result.SSL, result.Score)
conf.Server = server
conf.SSL = result.SSL
return true
}
func runWithReconnect(conf config.Config, sigChan chan os.Signal, met *metrics.Metrics) error {
attempts := 0
maxAttempts := conf.ReconnectMaxAttempts
baseDelay := time.Duration(conf.ReconnectDelaySeconds) * time.Second
maxDelay := 5 * time.Minute
consecutiveFailures := 0
for {
attempts++
if maxAttempts > 0 && attempts > maxAttempts {
return fmt.Errorf("nombre maximum de tentatives de reconnexion atteint (%d)", maxAttempts)
}
if attempts > 1 {
if met != nil {
met.IncReconnects()
met.SetConnected(false)
}
// Exponential backoff: baseDelay * 2^(failures-1), capped at maxDelay
delay := baseDelay
for i := 1; i < consecutiveFailures; i++ {
delay *= 2
if delay > maxDelay {
delay = maxDelay
break
}
}
log.Printf("Tentative de reconnexion %d dans %v (échecs consécutifs: %d)...", attempts, delay, consecutiveFailures)
time.Sleep(delay)
}
// Try server discovery before each connection attempt
discoverServer(&conf)
connectTime := time.Now()
bot, err := createAndStartBot(conf, met)
if err != nil {
log.Printf("Erreur de création du bot: %v", err)
consecutiveFailures++
continue
}
log.Printf("Démarrage du bot (tentative %d)...", attempts)
// Run bot in a goroutine and track when it exits
botDone := make(chan struct{})
go func() {
bot.Run()
close(botDone)
if met != nil {
met.SetConnected(false)
}
}()
// Send periodic IRC PINGs to keep VPN NAT mappings alive.
// Start as soon as registration completes so the connection stays
// alive through the SOCKS proxy / WireGuard tunnel before channel
// JOIN responses arrive. We use 002 (RPL_YOURHOST) because
// hellabot's built-in joinChannels handler consumes 001 before
// our trigger can see it.
pingStop := make(chan struct{})
pingReady := make(chan struct{})
bot.AddTrigger(hbot.Trigger{
Condition: func(bot *hbot.Bot, m *hbot.Message) bool {
return m.Command == "002" // RPL_YOURHOST
},
Action: func(bot *hbot.Bot, m *hbot.Message) bool {
select {
case <-pingReady:
// already signaled
default:
close(pingReady)
}
return false
},
})
go func() {
select {
case <-pingReady:
case <-pingStop:
return
}
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
bot.Send("PING :keepalive")
case <-pingStop:
return
}
}
}()
// Wait for either bot exit or shutdown signal
select {
case <-botDone:
close(pingStop)
uptime := time.Since(connectTime)
log.Printf("Connexion perdue après %v, nettoyage et tentative de reconnexion...", uptime)
bot.Close()
// If the connection lasted less than 30s, it was likely rejected
// (e.g. "Too many host connections") — count as a failure for backoff.
// If it stayed up longer, the server accepted us and something else
// happened — reset the backoff.
if uptime < 30*time.Second {
consecutiveFailures++
} else {
consecutiveFailures = 0
}
continue
case <-sigChan:
close(pingStop)
log.Println("Signal d'arrêt reçu, fermeture...")
shutdownBot(bot, conf.Channels)
// Wait a bit for clean shutdown
select {
case <-botDone:
case <-time.After(5 * time.Second):
}
return nil
}
}
}
func setupCommands() {
cmdList = &command.List{
Prefix: "!",
Commands: make(map[string]command.Command),
TitlerURL: core.Config.TitlerURL,
}
cmdList.AddCommand(command.Command{
Name: "cve",
Description: "Récupère des informations sur une CVE à partir de http://cve.circl.lu/",
Usage: "!cve CVE-2017-7494",
Run: core.GetCVE,
})
cmdList.AddCommand(command.Command{
Name: "convert",
Description: "Effectue une conversion d'une mesure d'une unité à une autre",
Usage: "!convert 400 ft m, !convert pour la liste des unités connues",
Run: core.ConvertUnits,
})
cmdList.AddCommand(command.Command{
Name: "version",
Description: "Affiche la version du bot",
Usage: "!version",
Run: core.ShowVersion,
})
cmdList.AddCommand(command.Command{
Name: "seen",
Description: "Indique quand un utilisateur a été vu pour la dernière fois",
Usage: "!seen <pseudo>",
Run: core.Seen,
})
cmdList.AddCommand(command.Command{
Name: "icao",
Description: "Trouve un aéroport par nom avec code pays optionnel",
Usage: "!icao lille FR",
Run: core.SearchForOACI,
})
cmdList.AddCommand(command.Command{
Name: "distance",
Description: "Calcule la distance entre deux aéroports en codes ICAO",
Usage: "!distance LFLL EGLL",
Run: core.CalculateDistance,
})
cmdList.AddCommand(command.Command{
Name: "time",
Description: "Affiche l'heure locale d'un aéroport par code ICAO",
Usage: "!time LFPG",
Run: core.GetAirportTime,
})
cmdList.AddCommand(command.Command{
Name: "helpircnet",
Description: "Affiche les 3 meilleurs serveurs IRCnet selon le healthcheck",
Usage: "!helpircnet",
Run: core.HelpIRCNet,
})
}