-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathserver_r12.py
More file actions
1243 lines (1065 loc) · 48.7 KB
/
server_r12.py
File metadata and controls
1243 lines (1065 loc) · 48.7 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
# server_r12.py - CLEANED & OPTIMIZED
import sys, socket, struct, time, threading, random, uuid
from _thread import *
# Import modular systems
from challenge_system_r11 import ChallengeSystem
from authentication_system_r11 import AuthenticationHandlers
from session_system_r11 import SessionManager, NetworkHandlers, PingManager, DataServerManager
from room_system_r11 import RoomManager, RoomHandlers
from message_system_r11 import MessageHandlers
from buddy_system_r11 import BuddyHandlers
from state_trigger import StateTrigger
# Import game modules
try:
from nascar_module import NascarHandlers
HAS_NASCAR = True
except ImportError:
HAS_NASCAR = False
print("WARNING: NASCAR module not available")
try:
from nbav3_module import NBAv3Handlers
HAS_NBAV3 = True
except ImportError:
HAS_NBAV3 = False
print("WARNING: NBA Street v3 module not available")
# Configuration
BUILD = "0.12-Modular"
PORT_NFSU_PS2 = 10900 # ps2nfs04.ea.com:10900
PORT_NFSU2_PS2 = 20900 # ps2nfs05.ea.com:10900
PORT_BO3U_PS2 = 21800 # ps2burnout05.ea.com:21800
PORT_BO3R_PS2 = 21840 # ps2lobby02.beta.ea.com:21840
PORT_NFL05_PS2 = 20000 # ps2madden05.ea.com:20000
PORT_BOP_PS3 = 21870 # ps3burnout08.ea.com:21870
PORT_BOP_PC = 21840 # pcburnout08.ea.com:21871
PORT_SSX3_PS2 = 11000 # ps2ssx04.ea.com:11000
PORT_NC04_PS2 = 10600 # ps2nascar04.ea.com:10600
PORT_NBAV3_PS2 = 21000 # ps2nbastreet05.ea.com:21000
# Update the PORTS dictionary
GAME_PORTS = {
'nc04': 10600, 'nbav3': 21000, 'nfsu': 10900, 'nfsu2': 20900,
'bo3u': 21800, 'bo3r': 21840, 'nfl05': 20000, 'bop_ps3': 21870,
'bop_pc': 21840, 'ssx3': 11000
}
# Update GAME_MODES dictionary (around line 35)
GAME_MODES = {
'nascar': {
'port': PORT_NC04_PS2,
'name': 'NASCAR Thunder 2004',
'module': None,
'handlers': None
},
'nbav3': {
'port': PORT_NBAV3_PS2,
'name': 'NBA Street v3',
'module': None,
'handlers': None
},
'nfsu': {
'port': PORT_NFSU_PS2,
'name': 'Need for Speed Underground',
'module': None,
'handlers': None
},
'nfsu2': {
'port': PORT_NFSU2_PS2,
'name': 'Need for Speed Underground 2',
'module': None,
'handlers': None
},
'bo3u': {
'port': PORT_BO3U_PS2,
'name': 'Burnout 3: Takedown (Update)',
'module': None,
'handlers': None
},
'bo3r': {
'port': PORT_BO3R_PS2,
'name': 'Burnout 3: Takedown (Release)',
'module': None,
'handlers': None
},
'nfl05': {
'port': PORT_NFL05_PS2,
'name': 'Madden NFL 2005',
'module': None,
'handlers': None
},
'bop_ps3': {
'port': PORT_BOP_PS3,
'name': 'Burnout Paradise (PS3)',
'module': None,
'handlers': None
},
'bop_pc': {
'port': PORT_BOP_PC,
'name': 'Burnout Paradise (PC)',
'module': None,
'handlers': None
},
'ssx3': {
'port': PORT_SSX3_PS2,
'name': 'SSX 3',
'module': None,
'handlers': None
}
}
SERVER_IP = None
PORTS = {
'listener': 10901,
'buddy': 10899,
'data_start': 11000,
}
# Game modes
GAME_MODES = {
'nascar': {
'port': PORT_NC04_PS2,
'name': 'NASCAR Thunder 2004',
'module': None,
'handlers': None
},
'nbav3': {
'port': PORT_NBAV3_PS2,
'name': 'NBA Street v3',
'module': None,
'handlers': None
}
}
# Global state
current_data_port = PORTS['data_start']
locks = {'data': threading.Lock()}
sockets = {'game': socket.socket(), 'buddy': socket.socket(), 'listener': socket.socket()}
current_game_mode = None # Will be set during bind_server()
# Protocol states
PROTOCOL_STATES = {
0x72646972: "STATE_DIRECTORY",
0x636f6e6e: "STATE_CONNECTED",
0x736b6579: "STATE_KEY_EXCHANGE",
0x69646c65: "STATE_IDLE",
0x61757468: "STATE_AUTH",
0x61636374: "STATE_ACCOUNT",
0x74696d65: "STATE_TIMEOUT",
0x7465726d: "STATE_TERMINATED",
0x6f66666c: "STATE_OFFLINE",
0xfefefefe: "STATE_ERROR"
}
# Update the imports section to be more concise
import sys, socket, struct, time, threading, random, uuid
from _thread import *
# Consolidated game ports
GAME_PORTS = {
'nc04': 10600, 'nbav3': 21000, 'nfsu': 10900, 'nfsu2': 20900,
'bo3u': 21800, 'bo3r': 21840, 'nfl05': 20000, 'bop_ps3': 21870,
'bop_pc': 21840, 'ssx3': 11000
}
# Update ClientSession field initialization to be more concise
class ClientSession:
def __init__(self, connection_id, game_mode=None):
self.connection_id = connection_id
self.game_mode = game_mode
self.room_id = 0
# Consolidate initialization
self.connection = self.ping_timer = None
self.data_port = 0
self.msgType = b''; self.msgSize = 0
self.authsent = self.SKEYSENT = self.NO_DATA = 0
self.news_cnt = self.ping_cnt = 0
self.last_activity = self.ping_start = time.time()
self.last_ping_time = 0; self.ping_interval = 5.0
self.ping_initiated = False
# User identity - consolidated
for attr in ['clientNAME', 'clientUSER', 'current_persona', 'authenticated_username']:
setattr(self, attr, 'Unknown')
self.available_personas = []
self.persona_count = 0
self.current_room = "Lobby"
self.current_room_id = 0
# Authentication - consolidated
self.auth_state = 0
self.auth_complete = False
self.auth_slots = []
self.validation_code1 = self.validation_code2 = self.validation_code3 = 0
self.auth_timestamp = 0
# Challenge system - consolidated
self.challenge_state = 0
self.challenger = self.challenge_target = self.challenge_seed = ''
self.challenge_timeout = 0
self.last_challenge_state = 0
self.system_command_sent = False
# Buddy system
self.buddy_socket = None
self.buddy_connected = False
self.buddy_list = []
# Consolidated game-specific setup
game_init_map = {
'nascar': self._init_nascar,
'nbav3': self._init_nbav3,
'nfsu': self._init_nfsu,
'nfsu2': self._init_nfsu,
'bo3u': self._init_burnout,
'bo3r': self._init_burnout,
'bop_ps3': self._init_burnout,
'bop_pc': self._init_burnout,
'nfl05': self._init_madden,
'ssx3': self._init_ssx3
}
if game_mode in game_init_map:
game_init_map[game_mode]()
# Protocol state - consolidated
self.client_state = 0x72646972
self.client_flags = self.direct_address = self.direct_port = self.public_key_sent = self.room_flags = 0
self.server_address = ""
self.game_state = 0x4b1
self.protocol_timeout = 0
self.last_protocol_activity = time.time()
self.buddy_config_sent = self.multiplayer_initialized = self.expecting_chal = False
# Consolidated client fields initialization
base_fields = ['ALTS', 'VERS', 'MAC', 'SKU', 'PERS', 'LAST', 'LKEY', 'PLAST', 'MAIL',
'ADDR', 'MADDR', 'BORN', 'PASS', 'PROD', 'SESS', 'SLUS', 'MINSIZE', 'MAXSIZE',
'CUSTFLAGS', 'PARAMS', 'PRIV', 'PERSONAS', 'SEED', 'SYSFLAGS', 'HWFLAG', 'HWMASK',
'DEFPER', 'SDKVER', 'PID', 'CHAN', 'INDEX', 'START', 'RANGE', 'roomNAME', 'roomPASS',
'roomDESC', 'roomMAX', 'moveNAME', 'movePASS', 'NEWS_PAYLOAD', 'pingREF', 'pingTIME',
'FROM', 'TO', 'WHEN', 'TEXT']
for field in base_fields:
attr_name = f"client{field}" if not field.startswith(('room', 'move', 'NEWS', 'ping', 'FROM', 'TO', 'WHEN', 'TEXT')) else field
setattr(self, attr_name, '')
def _init_nascar(self):
self.race_state = 'INACTIVE'
self.race_track = 'DAYTONA'
self.race_laps = '10'
self.race_difficulty = '2'
self.race_start_time = 0
self.lap_times = []
self.race_position = 1
self.race_config = {}
def _init_nbav3(self):
self.street_rank = 1
self.game_mode = 'STREET'
self.character_data = {}
def _init_nfsu(self):
self.car_data = {}
self.current_car = 'default'
self.race_type = 'circuit'
self.drift_score = 0
def _init_burnout(self):
self.crash_mode = False
self.takedown_count = 0
self.vehicle_type = 'car'
def _init_madden(self):
self.team_name = 'Unknown'
self.playbook = 'default'
self.quarter_length = 5
def _init_ssx3(self):
self.boarder_name = 'Unknown'
self.trick_score = 0
self.current_mountain = 'peak'
def update_client_state(self, new_state):
old_state = self.client_state
self.client_state = new_state
self.last_protocol_activity = time.time()
old_state_name = PROTOCOL_STATES.get(old_state, f"UNKNOWN({old_state:08x})")
new_state_name = PROTOCOL_STATES.get(new_state, f"UNKNOWN({new_state:08x})")
print(f"PROTOCOL STATE: {self.connection_id} {old_state_name} -> {new_state_name}")
if new_state == 0x69646c65:
self.protocol_timeout = int(time.time() * 1000) + 300000
elif new_state == 0x61757468:
self.protocol_timeout = int(time.time() * 1000) + 30000
def check_protocol_timeout(self):
if self.protocol_timeout == 0:
return False
current_time = int(time.time() * 1000)
if self.client_state == 0x69646c65:
time_since_activity = (current_time - self.protocol_timeout) / 1000
if time_since_activity > 300:
print(f"PROTOCOL TIMEOUT: {self.connection_id} idle for {time_since_activity:.0f}s")
self.client_state = 0x74696d65
return True
return False
else:
if current_time > self.protocol_timeout:
print(f"PROTOCOL TIMEOUT: {self.connection_id} state {self.client_state:08x}")
self.client_state = 0x74696d65
return True
return False
def update_activity(self):
self.last_activity = time.time()
self.protocol_timeout = int(time.time() * 1000) + 300000
def set_client_flag(self, flag):
self.client_flags |= flag
print(f"PROTOCOL FLAG: {self.connection_id} flags = {self.client_flags:08x}")
def clear_client_flag(self, flag):
self.client_flags &= ~flag
print(f"PROTOCOL FLAG: {self.connection_id} flags = {self.client_flags:08x}")
# System instances
challenge_system = None
auth_handlers = None
session_manager = None
network_handlers = None
ping_manager = None
data_server_manager = None
room_manager = None
room_handlers = None
message_handlers = None
buddy_handlers = None
def send_online_status(session):
"""Send online status to client after authentication"""
if session.connection:
try:
online_packet = create_packet('onln', '', f"S=0\nSTATUS=0\nUSER={session.clientNAME}\nROOM={session.current_room}\n")
session.connection.sendall(online_packet)
print(f"ONLN: Sent online status to {session.clientNAME}")
except Exception as e:
print(f"ONLN: Error sending online status: {e}")
def get_next_data_port():
global current_data_port
with locks['data']:
port = current_data_port
current_data_port = PORTS['data_start'] if current_data_port > PORTS['data_start'] + 1000 else current_data_port + 1
return port
def create_packet(command, subcommand, data):
"""STABLE Handshake/Lobby Header"""
if isinstance(data, str):
data_bytes = data.encode('latin1')
else:
data_bytes = data
# Handle subcommand if it's an int (like 0) or an empty string
if isinstance(subcommand, int):
sub_bytes = b'\x00\x00\x00\x00'
elif not subcommand:
sub_bytes = b'\x00\x00\x00\x00'
else:
# Pad or truncate to exactly 4 bytes
sub_bytes = subcommand.encode('ascii').ljust(4, b'\x00')[:4]
size = len(data_bytes) + 12
header = struct.pack(">4s4sL",
command.encode('ascii'),
sub_bytes,
size)
return header + data_bytes
def create_buddy_packet(command, subcommand, data):
"""
EXACT MATCH for NASCAR 2004 BuddyAPI Hex.
Uses Big-Endian, 4-byte integers, and PAYLOAD-ONLY length.
"""
if isinstance(data, str):
data_bytes = data.encode('latin1')
else:
data_bytes = data
# Ghidra shows BuddyApi TagField functions require the null terminator
if len(data_bytes) == 0 or data_bytes[-1:] != b'\x00':
data_bytes += b'\x00'
# BASED ON HEX: 0x5B (91 bytes) is PAYLOAD ONLY.
payload_size = len(data_bytes)
# Standardize command/sub to exactly 4 bytes
cmd_fixed = command.encode('ascii').ljust(4, b'\x00')[:4]
sub_fixed = subcommand.encode('ascii').ljust(4, b'\x00')[:4]
# ">4s4sI" = Big Endian: 4-byte Cmd, 4-byte Sub, 4-byte PAYLOAD size
header = struct.pack(">4s4sI", cmd_fixed, sub_fixed, payload_size)
return header + data_bytes
# Game-specific handler dispatcher
def handle_game_specific_command(cmd_str, data, session):
"""Route commands to game-specific handlers"""
global current_game_mode
if not current_game_mode or current_game_mode not in GAME_MODES:
print(f"ERROR: No game mode set for command {cmd_str}")
return None
game_handlers = GAME_MODES[current_game_mode]['handlers']
if not game_handlers:
print(f"ERROR: No handlers loaded for game mode {current_game_mode}")
return None
# Dispatch to game-specific handlers
if current_game_mode == 'nascar':
if cmd_str == 'rank':
return game_handlers.handle_rank(data, session)
elif current_game_mode == 'nbav3':
# Map commands to handlers
command_map = {
'gpro': game_handlers.handle_gpro,
'usld': game_handlers.handle_usld,
'uatr': game_handlers.handle_uatr,
'cbal': game_handlers.handle_cbal,
'ccrt': game_handlers.handle_ccrt,
'gqwk': game_handlers.handle_gqwk,
'glea': game_handlers.handle_glea,
'set%': game_handlers.handle_set_percent,
}
# Check direct mapping first
if cmd_str in command_map:
return command_map[cmd_str](data, session)
# Check if it's a data chunk
elif game_handlers.is_hex_continuation(cmd_str):
return game_handlers.handle_data_chunk(cmd_str, data, session)
return None
def update_game_state(session, new_state):
old_state = session.game_state
session.game_state = new_state
print(f"GAME STATE: {session.connection_id} 0x{old_state:04x} -> 0x{new_state:04x}")
def parse_data(data, session):
if not data: return
# Store original data as bytes
if isinstance(data, bytes):
data_bytes = data
else:
data_bytes = str(data).encode('latin1')
lines = data_bytes.split(b'\x0A')
if session.msgType == b'news':
session.NEWS_PAYLOAD = next((line.decode('latin1')[5:] for line in lines if line.startswith(b'NAME')), '')
elif session.msgType == b'~png':
for line in lines:
text = line.decode('latin1')
if text.startswith("REF"): session.pingREF = text[4:]
elif text.startswith("TIME"): session.pingTIME = text[5:]
elif session.msgType == b'room':
for line in lines:
text = line.decode('latin1')
if text.startswith("NAME"): session.roomNAME = text[5:]
elif text.startswith("PASS"): session.roomPASS = text[5:]
elif text.startswith("DESC"): session.roomDESC = text[5:]
elif text.startswith("MAX"): session.roomMAX = text[4:]
elif session.msgType == b'move':
for line in lines:
text = line.decode('latin1')
if text.startswith("NAME"):
session.moveNAME = text[5:] if text[5:] else 'Lobby'
elif text.startswith("PASS"): session.movePASS = text[5:]
elif session.msgType == b'chal':
for line in lines:
text = line.decode('latin1')
if text.startswith("FROM"): session.FROM = text[5:]
elif text.startswith("TO"): session.TO = text[3:]
elif session.msgType == b'mesg':
# Convert to string for debugging
data_str = data_bytes.decode('latin1', errors='ignore') if data_bytes else ""
print(f"MESG DEBUG from {session.clientNAME}:")
print(f" Raw data: {data_str}")
# Check if it's a challenge response
if 'T=ACPT' in data_str or 'T=DECL' in data_str or 'T=BLOC' in data_str:
print(f" CHALLENGE RESPONSE DETECTED!")
# Parse and log all fields
for line in lines:
if line.strip():
print(f" Field: {line.decode('latin1', errors='ignore')}")
for line in lines:
text = line.decode('latin1', errors='ignore')
if text.startswith("N"):
session.mesg_target = text[2:]
elif text.startswith("T"): session.TEXT = text[2:]
elif session.msgType == b'auxi':
for line in lines:
text = line.decode('latin1')
if text.startswith("TEXT"): session.TEXT = text[5:]
elif session.msgType == b'peek':
for line in lines:
text = line.decode('latin1')
if text.startswith("NAME"):
session.peekNAME = text[5:]
print(f"PARSE PEEK: Found NAME='{session.peekNAME}'")
elif session.msgType == b'rank':
for line in lines:
text = line.decode('latin1')
if text.startswith("SET_TRACK"): session.SET_TRACK = text[10:]
elif text.startswith("SET_RACELEN"): session.SET_RACELEN = text[12:]
elif text.startswith("SET_AIDIFF"): session.SET_AIDIFF = text[11:]
elif text.startswith("SET_DAMAGE"): session.SET_DAMAGE = text[11:]
elif text.startswith("SET_RANKED"): session.SET_RANKED = text[11:]
elif text.startswith("SET_SETUPS"): session.SET_SETUPS = text[11:]
elif text.startswith("SET_NUMAI"): session.SET_NUMAI = text[10:]
elif text.startswith("SET_ASSISTS"): session.SET_ASSISTS = text[12:]
elif text.startswith("SET_CAUTIONS"): session.SET_CAUTIONS = text[13:]
elif text.startswith("SET_CONSUME"): session.SET_CONSUME = text[12:]
elif text.startswith("SET_TRACKID"): session.SET_TRACKID = text[12:]
else:
field_map = {
'MID': 'MAC', 'MAC': 'MAC', 'PID': 'PID', 'SKU': 'SKU', 'ALTS': 'ALTS',
'BORN': 'BORN', 'SLUS': 'SLUS', 'VERS': 'VERS', 'NAME': 'NAME', 'USER': 'USER',
'PASS': 'PASS', 'PERS': 'PERS', 'PROD': 'PROD', 'SEED': 'SEED', 'MAIL': 'MAIL',
'LAST': 'LAST', 'LKEY': 'LKEY', 'PRIV': 'PRIV', 'PLAST': 'PLAST', 'MADDR': 'MADDR',
'HWFLAG': 'HWFLAG', 'HWMASK': 'HWMASK', 'DEFPER': 'DEFPER', 'PARAMS': 'PARAMS',
'SDKVER': 'SDKVER', 'MINSIZE': 'MINSIZE', 'MAXSIZE': 'MAXSIZE', 'SYSFLAGS': 'SYSFLAGS',
'CUSTFLAGS': 'CUSTFLAGS', 'PERSONAS': 'PERSONAS', 'FROM': 'FROM', 'TO': 'TO',
'WHEN': 'WHEN', 'TEXT': 'TEXT', 'TOS': 'TOS', 'LANG': 'LANG'
}
for line in lines:
text = line.decode('latin1')
for prefix, field in field_map.items():
if text.upper().startswith(prefix + '='):
value = text[text.find('=') + 1:]
if session.msgType == b'auth' and prefix == 'NAME':
setattr(session, f"client{field}", value)
print(f"PARSE AUTH: Found NAME='{value}'")
break
elif prefix == 'NAME' and session.msgType == b'peek':
setattr(session, f"peek{field}", value)
print(f"PARSE PEEK: Found NAME='{value}' for targeting")
break
elif prefix == 'NAME' and hasattr(session, 'auth_complete') and session.auth_complete:
print(f"PARSE DEBUG: Ignoring NAME='{value}' after authentication")
else:
if value or field in ['PASS', 'TEXT']:
setattr(session, f"client{field}", value)
break
def handle_system_command(data, session):
"""Handle system commands - delegate to challenge system"""
return challenge_system.handle_system_command(data, session)
def handle_onln(data, session):
# STATUS=0 (Available), STATUS=1 (Away), STATUS=2 (In-Game)
user_count = len(session_manager.client_sessions)
response = f"S=0\nSTATUS=0\nUSERS={user_count}\n"
return create_packet('onln', '', response)
def handle_snap(data, session):
data_str = data.decode('latin1') if isinstance(data, bytes) else str(data)
def get_tag(tag):
for line in data_str.split('\n'):
if line.startswith(f"{tag}="): return line.split('=')[1].strip()
return None
chan = get_tag("CHAN")
index = get_tag("INDEX")
find_name = get_tag("FIND")
start = int(get_tag("START") or 0)
# --- LEADERBOARD (CHAN 5) ---
if chan == "5":
# We'll send 3 players for testing
players = ["VTSTech2", "Jeff Gordon", "Tony Stewart"]
for i, name in enumerate(players):
current_rank = start + i + 1
# We use IDENT= to uniquely tag this row, as seen in strings.json
row_payload = (
f"N={name}\n"
f"R={current_rank}\n"
f"V={1000 - (i*100)}\n" # The stat value
f"IDENT={current_rank}\n" # Synchronize row identity
)
print(f"[DEBUG] Sending Row {current_rank}: {name}")
session.connection.sendall(create_packet("+snp", "", row_payload))
# CLOSING PACKET: Mandatory structural tags from strings.json
# LCOUNT = List Total Count, LIDENT = List Identity/Channel
done_payload = (
f"S=0\n"
f"CHAN={chan}\n"
f"COUNT={len(players)}\n"
f"LCOUNT={len(players)}\n"
f"LIDENT={chan}\n"
)
print(f"[DEBUG] Closing CHAN 5 with COUNT={len(players)}")
session.connection.sendall(create_packet("snap", "", done_payload))
return None
# --- PROFILE (CHAN 4) ---
elif chan == "4":
# Profile screens are single-entry 'snapshots'
user_row = (
f"N={find_name or 'VTSTech2'}\n"
"R=1\nW=50\nL=10\nS=60\nP=5\n"
"T5=20\nT10=40\nLL=500\nLC=1200\n"
"STRK=2\nAS=10\nAF=5\n"
)
session.connection.sendall(create_packet("+snp", "", user_row))
session.connection.sendall(create_packet("snap", "", "S=0\n"))
return None
return create_packet("snap", "", "S=0\n")
def handle_rept(data, session):
data_str = data.decode('latin1') if data else ""
print(f"REPT: Report from {session.clientNAME}")
# Parse PERS field if present
for line in data_str.split('\n'):
if line.startswith('PERS='):
persona = line[5:]
print(f"REPT: Persona report for {persona}")
return create_packet('rept', '', "S=0\nSTATUS=0\n")
def handle_tic(data, session):
pass
def reply_play(data, session):
# 1. Generate the 272-byte blob using the new packer
# We find the target session to get their info if needed
target_session = session_manager.get_session_by_persona(session.challenge_target)
binary_blob = challenge_system.create_272_byte_session_data(session, target_session)
# 2. Push the binary blob via +ses
# Note: +ses is a broadcast-style command (no sub-command)
ses_packet = create_packet('+ses', '', binary_blob)
session.connection.sendall(ses_packet)
if target_session:
target_session.connection.sendall(ses_packet)
# 3. Standard play response
response = "SELF=1\nHOST=1\nSTATUS=0\n"
return create_packet('play', '', response)
def send_multiplayer_initialization(session):
"""Send multiplayer initialization sequence AFTER room join"""
if session.multiplayer_initialized:
print(f"MULTIPLAYER: Already initialized for {session.clientNAME}")
return
print(f"\n=== MULTIPLAYER INIT for {session.clientNAME} (in room: {session.current_room}) ===")
# 1. Send 272-byte session data
print(" Step 1: Sending 272-byte session data (+ses)")
# Use challenge_system's method
if challenge_system and hasattr(challenge_system, 'create_272_byte_session_data'):
session_data = challenge_system.create_272_byte_session_data(session, session)
else:
# Fallback to local function (you'll need to define it or keep it)
session_data = create_272_byte_session_data(session, session)
if session_data:
ses_packet = create_packet('+ses', '', session_data)
try:
session.connection.sendall(ses_packet)
print(f" Success: Sent 272-byte session data to {session.clientNAME}")
except Exception as e:
print(f" Error sending session data: {e}")
return
else:
print(f" Error: Failed to create session data")
return
time.sleep(0.5)
print(f"=== MULTIPLAYER INIT COMPLETE ===\n")
session.multiplayer_initialized = True
session.expecting_chal = True
def handle_mesg_command(data, session):
"""Route mesg commands: challenge messages -> challenge system, others -> message system"""
# First try challenge system
challenge_response = challenge_system.handle_mesg(data, session)
if challenge_response is None:
# Not a challenge message, send to message system
print(f"MESG: Routing to message system (non-challenge message)")
return message_handlers.handle_mesg(data, session)
else:
# Challenge system handled it
return challenge_response
def build_reply(data, session):
cmd_str = session.msgType.decode('latin1') if isinstance(session.msgType, bytes) else str(session.msgType)
game_response = handle_game_specific_command(cmd_str, data, session)
if game_response:
return game_response
handlers = {
'@dir': lambda d, s: network_handlers.handle_dir_command(d, s),
'@tic': handle_tic,
'addr': lambda d, s: network_handlers.handle_addr_command(d, s),
'peek': lambda d, s: room_handlers.handle_peek(d, s),
'skey': lambda d, s: network_handlers.handle_skey(s),
'news': lambda d, s: network_handlers.handle_news(d, s),
'~png': lambda d, s: ping_manager.handle_ping(d, s),
'auth': lambda d, s: auth_handlers.handle_auth(d, s),
'acct': lambda d, s: auth_handlers.handle_acct(d, s),
'cper': lambda d, s: auth_handlers.handle_cper(d, s),
'dper': lambda d, s: auth_handlers.handle_dper(d, s),
'pers': lambda d, s: auth_handlers.handle_pers(d, s),
'user': lambda d, s: challenge_system.handle_user(d, s),
'edit': lambda d, s: auth_handlers.handle_edit(d, s),
'sele': lambda d, s: room_handlers.handle_sele(d, s),
'room': lambda d, s: room_handlers.handle_room(d, s),
'move': lambda d, s: room_handlers.handle_move(d, s),
'chal': lambda d, s: challenge_system.handle_chal(d, s),
'auxi': lambda d, s: challenge_system.handle_auxi(d, s),
'mesg': lambda d, s: challenge_system.handle_mesg(d, s),
'play': reply_play,
'sysc': lambda d, s: challenge_system.handle_system_command(d, s),
'onln': handle_onln,
'snap': handle_snap,
'rept': handle_rept,
'gqwk': lambda d, s: handle_game_specific_command('gqwk', d, s),
'glea': lambda d, s: handle_game_specific_command('glea', d, s),
'ccrt': lambda d, s: handle_game_specific_command('ccrt', d, s),
'RGET': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
'ROST': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
'PGET': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
'RADD': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
'RDEL': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
'BLOC': lambda d, s: buddy_handlers.handle_buddy_command(d, s),
}
if cmd_str in handlers:
parse_data(data, session)
return handlers[cmd_str](data, session)
print(f"UNKNOWN COMMAND: {cmd_str}")
return create_packet(cmd_str, '', "S=0\nSTATUS=0\n")
def threaded_client(connection, address, socket_type):
global session_manager, ping_manager, data_server_manager, room_manager, challenge_system
connection_id = f"conn_{uuid.uuid4().hex[:8]}"
session = session_manager.create_session(connection_id)
session.connection = connection
session_manager.add_session(connection_id, session)
thread_count = session_manager.increment_thread_count()
print(f'New {socket_type} connection: {connection_id} from {address[0]}:{address[1]} (Thread: {thread_count})')
try:
connection.settimeout(500)
# BUDDY SOCKET HANDLING
if socket_type == 'Buddy':
print(f"BUDDY: Starting buddy protocol for {connection_id}")
while True:
session.curr_time = time.time()
if session.check_protocol_timeout():
print(f"BUDDY PROTOCOL: Timeout detected for {connection_id}")
timeout_response = create_packet('time', '', "S=0\nSTATUS=0\nERROR=Protocol timeout\n")
try:
connection.sendall(timeout_response)
except:
pass
break
try:
header = connection.recv(12)
session.NO_DATA = False
session.update_activity()
except socket.timeout:
session.NO_DATA = True
time.sleep(0.1)
continue
except (socket.error, OSError) as e:
print(f"BUDDY: Connection error {connection_id}: {e}")
break
if not header:
print(f"BUDDY: Connection closed by client {connection_id}")
break
session.msgType = header[:4]
session.msgSubType = header[4:8]
session.msgSize = (header[10] + header[11]) - 12
if header[10] == 0:
session.msgSize = header[11] - 12
if session.msgSize == 1:
session.msgSize += 255 - 12
data = b''
if session.msgSize > 0:
try:
data = connection.recv(session.msgSize)
if not data:
print(f"BUDDY: Connection closed during data receive {connection_id}")
break
except (socket.error, OSError) as e:
print(f"BUDDY: Error receiving data {connection_id}: {e}")
break
cmd_str = session.msgType.decode('latin1') if isinstance(session.msgType, bytes) else str(session.msgType)
print(f"BUDDY RECV from {connection_id}: {cmd_str}")
# Use buddy command handler for all buddy socket commands
reply = buddy_handlers.handle_buddy_command(cmd_str, data, session)
if reply:
try:
connection.sendall(reply)
except (socket.error, OSError) as e:
print(f"BUDDY: Error sending reply to {connection_id}: {e}")
break
session.update_activity()
time.sleep(0.01)
# GAME SOCKET HANDLING
else:
while True:
session.curr_time = time.time()
if session.check_protocol_timeout():
print(f"PROTOCOL: Timeout detected for {connection_id}")
timeout_response = create_packet('time', '', "S=0\nSTATUS=0\nERROR=Protocol timeout\n")
try:
connection.sendall(timeout_response)
except:
pass
break
if challenge_system:
current_state = challenge_system.ChallengeState_Get(session)
if hasattr(session, 'last_challenge_state') and session.last_challenge_state != current_state:
state_name = challenge_system.states.get(current_state, f"UNKNOWN({current_state:02x})")
print(f"CHALLENGE STATE: {session.connection_id} -> {state_name}")
session.last_challenge_state = current_state
# Update challenge state (handles timeouts)
challenge_system.update_challenge_state(session)
try:
header = connection.recv(12)
session.NO_DATA = False
session.update_activity()
except socket.timeout:
session.NO_DATA = True
time.sleep(0.1)
continue
except (socket.error, OSError) as e:
print(f"Connection error {connection_id}: {e}")
break
if not header:
print(f"Connection closed by client {connection_id}")
break
session.msgType = header[:4]
session.msgSize = (header[10] + header[11]) - 12
if header[10] == 0:
session.msgSize = header[11] - 12
if session.msgSize == 1:
session.msgSize += 255 - 12
data = b''
if session.msgSize > 0:
try:
data = connection.recv(session.msgSize)
if not data:
print(f"Connection closed during data receive {connection_id}")
break
# Check for binary events
if handle_binary_event(data, session):
session.update_activity()
continue
except (socket.error, OSError) as e:
print(f"Error receiving data {connection_id}: {e}")
break
if data:
data_str = data.decode('latin1', errors='ignore')
if session.msgType != b'~png':
print(f"COMMAND: {session.clientNAME} sent {session.msgType}")
print(f" Data: {data_str[:200]}")
if session.msgType != b'~png':
print(f"RECV from {connection_id}: {session.msgType}")
reply = build_reply(data, session)
if reply:
try:
connection.sendall(reply)
except (socket.error, OSError) as e:
print(f"Error sending reply to {connection_id}: {e}")
break
session.update_activity()
# Handle post-command actions in the right sequence
if session.msgType == b'auth' and session.authsent == 1 and not session.ping_initiated:
print(f"AUTH: Sending initial ping to {connection_id}")
time.sleep(0.5)
ping_manager.send_initial_ping(session)
elif session.msgType == b'auth' and session.authsent == 1:
print(f"AUTH: Scheduling automatic PERS response for {connection_id}")
time.sleep(0.3)
current_persona = session.current_persona if session.current_persona else session.clientNAME
# IMPORTANT: Update user presence BEFORE sending PERS response
username = getattr(session, 'authenticated_username', session.clientNAME)
persona_name = current_persona
# Update presence in room manager
if room_manager:
room_manager.update_user_presence(
connection_id,
username,
persona_name,
'Lobby', # Default to Lobby
0, # Room ID 0 = Lobby
True, # Connected
True # Is self
)
print(f"AUTH: Updated presence for {username} in Lobby")
rooms_data = room_handlers.reply_rom(session)
pop_data = room_handlers.reply_pop(session)
client_socket.sendall(rooms_data + pop_data)
response = f"PERS={current_persona}\nS=0\nSTATUS=0\nLAST={time.strftime('%Y-%m-%d %H:%M:%S')}\n"
try:
connection.sendall(create_packet('pers', '', response))
print(f"AUTH: Sent automatic PERS confirmation for {connection_id}")
session.authsent = 2
room_manager.update_user_presence(connection_id,authenticated_username,persona_name,'Lobby',0,True,True)
except (socket.error, OSError) as e:
print(f"Error sending PERS response to {connection_id}: {e}")
break
elif session.msgType == b'pers':
# Client selected persona, send WHO list
time.sleep(0.3)
try:
connection.sendall(room_handlers.reply_who(session))
except (socket.error, OSError) as e:
print(f"Error sending WHO response to {connection_id}: {e}")
break
elif session.msgType == b'move':
# Client joined a room - NOW trigger multiplayer initialization
time.sleep(1.0) # Wait for room system to process
print(f"MOVE DEBUG: moveNAME = '{session.moveNAME}'")
print(f"MOVE DEBUG: active_rooms = {room_manager.active_rooms}")
#if not session.multiplayer_initialized:
#print(f"MOVE: {session.clientNAME} joined room, triggering multiplayer init")
#send_multiplayer_initialization(session)
elif session.msgType == b'room':
# Room creation/update
for response_func in [room_handlers.reply_pop, room_handlers.reply_usr, room_handlers.reply_who]:
time.sleep(0.3)
try:
connection.sendall(response_func(session))
except (socket.error, OSError) as e:
print(f"Error sending room response to {connection_id}: {e}")
break
if session.msgType == b'@dir' and session.data_port > 0:
start_new_thread(data_server_manager.start_data_server, (session,))