-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1609 lines (1438 loc) · 63.9 KB
/
main.go
File metadata and controls
1609 lines (1438 loc) · 63.9 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
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net"
"net/http"
"os"
"strconv" // <-- Added missing import
"strings"
"sync"
"time"
"unicode"
"regexp"
"github.com/oschwald/geoip2-golang"
"sort"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
"github.com/joho/godotenv"
_ "github.com/mattn/go-sqlite3"
"golang.org/x/time/rate"
)
// ---------- Region codes ----------
const (
RegionNAE = "[NAEst]" // North America – East
RegionNAC = "[NACen]" // North America – Central
RegionNAW = "[NAWst]" // North America – West
RegionCAM = "[CAmer]" // Central America
RegionSAM = "[SAmer]" // South America
RegionEWE = "[EUWst]" // Europe – West
RegionEEE = "[EUEst]" // Europe – East
RegionRUS = "[Rusia]" // Russia
RegionASE = "[AsiaE]" // Asia – East
RegionASS = "[AsiaS]" // Asia – South
RegionAEA = "[AsSEA]" // Asia – Southeast
RegionOCE = "[Ocean]" // Oceania
RegionMEA = "[MEast]" // Middle East
RegionAFR = "[Afric]" // Africa
RegionLOC = "[LOCAL]" // Private / loopback IPs detected by master server
RegionUNK = "[UNKNW]" // Unknown or GeoIP failed
)
// longitude cut-offs (refined)
const (
naWestCut = -105.0 // < −105 → West
naCentralCut = -90.0 // −105..−90 → Central ; ≥ −90 → East
euWestCut = 20.0 // < 20 E → EU-West
)
// pre-compiled once for prefix-strip: [[XXXXX]]␠
var stripPrefix = regexp.MustCompile(`^\[[A-Z]{2,5}\]\s`)
// ServerEntry holds info about a registered game server.
type ServerEntry struct {
HostName string `json:"host_name"`
MapName string `json:"map_name"`
GameMode string `json:"game_mode"`
MaxPlayers int `json:"max_players"`
Description string `json:"description"`
Playlist string `json:"playlist"`
PlaylistDisplayName string `json:"playlist_display_name"`
HasPassword bool `json:"has_password"`
TotalPlayers int `json:"total_players"`
HasAuth bool `json:"has_auth"`
IP string `json:"ip"`
Version string `json:"version"` // Added Version field
Port int `json:"port"`
Players []PlayerInfo `json:"players"`
LastUpdated time.Time `json:"-"` // Exclude from JSON
Validated bool `json:"validated"`
}
// PlayerInfo represents a player on the game server.
type PlayerInfo struct {
Name string `json:"name"`
Gen int `json:"gen"`
Lvl int `json:"lvl"`
Team int `json:"team"`
}
// DiscordAuthPayload is used for Discord authentication endpoints (primarily bot sync).
type DiscordAuthPayload struct {
DiscordId string `json:"discord_id"`
Username string `json:"username"` // Discord username (e.g., "pomelo_name")
DisplayName string `json:"display_name"` // Global display name (e.g., "Pomelo")
PomeloName string `json:"pomelo_name"` // Deprecated username format (e.g., "Pomelo#1234") - Use Username/DisplayName
}
// isValidMapName returns true if the given map name is valid.
func isValidMapName(name string) bool {
// Allow only lowercase letters, numbers, and underscores
for _, c := range name {
if !unicode.IsLower(c) && !unicode.IsDigit(c) && c != '_' {
return false
}
}
return true
}
// isValidGameMode returns true if the given game mode is valid.
func isValidGameMode(mode string) bool {
// Allow only lowercase letters, numbers, and underscores
for _, c := range mode {
if !unicode.IsLower(c) && !unicode.IsDigit(c) && c != '_' {
return false
}
}
return true
}
// MasterServer holds the in–memory state of registered servers and related data.
type MasterServer struct {
servers map[string]*ServerEntry // key: "ip:port"
challenges map[string]time.Time // last challenge initiation time per key
lastHeartbeats map[string]time.Time // last heartbeat time per key (redundant with ServerEntry?) - Let's rely on ServerEntry.LastUpdated
db *sql.DB
geoip *geoip2.Reader
// Per-IP rate limiters (keyed by client IP)
limiters map[string]*rate.Limiter
limiterMu sync.Mutex
serversMu sync.RWMutex
challengeMu sync.Mutex
}
// determineRegionCode maps a GeoIP “City” record to one of the 5-letter codes.
func determineRegionCode(rec *geoip2.City) string {
// Check if rec is nil or if Continent data exists via Code
// Fix: rec.Continent is a struct, cannot compare to nil. Check Code field.
if rec == nil || rec.Continent.Code == "" { return RegionUNK }
cc := rec.Country.IsoCode
return "["+cc+"]"; // just put the country code in the bag wagie
/*
// Fix: Location is a non-pointer struct. Check if its data is meaningful, not if the struct itself is nil.
// Declare variables before checking for location data.
var lon float64
// Check if Location data is meaningful (e.g., non-zero lat/lon)
hasLoc := rec.Location.Latitude != 0 || rec.Location.Longitude != 0
if hasLoc {
//lon = rec.Location.Longitude
} else {
// If no location data, lon remains its zero value (0.0).
// The code below relies on the `!hasLoc` checks within the NA/EU cases
// to default the region if location data is missing. This is fine.
}
// country overrides (fast path) - these don't typically depend on longitude
if cc == "RU" { return RegionRUS }
if _, ok := map[string]struct{}{
"BZ":{}, "CR":{}, "SV":{}, "GT":{}, "HN":{}, "NI":{}, "PA":{}, "MX":{},
}[cc]; ok { return RegionCAM }
if _, ok := map[string]struct{}{
"AE":{}, "BH":{}, "CY":{}, "EG":{}, "IR":{}, "IQ":{}, "IL":{}, "JO":{},
"KW":{}, "LB":{}, "OM":{}, "PS":{}, "QA":{}, "SA":{}, "SY":{}, "TR":{}, "YE":{},
}[cc]; ok { return RegionMEA }
if _, ok := map[string]struct{}{
"AF":{}, "BD":{}, "BT":{}, "IN":{}, "MV":{}, "NP":{}, "PK":{}, "LK":{},
}[cc]; ok { return RegionASS }
if _, ok := map[string]struct{}{
"BN":{}, "KH":{}, "ID":{}, "LA":{}, "MY":{}, "MM":{}, "PH":{}, "SG":{},
"TH":{}, "TL":{}, "VN":{},
}[cc]; ok { return RegionAEA }
switch rec.Continent.Code {
case "NA":
if !hasLoc { return RegionNAE } // Default NA region if no detailed location
switch { // Use the calculated 'lon' here
case lon < naWestCut: return RegionNAW
case lon < naCentralCut: return RegionNAC
default: return RegionNAE
}
case "EU":
if !hasLoc { return RegionEWE } // Default EU region if no detailed location
if lon < euWestCut { return RegionEWE } // Use the calculated 'lon' here
return RegionEEE
case "AS":
return RegionASE // defaults; sub-regions handled earlier
case "SA":
return RegionSAM
case "AF":
return RegionAFR
case "OC":
return RegionOCE
default:
return RegionUNK
}*/
}
// getLimiter returns a rate limiter for the given IP (creating one if needed).
func (ms *MasterServer) getLimiter(ip string) *rate.Limiter {
ms.limiterMu.Lock()
defer ms.limiterMu.Unlock()
limiter, exists := ms.limiters[ip]
if !exists {
// Allow up to 5 requests per second with burst capacity 5.
limiter = rate.NewLimiter(rate.Every(200*time.Millisecond), 5)
ms.limiters[ip] = limiter
}
return limiter
}
// rateLimitMiddleware applies per–IP rate limiting.
func (ms *MasterServer) rateLimitMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Use the IP resolved by Gin after trusted proxies are configured.
clientIP := c.ClientIP()
limiter := ms.getLimiter(clientIP)
if !limiter.Allow() {
log.Printf("Rate limited IP: %s", clientIP) // Log rate limiting
c.AbortWithStatus(http.StatusTooManyRequests)
return
}
c.Next()
}
}
// HandlePerServerToken issues a JWT to a server using its Discord–based credentials (permanent token).
// Endpoint: POST /server-token
// Authentication: Bearer <permanent_master_auth_token>
// Body: { "ip": "server_public_ip" }
// Response: { "token": "short_lived_server_auth_token", "discord_id": "...", "username": "...", "pomelo_name": "..." }
func (ms *MasterServer) HandlePerServerToken(c *gin.Context) {
// Get permanent token from Authorization header.
var permanentAuthToken string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(auth, "Bearer ") {
permanentAuthToken = strings.TrimPrefix(auth, "Bearer ")
} else {
log.Printf("Invalid authorization header from %s: %s", c.ClientIP(), auth)
c.AbortWithStatus(http.StatusBadRequest)
return
}
}
// Get the server IP from the JSON body.
var server struct {
IP string `json:"ip"`
}
if err := c.ShouldBindJSON(&server); err != nil {
log.Printf("Invalid server IP format from %s: %v", c.ClientIP(), err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
if server.IP == "" {
log.Printf("Invalid server IP from %s: missing field 'ip'", c.ClientIP())
c.AbortWithStatus(http.StatusBadRequest)
return
}
if permanentAuthToken == "" {
log.Printf("Missing authorization header from %s", c.ClientIP())
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Lookup user info based on the permanent token.
var discordId, username, displayName, pomeloName string
// Select all fields associated with the permanent token
row := ms.db.QueryRow("SELECT discord_id, username, display_name, pomelo_name FROM discord_auth WHERE token = ?", permanentAuthToken)
if err := row.Scan(&discordId, &username, &displayName, &pomeloName); err != nil {
if err == sql.ErrNoRows {
log.Printf("Permanent master token not found or invalid from %s", c.ClientIP())
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid permanent auth token"})
} else {
log.Printf("Failed to query permanent token from database: %v", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "An error occurred"})
}
return
}
// Read the EC private key from file (used for signing short-lived server tokens).
keyPath := os.Getenv("JWT_PRIVATE_KEY_FILE")
if keyPath == "" {
keyPath = "new_key.pem" // Default key file name
}
keyData, err := os.ReadFile(keyPath)
if err != nil {
// This is a critical server configuration error
log.Fatalf("Error reading EC private key file %q: %v", keyPath, err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error (missing key)"})
return
}
// Parse the EC private key.
privateKey, err := jwt.ParseECPrivateKeyFromPEM(keyData)
if err != nil {
// This is a critical server configuration error
log.Fatalf("Error parsing EC private key from %q: %v", keyPath, err)
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error (bad key)"})
return
}
// Create a short-lived server auth token.
// Claims structure seen in C++: "di", "dn", "p", "e", "s"
tokenClaims := jwt.MapClaims{
"di": discordId, // Discord User ID
"dn": displayName, // Discord Global Display Name
"p": pomeloName, // Discord Old Username format (if needed by client)
"s": server.IP, // Server's public IP provided in the request body
"e": time.Now().Add(5 * time.Minute).Unix(), // Expiration (5 minutes)
}
jwtToken := jwt.NewWithClaims(jwt.SigningMethodES256, tokenClaims)
serverAuthToken, err := jwtToken.SignedString(privateKey)
if err != nil {
log.Printf("Failed to create EC JWT token for server %s from user %s: %v", server.IP, discordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Return the short-lived server auth token and associated user info.
c.JSON(http.StatusOK, gin.H{
"token": serverAuthToken, // The short-lived token
"discord_id": discordId,
"username": displayName, // Return display_name as "username" for compatibility with C++? Or username from DB? C++ uses "dn" claim which is displayName. Let's use displayName.
"display_name": displayName, // Explicitly add display_name
"pomelo_name": pomeloName,
})
}
// HandleDiscordAuth handles the Discord OAuth2 code exchange flow from the client.
// Endpoint: GET /discord-auth?code=...
// Authentication: None initially, uses code from Discord redirect
// Response: { "token": "permanent_master_auth_token", "access_token": "...", "discord_id": "...", "username": "...", "pomelo_name": "..." }
func (ms *MasterServer) HandleDiscordAuth(c *gin.Context) {
token, exists := c.GetQuery("token")
if !exists || token == "" {
log.Printf("Invalid Discord auth code from %s: missing 'code' query parameter", c.ClientIP())
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Discord auth code"})
return
}
log.Printf("Discord auth code received: %s (from %s)", token, c.ClientIP())
// Get user info from Discord using the access token.
req, err := http.NewRequest("GET", "https://discord.com/api/v10/users/@me", nil)
if err != nil {
log.Printf("Failed to create user info request: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user info request"})
return
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("Failed to get user info: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error getting user info"})
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("Unexpected status code when fetching user info: %d", resp.StatusCode)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error fetching user info"})
return
}
var userResponse struct {
ID string `json:"id"`
Username string `json:"username"` // New username (pomelo_name replacement)
GlobalName string `json:"global_name"` // Global display name
Discriminator string `json:"discriminator"` // Old discriminator (may be "0")
Avatar string `json:"avatar"`
// Add other fields if needed
}
if err := json.NewDecoder(resp.Body).Decode(&userResponse); err != nil {
log.Printf("Failed to decode user response: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Determine display name and pomelo name (for backward compatibility)
displayName := userResponse.GlobalName // Discord's Global Name
if displayName == "" {
displayName = userResponse.Username // Fallback to new username
}
// Simulate old pomelo_name#discriminator format if needed
pomeloName := userResponse.Username // Start with new username
if userResponse.Discriminator != "0" && userResponse.Discriminator != "" {
pomeloName = fmt.Sprintf("%s#%s", userResponse.Username, userResponse.Discriminator)
}
// Check if record already exists for this discord_id.
var existingToken string
var existingUsername, existingDisplayName, existingPomeloName string
err = ms.db.QueryRow("SELECT token, username, display_name, pomelo_name FROM discord_auth WHERE discord_id = ?", userResponse.ID).Scan(&existingToken, &existingUsername, &existingDisplayName, &existingPomeloName)
if err == nil {
// Record exists. Update username, display_name, and pomelo_name if they changed.
// This also ensures the latest names from Discord are in our DB.
_, err = ms.db.Exec("UPDATE discord_auth SET username = ?, display_name = ?, pomelo_name = ? WHERE discord_id = ?",
userResponse.Username, displayName, pomeloName, userResponse.ID)
if err != nil {
log.Printf("Failed to update discord_auth for existing user %s (%s) during auth: %v", userResponse.ID, userResponse.Username, err)
// Log error but proceed, client still gets the existing token
} else {
log.Printf("Updated discord_auth for existing user %s (%s) during auth.", userResponse.ID, userResponse.Username)
}
// Return the existing token and the latest user info from DB/Discord
c.JSON(http.StatusOK, gin.H{
"token": existingToken, // Return existing permanent token
"discord_id": userResponse.ID,
"username": userResponse.Username, // Return Discord's new username
"display_name": displayName, // Return determined display name
"pomelo_name": pomeloName, // Return determined pomelo name (old format)
})
return
} else if err != sql.ErrNoRows {
log.Printf("Database error when querying discord_auth for %s (%s): %v", userResponse.ID, userResponse.Username, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Database error during login"})
return
}
// If err is sql.ErrNoRows, the user is not in our `discord_auth` table.
// Create a new entry and a new permanent token (HS256).
log.Printf("Registering new user %s (%s) via OAuth flow.", userResponse.ID, userResponse.Username)
jwtSecret := os.Getenv("JWT_DISCORD_SECRET")
if jwtSecret == "" {
log.Fatalf("JWT_DISCORD_SECRET environment variable not set") // Critical error
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error"})
return
}
// Create a new permanent master auth token (signed with HS256).
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"discord_id": userResponse.ID,
"username": userResponse.Username,
"display_name": displayName,
"pomelo_name": pomeloName,
// Permanent token doesn't expire according to C++ comment
})
permanentToken, err := tkn.SignedString([]byte(jwtSecret))
if err != nil {
log.Printf("Failed to create permanent master auth token for %s (%s): %v", userResponse.ID, userResponse.Username, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Insert the new user record into the database.
_, err = ms.db.Exec("INSERT INTO discord_auth (discord_id, username, token, display_name, pomelo_name) VALUES (?, ?, ?, ?, ?)",
userResponse.ID, userResponse.Username, permanentToken, displayName, pomeloName)
if err != nil {
log.Printf("Failed to store new user record in database for %s (%s): %v", userResponse.ID, userResponse.Username, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
log.Printf("Successfully registered and issued token for user %s (%s).", userResponse.ID, userResponse.Username)
// Return the new permanent token and Discord access token.
c.JSON(http.StatusOK, gin.H{
"token": permanentToken, // The new permanent master token
"discord_id": userResponse.ID,
"username": userResponse.Username, // Return Discord's new username
"display_name": displayName, // Return determined display name
"pomelo_name": pomeloName, // Return determined pomelo name (old format)
})
}
// HandleUser returns user info for a given permanent master auth token.
// Endpoint: GET /user
// Authentication: Bearer <permanent_master_auth_token>
// Response: { "discord_id": "...", "username": "...", "display_name": "...", "pomelo_name": "..." }
func (ms *MasterServer) HandleUser(c *gin.Context) {
var token string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(auth, "Bearer ") {
token = strings.TrimPrefix(auth, "Bearer ")
} else {
log.Printf("Invalid authorization header from %s: %s", c.ClientIP(), auth)
c.AbortWithStatus(http.StatusBadRequest)
return
}
}
if token == "" {
log.Printf("Missing authorization header from %s", c.ClientIP())
c.AbortWithStatus(http.StatusUnauthorized)
return
}
var discordId, username, displayName, pomeloName string
row := ms.db.QueryRow("SELECT discord_id, username, display_name, pomelo_name FROM discord_auth WHERE token = ?", token)
if err := row.Scan(&discordId, &username, &displayName, &pomeloName); err != nil {
if err == sql.ErrNoRows {
log.Printf("Permanent master token not found: %s (from %s)", token, c.ClientIP())
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
} else {
log.Printf("Database error when scanning user info for token %s (from %s): %v", token, c.ClientIP(), err)
c.AbortWithStatus(http.StatusInternalServerError)
}
return
}
c.JSON(http.StatusOK, gin.H{
"discord_id": discordId,
"username": username, // Return Discord's new username
"display_name": displayName, // Return Global Display Name
"pomelo_name": pomeloName, // Return old username format
})
}
// HandleDiscordAuthChunk processes a batch of Discord auth payloads (from a bot).
// Endpoint: POST /discord-auth-chunk
// Authentication: Bearer <MS_TOKEN>
// Body: [ { "discord_id": "...", "username": "...", "display_name": "...", "pomelo_name": "..." }, ... ]
// Response: { "status": "processed" } or error
func (ms *MasterServer) HandleDiscordAuthChunk(c *gin.Context) {
var payload []DiscordAuthPayload
if err := c.ShouldBindJSON(&payload); err != nil {
log.Printf("Invalid Discord auth payload from %s: %v", c.ClientIP(), err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Check master server token.
var msToken string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(auth, "Bearer ") {
msToken = strings.TrimPrefix(auth, "Bearer ")
log.Printf("Master server token received (chunk) from %s", c.ClientIP())
} else {
log.Printf("Invalid authorization header from %s: %s", c.ClientIP(), auth)
c.AbortWithStatus(http.StatusBadRequest)
return
}
}
if msToken == "" || msToken != os.Getenv("MS_TOKEN") {
log.Printf("Unauthorized master server token from %s", c.ClientIP())
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if len(payload) == 0 {
log.Printf("Empty Discord auth payload from %s", c.ClientIP())
c.JSON(http.StatusOK, gin.H{"status": "processed"}) // Return OK for empty payload
return
}
log.Printf("Discord auth chunk payload received (%d entries) from %s", len(payload), c.ClientIP())
// Load the Discord JWT signing secret from environment (used for generating permanent tokens).
jwtSecret := os.Getenv("JWT_DISCORD_SECRET")
if jwtSecret == "" {
log.Fatalf("JWT_DISCORD_SECRET environment variable not set") // Critical error
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error"})
return
}
// Use a transaction for batch inserts/updates
tx, err := ms.db.Begin()
if err != nil {
log.Printf("Failed to start transaction: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer tx.Rollback() // Rollback on error
// Prepare statements
insertStmt, err := tx.Prepare("INSERT INTO discord_auth (discord_id, username, token, display_name, pomelo_name) VALUES (?, ?, ?, ?, ?)")
if err != nil {
log.Printf("Failed to prepare INSERT statement: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer insertStmt.Close()
// Update statement includes username, display_name, and pomelo_name
updateStmt, err := tx.Prepare("UPDATE discord_auth SET username = ?, display_name = ?, pomelo_name = ? WHERE discord_id = ?")
if err != nil {
log.Printf("Failed to prepare UPDATE statement: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer updateStmt.Close()
// Select statement only needs to check for existence
selectStmt, err := tx.Prepare("SELECT 1 FROM discord_auth WHERE discord_id = ?") // SELECT 1 is efficient
if err != nil {
log.Printf("Failed to prepare SELECT statement: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer selectStmt.Close()
processedCount := 0
for _, p := range payload {
if p.DiscordId == "" || p.Username == "" { // Username is required for registration
log.Printf("Skipping entry with missing DiscordId or Username from %s: %+v", c.ClientIP(), p)
continue // Skip this specific invalid entry, don't abort the whole batch
}
// Check if record exists.
var exists bool
err := selectStmt.QueryRow(p.DiscordId).Scan(&exists)
if err != nil && err != sql.ErrNoRows {
log.Printf("Database error querying discord_auth for %s: %v", p.DiscordId, err)
continue // Log error and continue with the next payload
}
// Fix: Declare 'token' variable outside the conditional blocks so it's in scope for line 677 (and 682).
var token string
if err == sql.ErrNoRows {
// Record does not exist, create a new one.
log.Printf("Bot sync registering new user: %s (%s)", p.DiscordId, p.Username)
// Create a new permanent master auth token (signed with HS256).
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"discord_id": p.DiscordId,
"username": p.Username,
"display_name": p.DisplayName,
"pomelo_name": p.PomeloName,
// Permanent token doesn't expire
})
// Fix: Assign to the 'token' variable declared above. This is line 677.
token, err = tkn.SignedString([]byte(jwtSecret))
if err != nil {
log.Printf("Failed to create Discord JWT token for %s: %v", p.DiscordId, err)
continue // Log error and continue, don't abort batch
}
// Fix: Use the 'token' variable. This is line 682.
_, err = insertStmt.Exec(p.DiscordId, p.Username, token, p.DisplayName, p.PomeloName)
if err != nil {
log.Printf("Failed to store Discord token in database for %s: %v", p.DiscordId, err)
continue // Log error and continue
}
} else {
// Record exists, update username, display_name, and pomelo_name.
// Bot sync provides the latest names.
_, err = updateStmt.Exec(p.Username, p.DisplayName, p.PomeloName, p.DiscordId)
if err != nil {
log.Printf("Failed to update discord_auth for %s: %v", p.DiscordId, err)
// Log error and continue processing next payload.
continue
}
// log.Printf("Bot sync updated user: %s (%s)", p.DiscordId, p.Username) // Optional: Log updates
}
// Fix: Increment processedCount for both new inserts and updates.
processedCount++
}
// Commit the transaction.
if err := tx.Commit(); err != nil {
log.Printf("Failed to commit transaction: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
log.Printf("Discord auth chunk processed %d entries successfully from %s", processedCount, c.ClientIP())
c.JSON(http.StatusOK, gin.H{"status": "processed", "count": processedCount})
}
// HandleDiscordDelete deletes a Discord auth record (from a bot).
// Endpoint: DELETE /discord-auth
// Authentication: Bearer <MS_TOKEN>
// Body: { "discord_id": "..." }
// Response: 200 or 404 or 500
func (ms *MasterServer) HandleDiscordDelete(c *gin.Context) {
var payload DiscordAuthPayload
if err := c.ShouldBindJSON(&payload); err != nil {
log.Printf("Invalid payload from %s: %v", c.ClientIP(), err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
if payload.DiscordId == "" {
log.Printf("Missing DiscordId in payload from %s", c.ClientIP())
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Check master server token.
var msToken string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(auth, "Bearer ") {
msToken = strings.TrimPrefix(auth, "Bearer ")
log.Printf("Master server token received (delete) from %s", c.ClientIP())
} else {
log.Printf("Invalid authorization header from %s: %s", c.ClientIP(), auth)
c.AbortWithStatus(http.StatusBadRequest)
return
}
}
if msToken == "" || msToken != os.Getenv("MS_TOKEN") {
log.Printf("Unauthorized master server token from %s", c.ClientIP())
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Use a transaction even for a single delete for atomicity (optional but good practice)
tx, err := ms.db.Begin()
if err != nil {
log.Printf("Failed to start delete transaction: %v", err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
defer tx.Rollback()
result, err := tx.Exec("DELETE FROM discord_auth WHERE discord_id = ?", payload.DiscordId)
if err != nil {
log.Printf("Failed to delete Discord auth record for %s (from %s): %v", payload.DiscordId, c.ClientIP(), err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
rowsAffected, err := result.RowsAffected()
if err != nil {
log.Printf("Failed to get rows affected for deletion of %s (from %s): %v", payload.DiscordId, c.ClientIP(), err)
// Log but continue, delete might have succeeded
}
if rowsAffected > 0 {
log.Printf("Deleted Discord auth record for %s (from %s).", payload.DiscordId, c.ClientIP())
if err := tx.Commit(); err != nil {
log.Printf("Failed to commit delete transaction for %s: %v", payload.DiscordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Status(http.StatusOK)
} else {
log.Printf("Attempted to delete non-existent Discord auth record for %s (from %s).", payload.DiscordId, c.ClientIP())
if err := tx.Commit(); err != nil { // Still commit even if no rows affected
log.Printf("Failed to commit delete transaction (no rows affected) for %s: %v", payload.DiscordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
c.Status(http.StatusNotFound) // Indicate it wasn't found
}
}
// HandleDiscordClientAuth processes a Discord auth payload from a client (e.g., the game client).
// This endpoint's purpose is unclear from the C++ snippets provided, but assuming it's an internal/bot endpoint for single adds/updates.
// Endpoint: POST /discord-auth (or maybe /discord-auth-single?)
// Authentication: Bearer <MS_TOKEN> (Assumption based on payload structure similar to chunk)
// Body: { "discord_id": "...", "username": "...", "display_name": "...", "pomelo_name": "..." }
// Response: { "token": "permanent_master_auth_token" } or error
// NOTE: Renaming this endpoint to /discord-auth-single might be less confusing if its purpose is single bot sync.
// The current path POST /discord-auth conflicts semantically with GET /discord-auth for OAuth.
// Let's assume the POST /discord-auth endpoint is intended for bot sync of a single user.
func (ms *MasterServer) HandleDiscordClientAuth(c *gin.Context) {
var payload DiscordAuthPayload
if err := c.ShouldBindJSON(&payload); err != nil {
log.Printf("Invalid Discord auth payload from %s: %v", c.ClientIP(), err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Require DiscordId and Username for any sync/add operation
if payload.DiscordId == "" || payload.Username == "" {
log.Printf("Missing DiscordId or Username in payload from %s", c.ClientIP())
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Check master server token - ASSUMPTION: This is a bot/internal endpoint
var msToken string
if auth := c.GetHeader("Authorization"); auth != "" {
if strings.HasPrefix(auth, "Bearer ") {
msToken = strings.TrimPrefix(auth, "Bearer ")
log.Printf("Master server token received (single sync) from %s", c.ClientIP())
} else {
log.Printf("Invalid authorization header from %s: %s", c.ClientIP(), auth)
c.AbortWithStatus(http.StatusBadRequest)
return
}
}
if msToken == "" || msToken != os.Getenv("MS_TOKEN") {
log.Printf("Unauthorized master server token from %s", c.ClientIP())
c.AbortWithStatus(http.StatusUnauthorized)
return
}
log.Printf("Discord single auth payload received from %s: %+v", c.ClientIP(), payload)
// Load Discord JWT secret from env (for generating permanent tokens).
jwtSecret := os.Getenv("JWT_DISCORD_SECRET")
if jwtSecret == "" {
log.Fatalf("JWT_DISCORD_SECRET not set") // Critical error
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Server configuration error"})
return
}
// Check for existing token.
var token string
err := ms.db.QueryRow("SELECT token FROM discord_auth WHERE discord_id = ?", payload.DiscordId).Scan(&token)
if err != nil {
if err == sql.ErrNoRows {
// Record does not exist, create a new one.
log.Printf("Single sync registering new user: %s (%s)", payload.DiscordId, payload.Username)
tkn := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"discord_id": payload.DiscordId,
"username": payload.Username,
"display_name": payload.DisplayName,
"pomelo_name": payload.PomeloName,
// Permanent token doesn't expire
})
token, err = tkn.SignedString([]byte(jwtSecret))
if err != nil {
log.Printf("Failed to create Discord JWT token for %s: %v", payload.DiscordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Insert username, display_name, and pomelo_name
_, err = ms.db.Exec("INSERT INTO discord_auth (discord_id, username, token, display_name, pomelo_name) VALUES (?, ?, ?, ?, ?)",
payload.DiscordId, payload.Username, token, payload.DisplayName, payload.PomeloName)
if err != nil {
log.Printf("Failed to store Discord token in database for %s: %v", payload.DiscordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
} else {
log.Printf("Database error querying discord_auth for %s: %v", payload.DiscordId, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
} else {
// Record exists, update username, display_name, and pomelo_name.
// This assumes the single sync also sends the latest names.
_, err = ms.db.Exec("UPDATE discord_auth SET username = ?, display_name = ?, pomelo_name = ? WHERE discord_id = ?",
payload.Username, payload.DisplayName, payload.PomeloName, payload.DiscordId)
if err != nil {
log.Printf("Failed to update Discord auth record for %s: %v", payload.DiscordId, err)
// Log error but continue, client (bot) still gets the existing token
} else {
// log.Printf("Single sync updated user: %s", payload.DiscordId) // Optional: Log update
}
}
// Return the permanent token.
c.JSON(http.StatusOK, gin.H{"token": token})
}
// HandleHeartbeat processes a heartbeat from a game server.
// Endpoint: POST /heartbeat
// Authentication: None required initially, validation happens via UDP challenge
// Body: { "host_name": "...", "map_name": "...", ... }
func (ms *MasterServer) HandleHeartbeat(c *gin.Context) {
var heartbeat struct {
HostName string `json:"host_name"`
MapName string `json:"map_name"`
GameMode string `json:"game_mode"`
MaxPlayers int `json:"max_players"`
Version string `json:"version"`
Description string `json:"description"`
Playlist string `json:"playlist"`
PlaylistDisplayName string `json:"playlist_display_name"`
Port int `json:"port"`
HasPassword bool `json:"has_password"`
HasAuth bool `json:"has_auth"`
Players []PlayerInfo `json:"players"` // Array of players
// TotalPlayers field is computed from len(Players)
}
if err := c.ShouldBindJSON(&heartbeat); err != nil {
log.Printf("Invalid heartbeat format from %s: %v", c.ClientIP(), err)
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Get the client IP (this is the server's public IP from the master server's perspective)
ip := c.ClientIP()
// Validate port.
if heartbeat.Port <= 1024 || heartbeat.Port > 65535 {
log.Printf("Invalid port number %d in heartbeat from %s:%d", heartbeat.Port, ip, heartbeat.Port)
c.String(http.StatusBadRequest, "Invalid port number (must be 1025-65535)")
c.Abort()
return
}
// ---------- REGION-PREFIX & SANITIZATION LOGIC ----------
var regionCode string
// Parse the IP and check for errors
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
log.Printf("Invalid IP address parsed from c.ClientIP() for heartbeat: %s", ip)
regionCode = RegionUNK // Treat as unknown if IP is invalid
} else if parsedIP.IsLoopback() || parsedIP.IsPrivate() {
regionCode = RegionLOC // Mark as local if it's a private/loopback IP
} else if ms.geoip != nil {
rec, geoipErr := ms.geoip.City(parsedIP) // Use a specific error variable for geoip
if geoipErr != nil {
log.Printf("GeoIP lookup failed for %s: %v", ip, geoipErr) // Use specific error variable
regionCode = RegionUNK // Treat as unknown if GeoIP fails
} else {
regionCode = determineRegionCode(rec) // Determine region from GeoIP record
}
} else {
// GeoIP database not loaded (should be fatal, but handle defensively)
// Logged at startup if failed. Just assign UNK.
regionCode = RegionUNK
}
// Strip any old [[XXXXX]] prefix from the *original* hostname
cleanName := stripPrefix.ReplaceAllString(heartbeat.HostName, "")
cleanName = strings.TrimSpace(cleanName)
// Sanitize the clean name. This ensures the sanitization rules
// don't accidentally break the region prefix format itself.
sanitizedCleanName := strings.Map(func(r rune) rune {
// Keep letters, numbers, spaces, and some common punctuation. Remove others.
// Allow spaces. Note: Brackets '[' and ']' are deliberately excluded here
// as they are used for the region prefix format and should not appear in the name part.
if unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSpace(r) || strings.ContainsRune("!@#$%^&*()-_+=.,?'_:", r) {
return r
}
return '_' // Replace disallowed characters with underscore
}, cleanName) // Apply map to the cleanName
// Trim leading/trailing underscores or spaces that might result from sanitization
sanitizedCleanName = strings.Trim(sanitizedCleanName, "_ ")
// If the sanitized clean name is empty or too short, use a default *clean* name.
if len(sanitizedCleanName) < 3 { // Minimum length for the name part after region code
sanitizedCleanName = "Unnamed R1Delta Server" // Default clean name
}
// Construct the final hostname by prepending the region code to the sanitized clean name.
// The prefix is formatted as [[CODE]], e.g., [[US-EAST]]
heartbeat.HostName = fmt.Sprintf("%s %s", regionCode, sanitizedCleanName) // Correctly format and assign
// Limit total hostname length after prefixing
if len(heartbeat.HostName) > 64 {
heartbeat.HostName = heartbeat.HostName[:64]
}
// ---------- END REGION-PREFIX & SANITIZATION LOGIC ----------
// Disallow specific map names if needed
// if strings.Contains(heartbeat.MapName, "mp_npe") {
// log.Printf("Ignoring heartbeat from %s:%d on disallowed map '%s'", ip, heartbeat.Port, heartbeat.MapName)
// c.Status(http.StatusOK) // Indicate successful processing, but server won't be listed
// return
// }
// Validate map name.
if heartbeat.MapName == "" || len(heartbeat.MapName) > 32 || !isValidMapName(heartbeat.MapName) {
log.Printf("Invalid map name %q from %s:%d", heartbeat.MapName, ip, heartbeat.Port)
c.String(http.StatusBadRequest, "Invalid map name format (lowercase letters, numbers, underscores only)")
c.Abort()
return
}
// Validate game mode.
if heartbeat.GameMode == "" || len(heartbeat.GameMode) > 32 || !isValidGameMode(heartbeat.GameMode) {
log.Printf("Invalid game mode %q from %s:%d", heartbeat.GameMode, ip, heartbeat.Port)
c.String(http.StatusBadRequest, "Invalid game mode format (lowercase letters, numbers, underscores only)")
c.Abort()
return
}
// Validate max players.
if heartbeat.MaxPlayers <= 1 || heartbeat.MaxPlayers > 128 { // Assuming reasonable max players, e.g., up to 128
log.Printf("Invalid max players %d from %s:%d", heartbeat.MaxPlayers, ip, heartbeat.Port)
c.String(http.StatusBadRequest, "Invalid max players (must be 2-128)") // Adjust range as needed
c.Abort()
return
}
// Validate player count doesn't exceed max players.
if len(heartbeat.Players) > heartbeat.MaxPlayers {
log.Printf("Too many players (%d) vs max players (%d) from %s:%d", len(heartbeat.Players), heartbeat.MaxPlayers, ip, heartbeat.Port)
c.String(http.StatusBadRequest, "Player count exceeds max players")
c.Abort()
return
}
key := fmt.Sprintf("%s:%d", ip, heartbeat.Port) // Key is IP:Port
ms.serversMu.Lock()
defer ms.serversMu.Unlock()
// Retrieve existing server entry if it exists to preserve validation status.
existingEntry, serverExists := ms.servers[key]
// Limit maximum servers per IP to 5.
if !serverExists {
count := 0
for _, s := range ms.servers {
// Only count servers from the same IP.
if s.IP == ip { // Compare against the derived IP from c.ClientIP()
count++
}
}
if count >= 20 {
log.Printf("Too many servers (%d) for IP %s from %s", count, ip, c.ClientIP())
c.String(http.StatusBadRequest, "Maximum 5 servers per IP")