-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
625 lines (496 loc) · 13.8 KB
/
main.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
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package main
import (
"errors"
"io"
"net"
"net/rpc"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"wwfc/api"
"wwfc/common"
"wwfc/gamestats"
"wwfc/gpcm"
"wwfc/gpsp"
"wwfc/logging"
"wwfc/nas"
"wwfc/natneg"
"wwfc/qr2"
"wwfc/race"
"wwfc/sake"
"wwfc/serverbrowser"
"github.com/logrusorgru/aurora/v3"
)
var (
config = common.GetConfig()
)
func main() {
logging.SetLevel(*config.LogLevel)
args := os.Args[1:]
// Separate frontend and backend into two separate processes.
// This is to allow restarting the backend without closing all connections.
noSignal := false
noReload := false
if len(args) > 1 {
for _, arg := range args[1:] {
switch arg {
case "--nosignal":
noSignal = true
case "--noreload":
noReload = true
}
}
}
// Start the backend instead of the frontend if the first argument is "backend"
if len(args) > 0 && args[0] == "backend" {
backendMain(noSignal, noReload)
} else {
frontendMain(noSignal, len(args) > 0 && args[0] == "frontend")
}
}
type RPCPacket struct {
Server string
Index uint64
Address string
Data []byte
}
// backendMain starts all the servers and creates an RPC server to communicate with the frontend
func backendMain(noSignal, noReload bool) {
sigExit := make(chan os.Signal, 1)
signal.Notify(sigExit, syscall.SIGINT, syscall.SIGTERM)
if err := logging.SetOutput(config.LogOutput); err != nil {
logging.Error("BACKEND", err)
}
rpc.Register(&RPCPacket{})
address := config.BackendAddress
l, err := net.Listen("tcp", address)
if err != nil {
logging.Error("BACKEND", "Failed to listen on", aurora.BrightCyan(address))
os.Exit(1)
}
common.ConnectFrontend()
uuid := ""
if !noReload {
uuid = loadUuidFile()
}
reload, err := common.VerifyState(uuid)
if err != nil {
panic(err)
}
wg := &sync.WaitGroup{}
actions := []func(bool){nas.StartServer, gpcm.StartServer, qr2.StartServer, gpsp.StartServer, serverbrowser.StartServer, race.StartServer, sake.StartServer, natneg.StartServer, api.StartServer, gamestats.StartServer}
wg.Add(len(actions))
for _, action := range actions {
go func(ac func(bool)) {
defer wg.Done()
ac(reload)
}(action)
}
// Wait for all servers to start
wg.Wait()
go func() {
for {
conn, err := l.Accept()
if err != nil {
logging.Error("BACKEND", "Failed to accept connection on", aurora.BrightCyan(address))
continue
}
go rpc.ServeConn(conn)
}
}()
logging.Notice("BACKEND", "Listening on", aurora.BrightCyan(address))
common.Ready()
// Wait for a signal to shutdown
<-sigExit
if noSignal {
select {}
}
stateUuid, err := common.Shutdown()
if err != nil {
panic(err)
}
(&RPCPacket{}).Shutdown(stateUuid, &struct{}{})
}
func loadUuidFile() string {
stateFile, err := os.Open("state/uuid.txt")
if err != nil {
return ""
}
defer stateFile.Close()
uuid, err := io.ReadAll(stateFile)
if err != nil {
logging.Error("BACKEND", "Failed to read state file:", err)
return ""
}
return string(uuid)
}
// RPCPacket.NewConnection is called by the frontend to notify the backend of a new connection
func (r *RPCPacket) NewConnection(args RPCPacket, _ *struct{}) error {
switch args.Server {
case "serverbrowser":
serverbrowser.NewConnection(args.Index, args.Address)
case "gpcm":
gpcm.NewConnection(args.Index, args.Address)
case "gpsp":
gpsp.NewConnection(args.Index, args.Address)
case "gamestats":
gamestats.NewConnection(args.Index, args.Address)
}
return nil
}
// RPCPacket.HandlePacket is called by the frontend to forward a packet to the backend
func (r *RPCPacket) HandlePacket(args RPCPacket, _ *struct{}) error {
switch args.Server {
case "serverbrowser":
serverbrowser.HandlePacket(args.Index, args.Data, args.Address)
case "gpcm":
gpcm.HandlePacket(args.Index, args.Data)
case "gpsp":
gpsp.HandlePacket(args.Index, args.Data)
case "gamestats":
gamestats.HandlePacket(args.Index, args.Data)
}
return nil
}
// RPCPacket.closeConnection is called by the frontend to notify the backend of a closed connection
func (r *RPCPacket) CloseConnection(args RPCPacket, _ *struct{}) error {
switch args.Server {
case "serverbrowser":
serverbrowser.CloseConnection(args.Index)
case "gpcm":
gpcm.CloseConnection(args.Index)
case "gpsp":
gpsp.CloseConnection(args.Index)
case "gamestats":
gamestats.CloseConnection(args.Index)
}
return nil
}
// RPCPacket.Shutdown is called by the frontend to shutdown the backend
func (r *RPCPacket) Shutdown(stateUuid string, _ *struct{}) error {
if stateUuid == "" {
os.Exit(0)
return nil
}
wg := &sync.WaitGroup{}
actions := []func(){nas.Shutdown, gpcm.Shutdown, qr2.Shutdown, gpsp.Shutdown, serverbrowser.Shutdown, race.Shutdown, sake.Shutdown, natneg.Shutdown, api.Shutdown, gamestats.Shutdown}
wg.Add(len(actions))
for _, action := range actions {
go func(ac func()) {
defer wg.Done()
ac()
}(action)
}
wg.Wait()
stateFile, err := os.OpenFile("state/uuid.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
panic(err)
}
_, err = stateFile.WriteString(stateUuid)
if err != nil {
panic(err)
}
err = stateFile.Close()
if err != nil {
panic(err)
}
os.Exit(0)
return nil
}
type serverInfo struct {
rpcName string
protocol string
port int
}
type RPCFrontendPacket struct {
Server string
Index uint64
Data []byte
}
var (
rpcClient *rpc.Client
// This mutex could be locked for a very long time, don't use deadlock detection
rpcMutex sync.Mutex
rpcBusyCount sync.WaitGroup
backendReady = make(chan struct{})
frontendUuid string
connections = map[string]map[uint64]*net.Conn{}
integrated = false
)
// frontendMain starts the backend process and communicates with it using RPC
func frontendMain(noSignal, noBackend bool) {
integrated = !noBackend
sigExit := make(chan os.Signal, 1)
signal.Notify(sigExit, syscall.SIGINT, syscall.SIGTERM)
// Don't allow the frontend to output to a file (there's no reason to)
logOutput := config.LogOutput
if logOutput == "StdOutAndFile" {
logOutput = "StdOut"
}
if err := logging.SetOutput(logOutput); err != nil {
logging.Error("FRONTEND", err)
}
rpcMutex.Lock()
startFrontendServer()
if !noBackend {
go startBackendProcess(false, true)
} else {
go waitForBackend()
}
servers := []serverInfo{
{rpcName: "serverbrowser", protocol: "tcp", port: 28910},
{rpcName: "gpcm", protocol: "tcp", port: 29900},
{rpcName: "gpsp", protocol: "tcp", port: 29901},
{rpcName: "gamestats", protocol: "tcp", port: 29920},
}
for _, server := range servers {
connections[server.rpcName] = map[uint64]*net.Conn{}
go frontendListen(server)
}
// Wait for a signal to shutdown
<-sigExit
if noSignal {
select {}
}
if rpcClient == nil {
return
}
rpcClient.Call("RPCPacket.Shutdown", "", nil)
rpcClient.Close()
}
// startFrontendServer starts the frontend RPC server.
func startFrontendServer() {
rpc.Register(&RPCFrontendPacket{})
address := config.FrontendAddress
l, err := net.Listen("tcp", address)
if err != nil {
logging.Error("FRONTEND", "Failed to listen on", aurora.BrightCyan(address))
os.Exit(1)
}
logging.Notice("FRONTEND", "Listening on", aurora.BrightCyan(address))
go func() {
for {
conn, err := l.Accept()
if err != nil {
logging.Error("FRONTEND", "Failed to accept connection on", aurora.BrightCyan(address))
continue
}
go rpc.ServeConn(conn)
}
}()
}
// startBackendProcess starts the backend process and (optionally) waits for the RPC server to start.
// If wait is true, expects the RPC mutex to be locked.
func startBackendProcess(reload bool, wait bool) {
exe, err := os.Executable()
if err != nil {
logging.Error("FRONTEND", "Failed to get executable path:", err)
os.Exit(1)
}
logging.Info("FRONTEND", "Running from", aurora.BrightCyan(exe))
var cmd *exec.Cmd
if reload {
cmd = exec.Command(exe, "backend", "--nosignal")
} else {
cmd = exec.Command(exe, "backend", "--noreload", "--nosignal")
}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
logging.Error("FRONTEND", "Failed to start backend process:", err)
os.Exit(1)
}
if wait {
waitForBackend()
}
}
// waitForBackend waits for the backend to start.
// Expects the RPC mutex to be locked.
func waitForBackend() {
<-backendReady
backendReady = make(chan struct{})
for {
client, err := rpc.Dial("tcp", config.FrontendBackendAddress)
if err == nil {
rpcClient = client
rpcMutex.Unlock()
logging.Notice("FRONTEND", "Connected to backend")
return
}
<-time.After(50 * time.Millisecond)
}
}
// frontendListen listens on the specified port and forwards each packet to the backend
func frontendListen(server serverInfo) {
address := *config.GameSpyAddress + ":" + strconv.Itoa(server.port)
l, err := net.Listen(server.protocol, address)
if err != nil {
logging.Error("FRONTEND", "Failed to listen on", aurora.BrightCyan(address))
return
}
logging.Notice("FRONTEND", "Listening on", aurora.BrightCyan(address), "for", aurora.BrightCyan(server.rpcName))
// Increment by 1 for each connection, never decrement. Unlikely to overflow but it doesn't matter if it does.
count := uint64(0)
for {
conn, err := l.Accept()
if err != nil {
logging.Error("FRONTEND", "Failed to accept connection on", aurora.BrightCyan(address))
continue
}
if server.protocol == "tcp" {
err := conn.(*net.TCPConn).SetKeepAlive(true)
if err != nil {
logging.Warn("FRONTEND", "Unable to set keepalive", err.Error())
}
}
count++
go handleConnection(server, conn, count)
}
}
// handleConnection forwards packets between the frontend and backend
func handleConnection(server serverInfo, conn net.Conn, index uint64) {
defer conn.Close()
rpcMutex.Lock()
rpcBusyCount.Add(1)
pConn := &conn
connections[server.rpcName][index] = pConn
rpcMutex.Unlock()
err := rpcClient.Call("RPCPacket.NewConnection", RPCPacket{Server: server.rpcName, Index: index, Address: conn.RemoteAddr().String(), Data: []byte{}}, nil)
rpcBusyCount.Done()
if err != nil {
logging.Error("FRONTEND", "Failed to forward new connection to backend:", err)
rpcMutex.Lock()
delete(connections[server.rpcName], index)
rpcMutex.Unlock()
return
}
for {
buffer := make([]byte, 1024)
n, err := conn.Read(buffer)
if err != nil {
break
}
if n == 0 {
continue
}
rpcMutex.Lock()
rpcBusyCount.Add(1)
rpcMutex.Unlock()
// Forward the packet to the backend
err = rpcClient.Call("RPCPacket.HandlePacket", RPCPacket{Server: server.rpcName, Index: index, Address: conn.RemoteAddr().String(), Data: buffer[:n]}, nil)
rpcBusyCount.Done()
if err != nil {
logging.Error("FRONTEND", "Failed to forward packet to backend:", err)
if err == rpc.ErrShutdown {
os.Exit(1)
}
break
}
}
rpcMutex.Lock()
if connections[server.rpcName][index] != pConn {
rpcMutex.Unlock()
return
}
rpcBusyCount.Add(1)
delete(connections[server.rpcName], index)
rpcMutex.Unlock()
err = rpcClient.Call("RPCPacket.CloseConnection", RPCPacket{Server: server.rpcName, Index: index, Address: conn.RemoteAddr().String(), Data: []byte{}}, nil)
rpcBusyCount.Done()
if err != nil {
logging.Error("FRONTEND", "Failed to forward close connection to backend:", err)
if err == rpc.ErrShutdown {
os.Exit(1)
}
}
}
var (
ErrBadIndex = errors.New("incorrect connection index")
ErrorBusy = errors.New("backend is busy")
)
// RPCFrontendPacket.SendPacket is called by the backend to send a packet to a connection
func (r *RPCFrontendPacket) SendPacket(args RPCFrontendPacket, _ *struct{}) error {
rpcMutex.Lock()
defer rpcMutex.Unlock()
conn := connections[args.Server][args.Index]
if conn == nil {
return ErrBadIndex
}
_, err := (*conn).Write(args.Data)
return err
}
// RPCFrontendPacket.CloseConnection is called by the backend to close a connection
func (r *RPCFrontendPacket) CloseConnection(args RPCFrontendPacket, _ *struct{}) error {
rpcMutex.Lock()
defer rpcMutex.Unlock()
conn := connections[args.Server][args.Index]
if conn == nil {
return ErrBadIndex
}
return (*conn).Close()
}
// RPCFrontendPacket.ReloadBackend is called by an external program to reload the backend
func (r *RPCFrontendPacket) ReloadBackend(_ struct{}, _ *struct{}) error {
var stateUid string
r.ShutdownBackend(struct{}{}, &stateUid)
err := rpcClient.Call("RPCPacket.Shutdown", stateUid, nil)
if err != nil && !strings.Contains(err.Error(), "An existing connection was forcibly closed by the remote host.") {
logging.Error("FRONTEND", "Failed to reload backend:", err)
}
err = rpcClient.Close()
if err != nil {
logging.Error("FRONTEND", "Failed to close RPC client:", err)
}
// Unlocks the mutex locked by ShutdownBackend
startBackendProcess(true, true)
return nil
}
// RPCFrontendPacket.ShutdownBackend is called by the backend to prepare for shutdown
func (r *RPCFrontendPacket) ShutdownBackend(_ struct{}, uuid *string) error {
logging.Notice("FRONTEND", "Shutting down backend")
// Lock indefinitely
rpcMutex.Lock()
rpcBusyCount.Wait()
if !integrated {
go waitForBackend()
frontendUuid = common.RandomString(32)
*uuid = frontendUuid
} else {
*uuid = ""
}
return nil
}
// RPCFrontendPacket.VerifyState is called by the backend to verify the state UUID
func (r *RPCFrontendPacket) VerifyState(uuid string, reload *bool) error {
if rpcMutex.TryLock() {
rpcMutex.Unlock()
logging.Error("FRONTEND", "Failed to verify UUID, backend is active")
*reload = false
return ErrorBusy
}
if uuid != frontendUuid {
logging.Notice("FRONTEND", "VerifyState: Resetting all connections")
// Close all connections
for _, server := range connections {
for index, conn := range server {
(*conn).Close()
delete(server, index)
}
}
*reload = false
return nil
}
*reload = uuid != ""
return nil
}
// RPCFrontendPacket.Ready is called by the backend to indicate it is ready to accept connections
func (r *RPCFrontendPacket) Ready(_ struct{}, _ *struct{}) error {
close(backendReady)
return nil
}