-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.py
1773 lines (1546 loc) · 81.4 KB
/
main.py
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
r""" BeaconMC - Python 3
____________________________________________________________
____ ______ _____ ____ _ _ __ __ _____ |
| _ \| ____| /\ / ____/ __ \| \ | | \/ |/ ____| |
| |_) | |__ / \ | | | | | | \| | \ / | | | |
| _ <| __| / /\ \| | | | | | . ` | |\/| | | | |
| |_) | |____ / ____ \ |___| |__| | |\ | | | | |____| |
|____/|______/_/ \_\_____\____/|_| \_|_| |_|\_____| |
|
____________________________________________________________|
Source for dev :
- https://wiki.vg
This project is under the LICENSE.md license."""
# IMPORTS - LIBRAIRIES
import math
import socket as skt
import time as tm
import random as rdm
from typing import Literal
from libs.cryptography_system.system import CryptoSystem as Crypto
from cryptography.hazmat.primitives import serialization, hashes
import threading as thread
import os
import sys
import subprocess
import hashlib
import platform
import pluginapi
import json
from libs import mojangapi as m_api
import struct
import uuid
import traceback
import requests
from base64 import b64encode
from libs import crash_gen
import string
import select
try:
import nbtlib
except ModuleNotFoundError:
print("Installing missing library...")
subprocess.check_call([sys.executable, "-m", "pip", "install", "nbtlib"])
import nbtlib
print("Done")
dt_starting_to_start = tm.time()
lthr = []
if __name__ != "__start__":
print("Please start the server with start.py")
exit(0)
# BASE ERROR
class OSNotCompatibleError(OSError):
pass
class ConfigurationError(Exception):
pass
print(r"""
____ ______ _____ ____ _ _ __ __ _____
| _ \| ____| /\ / ____/ __ \| \ | | \/ |/ ____|
| |_) | |__ / \ | | | | | | \| | \ / | |
| _ <| __| / /\ \| | | | | | . ` | |\/| | |
| |_) | |____ / ____ \ |___| |__| | |\ | | | | |____
|____/|______/_/ \_\_____\____/|_| \_|_| |_|\_____|
""")
print(" (c) BeaconMCDev 2024-2025\n\n")
# Load configuration
_CONFIG = json.loads(open("config.json", "r").read())
whitelist = _CONFIG["whitelist"]
MOTD = _CONFIG["motd"]
PORT = _CONFIG["port"]
IP = _CONFIG["ip"]
MAX_PLAYERS = _CONFIG["max_players"]
ONLINE_MODE = _CONFIG["online_mode"]
lang = _CONFIG["lang"]
DEBUG = _CONFIG["debug_mode"]
ENFORCE_OFFLINE_PROFILES = _CONFIG["enforce_offline_profiles"]
PREVENT_PROXY_CONNEXION = _CONFIG["prevent_proxy_connexion"]
SERVER_LINKS = _CONFIG["links"]
COMPATIBLE_OS = ["Windows", "Linux"]
OS = platform.system()
SERVER_ID = "BeaconMC-" + "".join(rdm.choice(string.ascii_letters + string.digits) for _ in range(10))
if OS in COMPATIBLE_OS:
if OS == "Linux":
SEP = '/'
elif OS == "Windows":
SEP = "\\"
else:
raise OSNotCompatibleError(f"OS {OS} is not compatible ! Please use Linux or Windows !")
# GLOBAL DATAS - VARIABLES
connected_players = 0
blacklisted = []
whitelisted = []
# whitelist = True
users = []
logfile = ""
state = "OFF"
# GLOBAL DATAS - CONSTANTS
# ################################
# ## READ THIS ####
# ## don't touch this section ####
# ################################
SERVER_VERSION = "Alpha-dev" # Version of the server. For debug
CLIENT_VERSION = "1.21.3" # Which version the client must have to connect
PROTOCOL_VERSION = 768 # Protocol version beetween server and client. See https://minecraft.fandom.com/wiki/Protocol_version?so=search for details.
SALT_CHAR = "a-z-e-r-t-y-u-i-o-p-q-s-d-f-g-h-j-k-l-m-w-x-c-v-b-n-A-Z-E-R-T-Y-U-I-O-P-Q-S-D-F-G-H-J-K-L-M-W-X-C-V-B-N-0-1-2-3-4-5-6-7-8-9".split("-")
SALT = ''.join(rdm.choice(SALT_CHAR) for i in range(15))
CONFIG_TO_REQUEST = {"\u00A7": "\xc2\xa7", "§": "\xc2\xa7"}
# log counts
errors = 0
warnings = 0
debug = 0
info = 0
critical = 0
unknow = 0
print("")
def log(msg: str, type: int = -1):
"""Types:
- 0: info
- 1: warning
- 2: error
- 3: debug
- 4: chat
- 100: critical
- other: unknow"""
raise DeprecationWarning("This function is deprecated, please use <server>.getConsole().log() instead.")
global srv
srv.getConsole().log(msg, type)
def gettime():
return tm.asctime(tm.localtime(tm.time())).split(" ")[-2]
def be_ready_to_log():
global logfile
nb = 1
while os.path.exists(f"logs/log{nb}.log"):
nb += 1
logfile = f"logs/log{nb}.log"
def encode(msg: str):
"""Convert quickly a string into bytes that will be sended to the client."""
return msg.encode()
# #######################################################################################################################################################################################################################
# #######################################################################################################################################################################################################################
# #######################################################################################################################################################################################################################
# CLASSES
class MCServer(object):
"""Minecraft server class"""
SERVER_VERSION = SERVER_VERSION
CLIENT_VERSION = CLIENT_VERSION
PROTOCOL_VERSION = PROTOCOL_VERSION
PORT = PORT
IP = IP
ONLINE_MODE = ONLINE_MODE
def __init__(self):
"""Init the server"""
self._console = Console(self)
self.gui_thr = thread.Thread(target=self._console.mainthread, daemon=True)
self.gui_thr.start()
lthr.append(self.gui_thr)
self.socket = skt.socket(skt.AF_INET, skt.SOCK_STREAM) # socket creation
self.socket.bind((IP, PORT)) # bind the socket
self.list_info = []
self.list_clients = []
self.list_worlds = []
self.crypto_sys = Crypto(self)
def worlds_analyse(self):
"""Search for worlds in the worlds folder.
Return a list str that are the world name."""
self.getConsole().log("Analysing worlds...", 3)
items_list = os.listdir(f"{os.getcwd()}{SEP}worlds")
lst_world = []
for item in items_list:
try:
name, extention = item.split(".")
except ValueError:
continue
if extention == ".mcworld":
lst_world.append(name)
self.getConsole().log(f"{len(lst_world)} worlds found !", 3)
return lst_world
def log(self, msg: str, type: int = -1):
"""An alternative of main.log(). Don't delete, used by plugins."""
raise DeprecationWarning("This function is deprecated, please use <server>.getConsole().log() instead.")
self.getConsole().log(msg, type)
def kick(self, client, reason="Kicked by an operator"):
if isinstance(client, Client):
if client in self.list_clients:
if client.connected:
self.getConsole().log(f"Kicking {client.username} ({client.uuid}): {reason}")
client.disconnect(reason)
return True
else:
self.getConsole().log(f"Failed to kick {client.username}: client not connected.", 1)
return False
else:
self.getConsole().log(f"Failed to kick {client.username}: client not registered.", 1)
return False
else:
self.getConsole().log(f"Failed to kick {client}: not a Client instance.", 2)
return False
def banip(self, ip:str=None, client:object=None, username:str=None, reason:str="Banned by an operator"):
if ip != None:
with open("banned-ips.json", "r") as f:
data = json.loads(f.read())
data.append(
{
"ip": ip,
"reason": reason
# other info soon ?
}
)
with open("banned-ips.json", "w") as f:
f.write(json.dumps(data))
elif client != None:
with open("banned-ips.json", "r") as f:
data = json.loads(f.read())
data.append(
{
"ip": client.info,
"reason": reason
# other info soon ?
}
)
with open("banned-ips.json", "w") as f:
f.write(json.dumps(data))
elif username != None:
with open("banned-ips.json", "r") as f:
data = json.loads(f.read())
i = 0
for c in self.list_clients:
if c.username == username:
client = c
i += 1
if i > 1:
raise TwoPlayerWithSameUsernameException()
elif i == 0:
self.getConsole().log(f"Failed to kick {username}: player not found.", 1)
return
elif i == 1:
pass
else:
raise Exception("An unknow exception occured.")
data.append(
{
"ip": c.info,
"reason": reason
# other info soon ?
}
)
with open("banned-ips.json", "w") as f:
f.write(json.dumps(data))
def start(self):
try:
global state
"""Start the server"""
self.getConsole().log("Starting Minecraft server...", 0)
state = "ON"
self.getConsole().log(f"Server version: {SERVER_VERSION}", 3)
self.getConsole().log(f"MC version: {CLIENT_VERSION}", 3)
self.getConsole().log(f"Protocol version: {PROTOCOL_VERSION}", 3)
# WARNING - ANY MODIFICATION IN THIS SECTION WILL GET YOU NOT HELPABLE, PLEASE READ LICENSE.md.
try:
with open("eula.txt", "r") as eula_file:
eula = eula_file.read().split()
if "eula=true" in eula:
pass
else:
# WARNING - ANY MODIFICATION IN THIS SECTION WILL GET YOU NOT HELPABLE, PLEASE READ LICENSE.md.
self.getConsole().log("You need to agree the Minecraft EULA to continue.", 1)
self.getConsole().log("The conditions are readable here : https://www.minecraft.net/fr-ca/eula. To accept it, go to eula.txt and write 'eula=true'.", 1)
self.getConsole().log("The server will not start until the EULA is not accepted, and if this script is modified we will not support or help you.", 1)
self.stop(False, reason="You need to accept Minecraft eula to continue.")
return
except Exception as e:
self.getConsole().log(traceback.format_exc(e), 2)
# WARNING - ANY MODIFICATION IN THIS SECTION WILL GET YOU NOT HELPABLE, PLEASE READ LICENSE.md.
self.getConsole().log("The eula.txt file was not found, or the server was modified !", 1)
self.getConsole().log("You need to agree the Minecraft EULA to continue.", 1)
self.getConsole().log("The conditions are readable here : https://www.minecraft.net/fr-ca/eula. To accept it, go to eula.txt and write 'eula=true'.", 1)
self.getConsole().log("The server will not start until the EULA is not accepted, and if this script is modified we will not support or help you.", 1)
self.stop(False, reason="You need to agree eula to continue.")
return
# self.heartbeat()
self.getConsole().log("Loading plugins... (REMOVED)", 0)
self.load_plugins()
self.getConsole().log("Starting listening...", 0)
self.socket.listen(MAX_PLAYERS + 1) # +1 is for the temp connexions
self.load_worlds()
self.act = thread.Thread(target=self.add_client_thread)
self.act.start()
lthr.append(self.act)
self.main()
except Exception as e:
self.stop(critical=True, reason="An unknow exception occured.", e=e)
def getConsole(self):
return self._console
def load_plugins(self):
"""Load the plugins"""
self.plugin_loader = pluginapi.PluginLoader(server=self)
self.plugin_loader.load_plugins()
def load_worlds(self):
"""Load all of the server's worlds"""
self.getConsole().log("Loading worlds...", 0)
pre_list_worlds = self.worlds_analyse()
for world in pre_list_worlds:
w_class = World(world)
w_class.load()
self.list_worlds.append(w_class)
self.getConsole().log(f"DONE ! Server successfully started on {round(tm.time() - dt_starting_to_start, 2)} seconds.", 0)
def main(self):
"""Main"""
global state
try:
while state == "ON":
tm.sleep(0.1)
for p in self.list_clients:
p: Client
if not p.connected:
self.list_clients.remove(p)
except KeyboardInterrupt:
self.stop()
exit(0)
def stop(self, critical_stop=False, reason="Server closed", e: Exception=None):
"""stop the server"""
if critical_stop:
self.getConsole().log("Critical server stop trigered !", 100)
self.getConsole().log("Stopping the server...", 0)
global state
state = "OFF"
global lthr
self.getConsole().log("Disconnecting all the clients...", 0)
if critical_stop:
for i in self.list_clients:
i: Client
i.disconnect(reason=tr.key("disconnect.server.crash"))
else:
for i in self.list_clients:
i.disconnect(reason=tr.key("disconnect.server.closed"))
self.getConsole().log("Closing socket...", 0)
self.socket.close()
self.getConsole().log("Stopping all tasks...", 0)
for t in lthr:
t: thread.Thread
try:
t.running = False # stop console
except AttributeError:
pass
t.join(timeout=1) if t is not thread.current_thread() else None
lthr.remove(t)
...
# Stop plugins
...
# Save and clear sensitive cryptographic data
self.crypto_sys.stop()
if not (critical_stop):
self.getConsole().log(f"Server closed with {critical} criticals, {errors} errors, {warnings} warnings, {info} infos and {unknow} unknown logs : {reason}", 0)
self.getConsole().log("[Press enter to exit]")
self.getConsole().running = False
exit()
else:
self.getConsole().log(f"Server closed with {critical} criticals, {errors} errors, {warnings} warnings, {info} infos and {unknow} unknown logs : {reason}", 100)
self.crash(reason, e)
self.getConsole().log("[Press enter to exit]")
self.getConsole().running = False
exit(-1)
def crash(self, reason, e: Exception = None):
"""Generate a crash report
Arg:
- reason: str --> The crash message"""
if e == None:
try:
raise Exception(reason)
except Exception as e:
pass
crash_gen.gen_crash_report(CLIENT_VERSION, SERVER_VERSION, e)
return
raise DeprecationWarning("This code should be unreachable, please report us this.")
c = 0
try:
import datetime
t = traceback.format_exc()
except Exception:
t = None
while os.path.exists("crash_reports/crash{0}".format(c)):
c += 1
with open("crash_reports/crash{0}".format(c), "w") as crashfile:
crashfile.write(f"""{datetime.datetime.now()}\nBeaconMC {SERVER_VERSION}\nFor Minecraft {CLIENT_VERSION}\n________________________________________________________________________________________________________________\nCritical error, the server had to stop. This crash report contain informations about the crash.\n________________________________________________________________________________________________________________\nCause of the crash : {reason}\n{traceback.format_exc(e)}\nDebug mode : {DEBUG}\n________________________________________________________________________________________________________________\n{t}""")
def add_client_thread(self):
"""Thread for add clients."""
global state
self.client_id_count = 0
while state == "ON":
try:
client_connection, client_info = self.socket.accept()
except OSError:
tm.sleep(0.1)
continue
cl = Client(client_connection, client_info, self)
# self.list_clients.append(cl)
thr = thread.Thread(target=cl.client_thread, args=[self.client_id_count])
thr.start()
lthr.append(thr)
self.client_id_count += 1
tm.sleep(0.1)
def is_premium(self, username: str):
"""Check if the user is a premium user. Return a boolean"""
import libs.mojangapi as mojangapi
accchecker = mojangapi.Accounts()
return accchecker.check(self.username)
def setblock(self, base_request: bytes):
"""Analyse the setblock request and modify a block"""
id = base_request[0]
x = base_request[1:2]
y = base_request[3:4]
z = base_request[5:6]
mode = base_request[7]
block = base_request[8]
# check the request
if id != "\x05":
self.getConsole().log("A non-setblock request was sent to the bad method. Something went wrong. Please leave an issue on GitHub or on Discord !", 100)
self.stop(critical=True, reason="A non-setblock request was sent to the bad method. Something went wrong. Please leave an issue on GitHub or on Discord !")
raise RequestAnalyseException("Exception on analysing a request : bad method used (setblock andnot unknow).")
# TODO: Modify the block in the world
...
# TODO: send to every clients the modification
...
def post_to_chat(self, message: str, author: str = ""):
"""Post a message in all player's chat
Args:
- message: str --> the message to send
- author: str --> the author of the message: by default ""."""
if author == "":
msg = message
else:
msg = f"<{author}>: {message}"
for p in self.list_clients:
p: Client
p.send_msg_to_chat(msg)
self.getConsole().log(msg, 4)
def mp(self, message: str, addressee: str, author: str):
"""Send a mp to 1 player
Args:
- message:str --> the message to send in mp
- addressee:str --> player that will receive msg
- author:str --> the author of the msg: by default ""."""
pl = self.find_player_by_username(addressee)
msg = f"{author} --> you: {message}"
pl.send_msg_to_chat(msg)
self.getConsole().log(f"{author} --> {pl}: {message}", 4)
for pl in self.PLUGIN_LIST:
pl.on_mp(message=message, source=author, addressee=addressee)
def find_player_by_username(self, username:str):
"""Find the player socket with the username.
Arg:
- username:str --> the username of the player.
- Returns player socket
- return None if no player found
- Raise error if more than 1 player is found"""
lst = []
for p in self.list_clients:
if p.username == username:
lst.append(p)
if len(lst) == 0:
return None
elif len(lst) == 1:
return lst[0]
else:
raise TwoPlayerWithSameUsernameException(f"2 players with the same username {username} were found.")
class PacketException(Exception):
pass
class PrefixedArray(object):
def __init__(self, array:tuple|list):
self.data = []
for i in array:
self.data.append(i)
self.lenth = len(self.data)
def happend(self, data):
self.data.happend(data)
def encode(self):
self.lenth = len(self.data)
elenth = Packet(None, None).pack_varint(self.lenth)
prefixlenth = Packet(None, None).pack_varint(len(elenth))
end = prefixlenth + elenth
for i in self.data:
end += Packet(None, None).pack(i)
return end
class Packet(object):
# DANGER | DO NOT TOUCH
SEGMENT_BITS = 0x7F
CONTINUE_BIT = 0x80
def __init__(self, socket: skt.socket,
direction: Literal["-OUTGOING", "-INCOMING"], typep: hex = None,
packet: bytes = None, args: tuple = None):
self.type = typep
self.socket = socket
self.direction = direction
self.packet = packet
self.args = args
# if packet == None or b"" and typep == None:
# raise PacketException(f"No information provided in the Packet instance {self}")
if direction == "-INCOMING":
self.incoming_packet()
elif direction == "-OUTGOING":
self.outgoing_packet()
def incoming_packet(self):
self.unpack()
def unpack_uuid(self, uuid):
if len(uuid) != 16:
raise ValueError(f"invalid lenth {len(uuid)} for binary uuid")
hex_uuid = uuid.hex()
uuid_format = f"{hex_uuid[:8]}-{hex_uuid[8:12]}-{hex_uuid[12:16]}-{hex_uuid[16:20]}-{hex_uuid[20:]}"
return uuid_format
def wait_for_packet(self):
if self.type == "-INCOMING":
self.lenth = self.unpack_varint(self.socket.recv(1))
tc = self.lenth
if self.lenth <= 0:
raise PacketException("NullPacket")
self.id = self.unpack_varint(self.socket.recv(1))
tc -= 1
if self.id == 0:
# 2 more possibles cases
...
else:
raise PacketException("Wating to receive packet in -OUTGOING mode")
def unpack(self):
lenth = self.packet[0]
id = self.packet[1]
other = self.packet[2:]
self.type = id
self.args = other
return lenth
def outgoing_packet(self):
...
def pack_varint(self, d: int):
o = b""
# if d >= 255:
# o = d.to_bytes(2, byteorder="little")
# else:
# test
if True:
while True:
b = d & 0x7F
d >>= 7
o += struct.pack("B", b | (0x80 if d > 0 else 0))
if d == 0:
break
return o
def unpack_varint(self, data, debug=False):
if debug:
srv.getConsole().log(f"Data : {data}", 3)
d = 0
for i in range(5):
b = data[i]
d |= (b & 0x7F) << (7 * i)
if not b & 0x80:
break
return d
def pack_data(self, d):
h = self.pack_varint(len(d))
if isinstance(d, str):
d = bytes(d, "utf-8")
return h + d
def send(self):
if self.direction == "-OUTGOING":
self.socket.send(self.__repr__())
else:
raise PacketException("Incoming packet tryied to be sended")
def pack(self, i) -> bytes:
if isinstance(i, int):
return self.pack_varint(i)
elif isinstance(i, PrefixedArray):
return i.encode()
elif isinstance(i, UUID):
return self.pack_uuid(i.uuid)
elif isinstance(i, bool):
if i:
return b"\x01"
else:
return b"\x00"
elif isinstance(i, tuple) or isinstance(i, list):
x = b""
for j in i:
x += self.pack(j)
return self.pack(len(i)) + x
elif isinstance(i, bytes):
return self.pack_varint(len(i)) + i
elif isinstance(i, bytearray):
return self.pack_varint(len(bytes(i))) + bytes(i)
elif isinstance(i, str):
return self.pack_data(i)
else:
return self.pack_data(i)
def __repr__(self) -> bytes:
out = self.pack_varint(self.type) # pack the type
for i in self.args:
out += self.pack(i)
out = self.pack_varint(len(out)) + out
return out
def pack_uuid(self, uuid_to_pack):
return uuid.UUID(uuid_to_pack).bytes
def __str__(self):
return self.__repr__().decode()
########################################################################################################################################################################################################################
########################################################################################################################################################################################################################
########################################################################################################################################################################################################################
class UUID(object):
def __init__(self, uuid):
self.uuid = uuid
class Client(object):
def __init__(self, connexion: skt.socket, info, server: MCServer):
self.connexion = connexion
self.info = info
self.server = server
self.is_op = False
self.x = None
self.y = None
self.z = None
self.connected = True
self.protocol_state = "Handshaking"
self.encrypted = False
self.authenticated = False
self.configured = False
def on_heartbeat(self):
"""Id of the packet: 0x00"""
client_protocol_version = self.request[1:]
...
def on_login_start(self):
"""Starting the login in (rq C --> S)"""
self.request
...
def sha1_hash_digest(self, hash):
number_representation = self._number_from_bytes(hash.digest(), signed=True)
return format(number_representation, 'x')
def _number_from_bytes(self, b, signed=False):
try:
return int.from_bytes(b, byteorder='big', signed=signed)
except AttributeError:
if len(b) == 0:
b = b'\x00'
num = int(str(b).encode('hex'), 16)
if signed and (ord(b[0]) & 0x80):
num -= 2 ** (len(b) * 8)
return num
def load_properties(self):
if ONLINE_MODE:
if PREVENT_PROXY_CONNEXION:
ip_field = self.info
else:
ip_field = ""
try:
response = requests.get(url="https://sessionserver.mojang.com/session/minecraft/hasJoined", params={"username": self.username, "serverId": SERVER_ID, "ip": ip_field})
except TimeoutError:
self.server.getConsole().log("Authentification servers didn't responded on time !", 1)
self.disconnect("Time out with mojang auth servers. Are they online ?")
return
except requests.HTTPError as e:
self.server.getConsole().log("An unexcepted exception occured with authentification servers !", 2)
self.server.getConsole().log(traceback.format_exc(e), 2)
self.disconnect("HTTP Exception with auth servers, are they online ?")
return
except ConnectionError:
self.server.getConsole().log("Exception while connecting to auth servers.", 2)
self.disconnect("Exception while connecting to the mojang auth servers.")
return
except Exception as e:
self.server.getConsole().log("Unknow exception while contacting auth servers.", 2)
self.server.getConsole().log(traceback.format_exc(e), 2)
self.disconnect("Failed to login with auth servers (internal exception).")
assert isinstance(response, requests.Response)
if response.status_code == 204:
self.server.getConsole().log("Mojang authentification server responded by 204 http status !", 1)
self.disconnect("Invalid response from authentifications servers.")
return
api_response = json.loads(response.content)
if response.status_code != 200:
if response.status_code == 403:
self.disconnect(f"Failed to login: {api_response['error']}.")
else:
self.disconnect("Failed to login.")
return
self.properties = api_response["properties"]
list_prop = []
for p in self.properties:
list_prop.append("name")
list_prop.append(p["name"])
list_prop.append("value")
list_prop.append(p["value"])
try:
sig = p["signature"] # potential kry error
list_prop.append("signature")
list_prop.append(sig)
except KeyError:
pass
array = PrefixedArray(list_prop)
parg = [UUID(self.uuid), self.username, array]
else:
parg = [UUID(self.uuid), self.username, PrefixedArray(["name", "textures", "value", "eyJ0aW1lc3RhbXAiOjE1OTAwMDAwMDAsInByb2ZpbGVJZCI6IjAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAiLCJwcm9wZXJ0aWVzIjpbeyJrZXkiOiJUZXh0dXJlcyIsInZhbHVlIjoieyJTS0lOIjp7InVybCI6Imh0dHBzOi8vc2Vzc2lvbnMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzE2YTQ4Njc0YzMwMmRjM2VhNzZjZmZhZjMyMmQ5MmJmZjBjMDI5ZTZhOGY4MTk4ZDczZjMzYjRhZDdkMzY2ZjAifX19"])]
response = Packet(self.connexion, "-OUTGOING", 2, args=parg)
self.server.getConsole().log(response.__repr__(), 3)
response.send()
self.server.list_clients.append(self)
def client_thread(self, id):
"""Per client thread"""
self.id = id
try:
self.server.getConsole().log(f"New client from {self.info}", 3)
self.server.getConsole().log("Starting listening loop in Handshaking state", 3)
# Ping / Auth loop (to developp)
d_reason = "None"
misc_d = True
while self.connected and state == "ON":
# Auth loop
try:
num_read = 0
lenth = 0
while True:
byte = self.connexion.recv(1)
if not byte:
return None
byte = byte[0]
lenth |= (byte & 0x7F) << (7 * num_read)
num_read += 1
if not (byte & 0x80):
break
if num_read > 5:
raise ValueError("Varint too big")
if lenth == b"":
continue
if self.encrypted:
self.request = self.server.crypto_sys.decode(self.connexion.recv(lenth), self.shared_secret)
else:
self.request = Packet.pack_varint(None, lenth) + self.connexion.recv(lenth)
except ConnectionResetError:
self.server.getConsole().log(f"Client {self.info} disconnected : Connexion reset.")
if self.request == "":
continue
self.server.getConsole().log(f"Receiving serverbound packet : {self.request}", 3)
self.packet = Packet(self.connexion, "-INCOMING", packet=self.request)
self.server.getConsole().log(f"Packet ID : {self.packet.type}", 3)
self.server.getConsole().log(f"Protocol state : {self.protocol_state}", 3)
if self.protocol_state == "Handshaking":
if self.packet.type == 0:
if self.packet.args[-1] == 1:
# Switch protocol state to status
self.protocol_state = "Status"
self.server.getConsole().log(f"Switching to Status state for {self.info}", 3)
continue
elif self.packet.args[-1] == 2:
# Switch protocol state to login
self.protocol_state = "Login"
self.protocol_version = Packet.unpack_varint(None, self.packet.args[0:2])
self.server.getConsole().log(f"Switching to login state for {self.info}", 3)
continue
elif self.packet.args[-1] == 3:
# Switch protocol state to transfer
self.protocol_state = "Transfer"
self.server.getConsole().log(f"Switching to transfer state for {self.info}", 3)
continue
else:
self.connected = False
self.connected = False
self.server.getConsole().log(f"Disconnecting {self.info} : protocol error (unknow next state {self.packet.args[-1]} in handshake)", 3)
break
elif self.protocol_state == "Status":
if self.packet.type == 0:
# Status request -> Status response (SLP)
self.SLP()
continue
elif self.packet.type == 1:
pong_packet = self.packet
pong_packet.direction = "-OUTGOING"
pong_packet.send()
# payload = self.packet.args[0]
# self.ping_response(payload)
self.connected = False
break
elif self.protocol_state == "Login":
if self.packet.type == 0:
if self.protocol_version != PROTOCOL_VERSION:
self.disconnect(f"Please try to connect using Minecraft {CLIENT_VERSION}")
return
unamelenth = self.packet.args[0]
i = 1
self.username = ""
while i <= unamelenth:
sb = self.packet.args[i:i+1]
self.username += sb.decode("utf-8")
i += 1
#i = 0
self.uuid = self.packet.unpack_uuid(uuid=self.packet.args[i:])
self.server.getConsole().log(f"UUID of {self.username} is {self.uuid}.", 0)
self.server.getConsole().log(f"{self.username} is logging in from {self.info}.", 0)
for player in self.server.list_clients:
if self.username == player.username or self.uuid == player.uuid:
if i == 1:
self.server.getConsole().log(f"{self.username} is already connected !", 1)
if not(ONLINE_MODE) and ENFORCE_OFFLINE_PROFILES:
if self.info == player.info:
self.connected = False
misc_d = False
d_reason = tr.key("disconnect.username.conflict.offline.sameip")
else:
self.server.getConsole().log("Banning the player for security reason: the server is running offline mode.", 1)
self.server.banip(ip=self.info, reason=tr.key("disconnect.username.conflict.offline.dif_ip"))
self.server.banip(ip=player.info, reason=tr.key("disconnect.username.conflict.offline.dif_ip"))
self.server.kick(player, tr.key("disconnect.username.conflict.offline.dif_ip"))
else:
self.connected = False
misc_d = False
d_reason = tr.key("disconnect.username.conflict.online")
break
else:
i += 1
with open("banned-ips.json", "r") as f:
banedips = json.loads(f.read())
for bip in banedips:
if bip["ip"] == self.info:
self.connected = False
misc_d = False
reason = {bip['reason']}
d_reason = tr.key("disconnect.ban.ip")
self.server.getConsole().log(f"{self.username}'s IP is banned. Disconnecting...", 0)
break
with open("banned-players.json", "r") as f:
banedacc = json.loads(f.read())
for bacc in banedacc:
if bacc["username"] == self.info:
self.connected = False
misc_d = False
reason = {bacc['reason']}
d_reason = tr.key("disconnect.ban.account")
self.server.getConsole().log(f"{self.username} is banned. Disconnecting...", 0)
break
if len(self.server.list_clients) >= MAX_PLAYERS:
self.connected = False
misc_d = False
d_reason = tr.key("disconnect.full")
continue
if whitelist:
with open ("whitelist.json", "r") as wf:
data = json.loads(wf.read())
o = 0
for d in data:
if d["uuid"] == self.uuid:
o += 1
if o != 1:
self.connected = False
d_reason = tr.key("disconnect.whitelist")
misc_d = False
if o > 1:
self.server.getConsole().log("User is whitelisted more than 1 time !", 1)
continue
if ONLINE_MODE:
api_system = m_api.Accounts()
check_result = api_system.authenticate(self.username, self.uuid)
if check_result[0]:
self.server.getConsole().log(f"successfully authenticated {self.username}.", 3)
self.authenticated = True
pass
else:
self.server.getConsole().log(f"Failed to authenticate {self.info} using uuid {self.uuid} and username {self.username}.", 1)
self.connected = False
d_reason = tr.key("disconnect.login.failed")
misc_d = False
break
# temp
# self.load_properties()
# continue
# Encryption request
verify_token = bytearray()
for i in range(4):
verify_token.append(rdm.randint(0, 255))
resp_pack = Packet(self.connexion, "-OUTGOING", typep=1, args=("",
bytearray(self.server.crypto_sys.__public_key__.public_bytes(encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo)),
verify_token))
resp_pack.send()
continue