-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
3542 lines (3162 loc) · 106 KB
/
main.go
File metadata and controls
3542 lines (3162 loc) · 106 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 (
"archive/zip"
"bufio"
"bytes"
"compress/gzip"
"crypto/md5"
crand "crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/binary"
"encoding/hex"
"encoding/json"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"log"
"math"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
_ "modernc.org/sqlite"
)
// ═══════════════════════════════════════════════════════════════════
// CONFIGURATION & PERSISTENCE
// ═══════════════════════════════════════════════════════════════════
type Config struct {
ServerName string
Motd string
Port string
WorldPasswords map[string]string
OpPassword string
BannedBlocks []byte
Public bool
MaxPlayers int
VerifyNames bool
TerrainURL string // URL sent to clients for texture pack
HTTPPort string // port for built-in HTTP server (serves terrain.png)
Software string
}
var (
serverConfig Config
serverSalt string // random salt for heartbeat / name verification
)
func hashPassword(password string) string {
hash := sha256.Sum256([]byte(password))
return hex.EncodeToString(hash[:])
}
func generateSalt() string {
b := make([]byte, 16)
crand.Read(b)
return hex.EncodeToString(b)[:16]
}
// verifyPlayerName checks md5(salt + username) == verifyKey.
// This is the ClassiCube name verification scheme.
func verifyPlayerName(username, verifyKey string) bool {
expected := md5.Sum([]byte(serverSalt + username))
return hex.EncodeToString(expected[:]) == verifyKey
}
func saveConfig() {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("ServerName=%s\n", serverConfig.ServerName))
buf.WriteString(fmt.Sprintf("Motd=%s\n", serverConfig.Motd))
buf.WriteString(fmt.Sprintf("Port=%s\n", strings.TrimPrefix(serverConfig.Port, ":")))
buf.WriteString(fmt.Sprintf("Public=%v\n", serverConfig.Public))
buf.WriteString(fmt.Sprintf("MaxPlayers=%d\n", serverConfig.MaxPlayers))
buf.WriteString(fmt.Sprintf("VerifyNames=%v\n", serverConfig.VerifyNames))
buf.WriteString(fmt.Sprintf("Software=%s\n", serverConfig.Software))
if serverConfig.TerrainURL != "" {
buf.WriteString(fmt.Sprintf("TerrainURL=%s\n", serverConfig.TerrainURL))
}
if serverConfig.HTTPPort != "" {
buf.WriteString(fmt.Sprintf("HTTPPort=%s\n", serverConfig.HTTPPort))
}
if serverConfig.OpPassword != "" {
buf.WriteString(fmt.Sprintf("OpPassword=%s\n", serverConfig.OpPassword))
}
if len(serverConfig.BannedBlocks) > 0 {
var strBlocks []string
for _, b := range serverConfig.BannedBlocks {
strBlocks = append(strBlocks, strconv.Itoa(int(b)))
}
buf.WriteString(fmt.Sprintf("BannedBlocks=%s\n", strings.Join(strBlocks, ",")))
}
for world, passHash := range serverConfig.WorldPasswords {
buf.WriteString(fmt.Sprintf("pass_%s=%s\n", world, passHash))
}
os.WriteFile("server.properties", buf.Bytes(), 0644)
}
func savePortals(portals []Portal, path string) {
data, _ := json.MarshalIndent(portals, "", " ")
os.WriteFile(path, data, 0644)
}
func loadPortals(path string) []Portal {
data, err := os.ReadFile(path)
if err != nil {
return nil
}
var portals []Portal
json.Unmarshal(data, &portals)
return portals
}
func loadConfig() {
serverConfig = Config{
ServerName: "Go Classic Server",
Motd: "Welcome to the server!",
Port: ":25565",
WorldPasswords: make(map[string]string),
Public: false,
MaxPlayers: 128,
VerifyNames: true,
Software: "GoClassic 1.0",
}
f, err := os.Open("server.properties")
if err != nil {
defaultWorldHash := hashPassword("letmein")
defaultOpHash := hashPassword("admin")
defaultProps := fmt.Sprintf("ServerName=Go Classic Server\nMotd=Welcome to the server!\nPort=25565\nPublic=false\nMaxPlayers=128\nVerifyNames=true\nSoftware=GoClassic 1.0\n# TerrainURL=http://your-ip:8080/terrain.zip\n# HTTPPort=8080\npass_world2=%s\nOpPassword=%s\nBannedBlocks=8,9,10,11\n", defaultWorldHash, defaultOpHash)
os.WriteFile("server.properties", []byte(defaultProps), 0644)
serverConfig.WorldPasswords["world2"] = defaultWorldHash
serverConfig.OpPassword = defaultOpHash
serverConfig.BannedBlocks = []byte{8, 9, 10, 11}
return
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "#") || !strings.Contains(line, "=") {
continue
}
parts := strings.SplitN(line, "=", 2)
key, val := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
switch key {
case "ServerName":
serverConfig.ServerName = val
case "Motd":
serverConfig.Motd = val
case "Port":
serverConfig.Port = ":" + strings.TrimPrefix(val, ":")
case "OpPassword":
serverConfig.OpPassword = val
case "Public":
serverConfig.Public = strings.EqualFold(val, "true")
case "MaxPlayers":
if n, err := strconv.Atoi(val); err == nil && n > 0 {
serverConfig.MaxPlayers = n
}
case "VerifyNames":
serverConfig.VerifyNames = strings.EqualFold(val, "true")
case "TerrainURL":
serverConfig.TerrainURL = val
case "HTTPPort":
serverConfig.HTTPPort = strings.TrimPrefix(val, ":")
case "Software":
serverConfig.Software = val
case "BannedBlocks":
for _, bStr := range strings.Split(val, ",") {
if b, err := strconv.Atoi(strings.TrimSpace(bStr)); err == nil {
serverConfig.BannedBlocks = append(serverConfig.BannedBlocks, byte(b))
}
}
default:
if strings.HasPrefix(key, "pass_") {
worldName := strings.TrimPrefix(key, "pass_")
serverConfig.WorldPasswords[worldName] = val
}
}
}
}
// ═══════════════════════════════════════════════════════════════════
// CLASSICUBE HEARTBEAT & SERVER LIST
// ═══════════════════════════════════════════════════════════════════
func startHeartbeat(server *Server) {
if !serverConfig.Public {
log.Println("[Heartbeat] Public=false — not sending heartbeats.")
return
}
log.Printf("[Heartbeat] Salt=%s — starting heartbeat to classicube.net", serverSalt)
go func() {
ticker := time.NewTicker(45 * time.Second)
defer ticker.Stop()
// Send immediately on start, then every 45s
sendHeartbeat(server)
for range ticker.C {
sendHeartbeat(server)
}
}()
}
func sendHeartbeat(server *Server) {
server.mu.RLock()
playerCount := len(server.players)
server.mu.RUnlock()
port := strings.TrimPrefix(serverConfig.Port, ":")
params := url.Values{}
params.Set("name", serverConfig.ServerName)
params.Set("port", port)
params.Set("users", strconv.Itoa(playerCount))
params.Set("max", strconv.Itoa(serverConfig.MaxPlayers))
params.Set("public", "True")
params.Set("software", serverConfig.Software)
params.Set("salt", serverSalt)
params.Set("web", "True")
// ClassiCube heartbeat accepts GET with query params
heartbeatURL := "https://www.classicube.net/server/heartbeat/?" + params.Encode()
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Get(heartbeatURL)
if err != nil {
log.Printf("[Heartbeat] Failed: %v", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
result := strings.TrimSpace(string(body))
if resp.StatusCode == 200 && strings.HasPrefix(result, "http") {
log.Printf("[Heartbeat] Listed — %d player(s) — %s", playerCount, result)
} else if resp.StatusCode == 200 {
// 200 but no URL means an error message from the server
log.Printf("[Heartbeat] Response: %s", result)
} else {
log.Printf("[Heartbeat] HTTP %d: %s", resp.StatusCode, result)
}
}
// ═══════════════════════════════════════════════════════════════════
// BUILT-IN HTTP SERVER (serves terrain.png as .zip for CPE EnvMapAspect)
// ═══════════════════════════════════════════════════════════════════
var terrainZipCache []byte // cached zip containing terrain.png
func buildTerrainZip() ([]byte, error) {
pngData, err := os.ReadFile("terrain.png")
if err != nil {
return nil, err
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
fw, err := zw.Create("terrain.png")
if err != nil {
return nil, err
}
fw.Write(pngData)
zw.Close()
return buf.Bytes(), nil
}
func startHTTPServer() {
if serverConfig.HTTPPort == "" {
return
}
// Look for terrain.png in the current dir or a textures/ subdir
terrainPath := "terrain.png"
if _, err := os.Stat(terrainPath); os.IsNotExist(err) {
terrainPath = filepath.Join("textures", "terrain.png")
if _, err := os.Stat(terrainPath); os.IsNotExist(err) {
log.Printf("[HTTP] terrain.png not found — HTTP server not started.")
log.Printf("[HTTP] Place terrain.png in the server directory to enable.")
return
}
}
// Pre-build the zip
zipData, err := buildTerrainZip()
if err != nil {
log.Printf("[HTTP] Failed to build terrain.zip: %v", err)
return
}
terrainZipCache = zipData
log.Printf("[HTTP] Built terrain.zip (%d bytes) from %s", len(zipData), terrainPath)
mux := http.NewServeMux()
// Serve the raw PNG
mux.HandleFunc("/terrain.png", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "image/png")
w.Header().Set("Cache-Control", "public, max-age=3600")
w.Header().Set("Access-Control-Allow-Origin", "*")
http.ServeFile(w, r, terrainPath)
})
// Serve the zipped texture pack (ClassiCube EnvMapAspect expects a .zip)
mux.HandleFunc("/terrain.zip", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/zip")
w.Header().Set("Content-Length", strconv.Itoa(len(terrainZipCache)))
w.Header().Set("Cache-Control", "public, max-age=3600")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(terrainZipCache)
})
// Reload endpoint so ops can update the texture without restarting
mux.HandleFunc("/terrain/reload", func(w http.ResponseWriter, r *http.Request) {
newZip, err := buildTerrainZip()
if err != nil {
http.Error(w, "reload failed: "+err.Error(), 500)
return
}
terrainZipCache = newZip
log.Printf("[HTTP] terrain.zip reloaded (%d bytes)", len(newZip))
w.Write([]byte("OK"))
})
addr := ":" + serverConfig.HTTPPort
log.Printf("[HTTP] Serving terrain on %s (/terrain.png, /terrain.zip)", addr)
go func() {
if err := http.ListenAndServe(addr, mux); err != nil {
log.Printf("[HTTP] Server failed: %v", err)
}
}()
}
// ═══════════════════════════════════════════════════════════════════
// CPE EnvMapAspect — send texture URL to client
// ═══════════════════════════════════════════════════════════════════
// sendSetTexturePack sends a CPE SetMapEnvUrl (0x28) packet from
// the EnvMapAspect extension — this sets the texture pack URL.
func sendSetTexturePack(conn net.Conn, textureURL string) {
pkt := make([]byte, 65)
pkt[0] = 0x28
copy(pkt[1:65], padString(textureURL))
conn.Write(pkt)
}
// ═══════════════════════════════════════════════════════════════════
// CUSTOM BLOCK DEFINITIONS (CPE BlockDefinitions)
// ═══════════════════════════════════════════════════════════════════
// CustomBlock holds every property the CPE DefineBlock packet carries.
// Persisted to customblocks.json and sent to BlockDefinitions-capable clients.
type CustomBlock struct {
ID byte `json:"id"`
Name string `json:"name"`
Solidity byte `json:"solidity"` // 0=walk-through 1=swim-through 2=solid
Speed byte `json:"speed"` // 1..8 (4 = normal 1.0x)
TopTex byte `json:"top_tex"` // texture-atlas index
SideTex byte `json:"side_tex"` // texture-atlas index (all 4 sides)
BottomTex byte `json:"bottom_tex"` // texture-atlas index
TransmitLight byte `json:"transmit_light"` // 0 or 1
WalkSound byte `json:"walk_sound"` // 0=none 1=wood 2=gravel 3=grass 4=stone 5=metal 6=glass 7=wool 8=sand 9=snow
FullBright byte `json:"full_bright"` // 0 or 1
Shape byte `json:"shape"` // 0=sprite 1-16=height in sixteenths
BlockDraw byte `json:"block_draw"` // 0=opaque 1=transparent(same) 2=transparent(diff) 3=translucent 4=gas
FogDensity byte `json:"fog_density"`
FogR byte `json:"fog_r"`
FogG byte `json:"fog_g"`
FogB byte `json:"fog_b"`
Fallback byte `json:"fallback"` // vanilla block ID for non-CPE clients (0-49)
}
var (
customBlocks = make(map[byte]CustomBlock) // key = block ID
customBlocksMu sync.RWMutex
)
func loadCustomBlocks() {
data, err := os.ReadFile("customblocks.json")
if err != nil {
return
}
// Strip UTF-8 BOM if present (common when editing with Notepad on Windows)
if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
data = data[3:]
}
var list []CustomBlock
if err := json.Unmarshal(data, &list); err != nil {
log.Printf("[Blocks] ERROR parsing customblocks.json: %v", err)
log.Printf("[Blocks] No custom blocks loaded — fix the JSON and restart.")
return
}
customBlocksMu.Lock()
for _, cb := range list {
if cb.ID < 50 {
log.Printf("[Blocks] WARNING: skipping block %d (%q) — ID must be 50-255", cb.ID, cb.Name)
continue
}
cb = clampBlockProperties(cb)
customBlocks[cb.ID] = cb
log.Printf("[Blocks] Loaded block %d: %q (tex %d/%d/%d, fb %d)",
cb.ID, cb.Name, cb.TopTex, cb.SideTex, cb.BottomTex, cb.Fallback)
}
customBlocksMu.Unlock()
}
// clampBlockProperties forces every field into its valid range so a
// hand-edited JSON file can never produce a broken DefineBlock packet.
func clampBlockProperties(cb CustomBlock) CustomBlock {
if cb.Solidity > 2 {
cb.Solidity = 2
}
if cb.Speed < 1 || cb.Speed > 8 {
cb.Speed = 4
}
if cb.TransmitLight > 1 {
cb.TransmitLight = 0
}
if cb.WalkSound > 9 {
cb.WalkSound = 0
}
if cb.FullBright > 1 {
cb.FullBright = 0
}
if cb.Shape > 16 {
cb.Shape = 16
}
if cb.BlockDraw > 4 {
cb.BlockDraw = 0
}
if cb.Fallback > 49 {
cb.Fallback = 1
}
if len(cb.Name) > 64 {
cb.Name = cb.Name[:64]
}
return cb
}
// ── MCGalaxy global.json import ──────────────────────────────────
// mcgBlockDef mirrors the JSON layout MCGalaxy uses in global.json.
type mcgBlockDef struct {
BlockID int `json:"BlockID"`
Name string `json:"Name"`
Speed int `json:"Speed"`
CollideType int `json:"CollideType"`
TopTex int `json:"TopTex"`
BottomTex int `json:"BottomTex"`
LeftTex int `json:"LeftTex"`
RightTex int `json:"RightTex"`
FrontTex int `json:"FrontTex"`
BackTex int `json:"BackTex"`
BlocksLight bool `json:"BlocksLight"`
WalkSound int `json:"WalkSound"`
FullBright bool `json:"FullBright"`
Shape int `json:"Shape"`
BlockDraw int `json:"BlockDraw"`
FallBack int `json:"FallBack"`
FogDensity int `json:"FogDensity"`
FogR int `json:"FogR"`
FogG int `json:"FogG"`
FogB int `json:"FogB"`
MinX int `json:"MinX"`
MinY int `json:"MinY"`
MinZ int `json:"MinZ"`
MaxX int `json:"MaxX"`
MaxY int `json:"MaxY"`
MaxZ int `json:"MaxZ"`
}
// mcgToCustomBlock converts an MCGalaxy block definition into our format.
func mcgToCustomBlock(m mcgBlockDef) CustomBlock {
// MCGalaxy stores per-face side textures; DefineBlock (0x23) has one
// SideTex field, so pick LeftTex (they're usually all the same).
sideTex := byte(m.LeftTex)
// MCGalaxy: BlocksLight=true means the block BLOCKS light → TransmitLight=0
transmit := byte(0)
if !m.BlocksLight {
transmit = 1
}
bright := byte(0)
if m.FullBright {
bright = 1
}
// MCGalaxy Speed is the raw CPE byte (1-8).
// A value of 0 in their JSON means "default" → treat as 4 (1.0×).
speed := byte(m.Speed)
if speed == 0 {
speed = 4
}
// Ensure fallback is vanilla-safe
fallback := byte(m.FallBack)
if fallback > 49 {
fallback = 1
}
return clampBlockProperties(CustomBlock{
ID: byte(m.BlockID),
Name: m.Name,
Solidity: byte(m.CollideType),
Speed: speed,
TopTex: byte(m.TopTex),
SideTex: sideTex,
BottomTex: byte(m.BottomTex),
TransmitLight: transmit,
WalkSound: byte(m.WalkSound),
FullBright: bright,
Shape: byte(m.Shape),
BlockDraw: byte(m.BlockDraw),
FogDensity: byte(m.FogDensity),
FogR: byte(m.FogR),
FogG: byte(m.FogG),
FogB: byte(m.FogB),
Fallback: fallback,
})
}
// importMCGalaxyBlocks reads an MCGalaxy-format JSON file and merges
// the blocks into the custom blocks map. Returns counts of imported
// and skipped blocks plus any error.
func importMCGalaxyBlocks(path string) (imported, skipped int, err error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, 0, err
}
// Strip UTF-8 BOM
if len(data) >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF {
data = data[3:]
}
var defs []mcgBlockDef
if err := json.Unmarshal(data, &defs); err != nil {
return 0, 0, fmt.Errorf("JSON parse error: %w", err)
}
customBlocksMu.Lock()
defer customBlocksMu.Unlock()
for _, m := range defs {
if m.BlockID < 50 || m.BlockID > 255 {
log.Printf("[Import] Skipping block %d (%q) — ID out of range 50-255", m.BlockID, m.Name)
skipped++
continue
}
cb := mcgToCustomBlock(m)
customBlocks[cb.ID] = cb
imported++
log.Printf("[Import] Imported block %d: %q (tex %d/%d/%d, fb %d)",
cb.ID, cb.Name, cb.TopTex, cb.SideTex, cb.BottomTex, cb.Fallback)
}
return imported, skipped, nil
}
func saveCustomBlocks() {
customBlocksMu.RLock()
list := make([]CustomBlock, 0, len(customBlocks))
for _, cb := range customBlocks {
list = append(list, cb)
}
customBlocksMu.RUnlock()
data, _ := json.MarshalIndent(list, "", " ")
os.WriteFile("customblocks.json", data, 0644)
}
// vanillaBlockNames maps standard Classic block IDs to human-readable names.
var vanillaBlockNames = map[byte]string{
0: "Air", 1: "Stone", 2: "Grass", 3: "Dirt", 4: "Cobblestone",
5: "Planks", 6: "Sapling", 7: "Bedrock", 8: "Water", 9: "Still Water",
10: "Lava", 11: "Still Lava", 12: "Sand", 13: "Gravel", 14: "Gold Ore",
15: "Iron Ore", 16: "Coal Ore", 17: "Log", 18: "Leaves", 19: "Sponge",
20: "Glass", 21: "Red Wool", 22: "Orange Wool", 23: "Yellow Wool",
24: "Lime Wool", 25: "Green Wool", 26: "Teal Wool", 27: "Aqua Wool",
28: "Cyan Wool", 29: "Blue Wool", 30: "Indigo Wool", 31: "Violet Wool",
32: "Magenta Wool", 33: "Pink Wool", 34: "Black Wool", 35: "Gray Wool",
36: "White Wool", 37: "Dandelion", 38: "Rose", 39: "Brown Mushroom",
40: "Red Mushroom", 41: "Gold Block", 42: "Iron Block", 43: "Double Slab",
44: "Slab", 45: "Brick", 46: "TNT", 47: "Bookshelf", 48: "Mossy Cobblestone",
49: "Obsidian",
// CPE CustomBlocks (50-65)
50: "Cobblestone Slab", 51: "Rope", 52: "Sandstone", 53: "Snow",
54: "Fire", 55: "Light Pink", 56: "Forest Green", 57: "Brown",
58: "Deep Blue", 59: "Turquoise", 60: "Ice", 61: "Ceramic Tile",
62: "Magma", 63: "Pillar", 64: "Crate", 65: "Stone Brick",
}
// blockName returns a human-readable name for a block ID.
// Checks custom blocks first, then vanilla names, then falls back to the numeric ID.
func blockName(id byte) string {
customBlocksMu.RLock()
if cb, ok := customBlocks[id]; ok {
customBlocksMu.RUnlock()
return cb.Name
}
customBlocksMu.RUnlock()
if name, ok := vanillaBlockNames[id]; ok {
return name
}
return fmt.Sprintf("Block %d", id)
}
// sendDefineBlock sends a CPE DefineBlock (0x23) packet to a single connection.
func sendDefineBlock(conn net.Conn, cb CustomBlock) {
pkt := make([]byte, 80)
pkt[0] = 0x23
pkt[1] = cb.ID
copy(pkt[2:66], padString(cb.Name))
pkt[66] = cb.Solidity
pkt[67] = cb.Speed
pkt[68] = cb.TopTex
pkt[69] = cb.SideTex
pkt[70] = cb.BottomTex
pkt[71] = cb.TransmitLight
pkt[72] = cb.WalkSound
pkt[73] = cb.FullBright
pkt[74] = cb.Shape
pkt[75] = cb.BlockDraw
pkt[76] = cb.FogDensity
pkt[77] = cb.FogR
pkt[78] = cb.FogG
pkt[79] = cb.FogB
conn.Write(pkt)
}
// sendRemoveBlockDef sends a CPE RemoveBlockDefinition (0x24) packet.
func sendRemoveBlockDef(conn net.Conn, id byte) {
conn.Write([]byte{0x24, id})
}
// sendAllCustomBlocks sends every stored definition to a connection.
func sendAllCustomBlocks(conn net.Conn) {
customBlocksMu.RLock()
defer customBlocksMu.RUnlock()
for _, cb := range customBlocks {
sendDefineBlock(conn, cb)
}
}
// broadcastDefineBlock pushes a definition to every connected BlockDefs client.
func (s *Server) broadcastDefineBlock(cb CustomBlock) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, p := range s.players {
if p.SupportsBlockDefs {
sendDefineBlock(p.Conn, cb)
}
}
}
// broadcastRemoveBlock pushes a remove to every connected BlockDefs client.
func (s *Server) broadcastRemoveBlock(id byte) {
s.mu.RLock()
defer s.mu.RUnlock()
for _, p := range s.players {
if p.SupportsBlockDefs {
sendRemoveBlockDef(p.Conn, id)
}
}
}
// ═══════════════════════════════════════════════════════════════════
// PLAYER DB PERSISTENCE
// ═══════════════════════════════════════════════════════════════════
// PlayerState is used only for JSON migration.
type PlayerState struct {
World string `json:"world"`
X int16 `json:"x"`
Y int16 `json:"y"`
Z int16 `json:"z"`
Yaw byte `json:"yaw"`
Pitch byte `json:"pitch"`
SavedPasswords map[string]string `json:"saved_passwords"`
}
// loadPlayerState reads a player's saved state from SQLite.
func loadPlayerState(username string) (world string, x, y, z int16, yaw, pitch, heldBlock byte, passwords map[string]string, ok bool) {
if serverDB == nil {
return
}
passwords = make(map[string]string)
err := serverDB.QueryRow(
"SELECT world, x, y, z, yaw, pitch, held_block FROM players WHERE username=?", username,
).Scan(&world, &x, &y, &z, &yaw, &pitch, &heldBlock)
if err != nil {
return
}
ok = true
rows, err := serverDB.Query("SELECT world_name, password_hash FROM player_passwords WHERE username=?", username)
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var wn, ph string
rows.Scan(&wn, &ph)
passwords[wn] = ph
}
return
}
// updatePlayerState saves the player's current state to SQLite.
func updatePlayerState(p *Player) {
if p.World == nil || serverDB == nil {
return
}
p.mu.Lock()
hb := p.HeldBlock
savedPws := make(map[string]string)
for k, v := range p.SavedPasswords {
savedPws[k] = v
}
p.mu.Unlock()
serverDB.Exec(`
INSERT INTO players(username, world, x, y, z, yaw, pitch, held_block)
VALUES(?,?,?,?,?,?,?,?)
ON CONFLICT(username) DO UPDATE SET
world=excluded.world, x=excluded.x, y=excluded.y, z=excluded.z,
yaw=excluded.yaw, pitch=excluded.pitch, held_block=excluded.held_block
`, p.Username, p.World.Name, p.X, p.Y, p.Z, p.Yaw, p.Pitch, hb)
// Update saved passwords
for wn, ph := range savedPws {
serverDB.Exec(`
INSERT INTO player_passwords(username, world_name, password_hash)
VALUES(?,?,?)
ON CONFLICT(username, world_name) DO UPDATE SET password_hash=excluded.password_hash
`, p.Username, wn, ph)
}
}
// ═══════════════════════════════════════════════════════════════════
// BAN LIST
// ═══════════════════════════════════════════════════════════════════
type BanEntry struct {
Username string `json:"username"`
Reason string `json:"reason"`
BannedBy string `json:"banned_by"`
Time string `json:"time"`
IP string `json:"ip"`
}
var (
bannedPlayers = make(map[string]BanEntry)
banMutex sync.RWMutex
)
func loadBanList() {
data, err := os.ReadFile("banned.json")
if err != nil {
return
}
var list []BanEntry
if json.Unmarshal(data, &list) == nil {
banMutex.Lock()
for _, b := range list {
bannedPlayers[strings.ToLower(b.Username)] = b
}
banMutex.Unlock()
}
}
func saveBanList() {
banMutex.RLock()
list := make([]BanEntry, 0, len(bannedPlayers))
for _, b := range bannedPlayers {
list = append(list, b)
}
banMutex.RUnlock()
data, _ := json.MarshalIndent(list, "", " ")
os.WriteFile("banned.json", data, 0644)
}
func isPlayerBanned(username string) (BanEntry, bool) {
banMutex.RLock()
defer banMutex.RUnlock()
b, ok := bannedPlayers[strings.ToLower(username)]
return b, ok
}
// ═══════════════════════════════════════════════════════════════════
// BLOCK HISTORY — SQLite-backed per-world change log
// ═══════════════════════════════════════════════════════════════════
type BlockChange struct {
Time int64
Player string
World string
X int16
Y int16
Z int16
OldBlock byte
NewBlock byte
}
var serverDB *sql.DB
func initDatabase() {
var err error
serverDB, err = sql.Open("sqlite", "server.db?_journal_mode=WAL&_busy_timeout=5000")
if err != nil {
log.Fatalf("[DB] Failed to open database: %v", err)
}
// WAL mode + pragmas for performance
serverDB.Exec("PRAGMA journal_mode=WAL")
serverDB.Exec("PRAGMA synchronous=NORMAL")
serverDB.Exec("PRAGMA cache_size=-8000") // 8MB cache
// ── Block history table ──
_, err = serverDB.Exec(`
CREATE TABLE IF NOT EXISTS block_changes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
time INTEGER NOT NULL,
player TEXT NOT NULL,
world TEXT NOT NULL,
x INTEGER NOT NULL,
y INTEGER NOT NULL,
z INTEGER NOT NULL,
old_block INTEGER NOT NULL,
new_block INTEGER NOT NULL
)
`)
if err != nil {
log.Fatalf("[DB] Failed to create block_changes table: %v", err)
}
serverDB.Exec("CREATE INDEX IF NOT EXISTS idx_block_pos ON block_changes(world, x, y, z, time DESC)")
serverDB.Exec("CREATE INDEX IF NOT EXISTS idx_player_time ON block_changes(world, player COLLATE NOCASE, time DESC)")
serverDB.Exec("CREATE INDEX IF NOT EXISTS idx_time ON block_changes(time)")
// ── Players table ──
serverDB.Exec(`
CREATE TABLE IF NOT EXISTS players (
username TEXT PRIMARY KEY,
world TEXT NOT NULL DEFAULT 'hub',
x INTEGER NOT NULL DEFAULT 0,
y INTEGER NOT NULL DEFAULT 0,
z INTEGER NOT NULL DEFAULT 0,
yaw INTEGER NOT NULL DEFAULT 0,
pitch INTEGER NOT NULL DEFAULT 0,
held_block INTEGER NOT NULL DEFAULT 1,
last_seen INTEGER NOT NULL DEFAULT 0
)
`)
// ── Player saved passwords table ──
serverDB.Exec(`
CREATE TABLE IF NOT EXISTS player_passwords (
username TEXT NOT NULL,
world_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
PRIMARY KEY (username, world_name)
)
`)
// Auto-migrate old data
migrateJSONHistory()
migrateJSONPlayers()
// Migrate old blockhistory.db if present (from before the rename)
if _, err := os.Stat("blockhistory.db"); err == nil {
log.Printf("[DB] NOTE: Old blockhistory.db found. Data has been migrated to server.db.")
log.Printf("[DB] You can delete blockhistory.db to save space.")
}
var histCount int64
serverDB.QueryRow("SELECT COUNT(*) FROM block_changes").Scan(&histCount)
var playerCount int64
serverDB.QueryRow("SELECT COUNT(*) FROM players").Scan(&playerCount)
log.Printf("[DB] Ready — %d block changes, %d players", histCount, playerCount)
}
func migrateJSONPlayers() {
data, err := os.ReadFile("players.json")
if err != nil {
return
}
var oldDB map[string]PlayerState
if json.Unmarshal(data, &oldDB) != nil || len(oldDB) == 0 {
return
}
log.Printf("[DB] Migrating %d players from players.json to SQLite...", len(oldDB))
tx, err := serverDB.Begin()
if err != nil {
return
}
playerStmt, _ := tx.Prepare(`
INSERT OR IGNORE INTO players(username, world, x, y, z, yaw, pitch, held_block, last_seen)
VALUES(?,?,?,?,?,?,?,1,?)
`)
pwStmt, _ := tx.Prepare(`
INSERT OR IGNORE INTO player_passwords(username, world_name, password_hash)
VALUES(?,?,?)
`)
now := time.Now().Unix()
for username, state := range oldDB {
playerStmt.Exec(username, state.World, state.X, state.Y, state.Z, state.Yaw, state.Pitch, now)
for wn, ph := range state.SavedPasswords {
pwStmt.Exec(username, wn, ph)
}
}
playerStmt.Close()
pwStmt.Close()
tx.Commit()
os.Rename("players.json", "players.json.migrated")
log.Printf("[DB] Migrated %d players — renamed players.json to players.json.migrated", len(oldDB))
}
func migrateJSONHistory() {
entries, err := os.ReadDir("blockhistory")
if err != nil {
return
}
type jsonChange struct {
Time int64 `json:"t"`
Player string `json:"p"`
X int16 `json:"x"`
Y int16 `json:"y"`
Z int16 `json:"z"`
OldBlock byte `json:"ob"`
NewBlock byte `json:"nb"`
}
total := 0
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
worldName := strings.TrimSuffix(e.Name(), ".json")
data, err := os.ReadFile("blockhistory/" + e.Name())
if err != nil {
continue
}
var changes []jsonChange
if json.Unmarshal(data, &changes) != nil || len(changes) == 0 {
continue
}
log.Printf("[History] Migrating %d entries from %s to SQLite...", len(changes), e.Name())
tx, err := serverDB.Begin()
if err != nil {
continue
}
stmt, _ := tx.Prepare("INSERT INTO block_changes(time,player,world,x,y,z,old_block,new_block) VALUES(?,?,?,?,?,?,?,?)")
for _, c := range changes {
stmt.Exec(c.Time, c.Player, worldName, c.X, c.Y, c.Z, c.OldBlock, c.NewBlock)
}
stmt.Close()
tx.Commit()
total += len(changes)
// Rename the old file so it's not migrated again
os.Rename("blockhistory/"+e.Name(), "blockhistory/"+e.Name()+".migrated")