forked from Igoorx/PyRoyale
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
358 lines (284 loc) · 12.4 KB
/
server.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
import os
import sys
if sys.version_info.major != 3:
sys.stderr.write("You need python 3.7 or later to run this script\n")
if os.name == 'nt': # Enforce that the window opens in windows
print("Press ENTER to exit")
input()
exit(1)
from twisted.python import log
log.startLogging(sys.stdout)
from autobahn.twisted import install_reactor
# we use an Autobahn utility to import the "best" available Twisted reactor
reactor = install_reactor(verbose=False,
require_optimal_reactor=False)
from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
from twisted.internet.protocol import Factory
import json
import random
import hashlib
import traceback
import configparser
from buffer import Buffer
from player import Player
from match import Match
class MyServerProtocol(WebSocketServerProtocol):
def __init__(self, server):
WebSocketServerProtocol.__init__(self)
self.server = server
self.address = str()
self.recv = bytes()
self.pendingStat = None
self.stat = str()
self.player = None
self.blocked = bool()
self.dcTimer = None
def startDCTimer(self, time):
self.stopDCTimer()
self.dcTimer = reactor.callLater(time, self.transport.loseConnection)
def stopDCTimer(self):
try:
self.dcTimer.cancel()
except:
pass
def onConnect(self, request):
#print("Client connecting: {0}".format(request.peer))
if "x-real-ip" in request.headers:
self.address = request.headers["x-real-ip"]
def onOpen(self):
#print("WebSocket connection open.")
if not self.address:
self.address = self.transport.getPeer().host
self.startDCTimer(25)
self.setState("l")
def onClose(self, wasClean, code, reason):
#print("WebSocket connection closed: {0}".format(reason))
self.stopDCTimer()
if self.stat == "g" and self.player != None:
self.server.players.remove(self.player)
self.player.match.removePlayer(self.player)
self.player.match = None
self.player = None
self.pendingStat = None
self.stat = str()
def onMessage(self, payload, isBinary):
if len(payload) == 0:
return
self.server.messages += 1
try:
if isBinary:
self.recv += payload
while len(self.recv) > 0:
self.onBinaryMessage()
else:
self.onTextMessage(payload.decode('utf8'))
except Exception as e:
traceback.print_exc()
self.transport.loseConnection()
self.recv = bytes()
return
def sendJSON(self, j):
self.sendMessage(json.dumps(j).encode('utf-8'), False)
def sendBin(self, code, buff):
msg=Buffer().writeInt8(code).write(buff.toBytes() if isinstance(buff, Buffer) else buff).toBytes()
self.sendMessage(msg, True)
def loginSuccess(self):
self.sendJSON({"packets": [
{"name": self.player.name, "team": self.player.team, "sid": "i-dont-know-for-what-this-is-used", "type": "l01"}
], "type": "s01"})
def setState(self, state):
self.stat = self.pendingStat = state
self.sendJSON({"packets": [
{"state": state, "type": "s00"}
], "type": "s01"})
def exception(self, message):
self.sendJSON({"packets": [
{"message": message, "type": "x00"}
], "type": "s01"})
def block(self, reason):
if self.blocked:
return
print("Player blocked: {0}".format(self.player.name))
self.blocked = True
if not self.player.dead:
self.player.match.broadBin(0x11, Buffer().writeInt16(self.player.id), self.player.id) # KILL_PLAYER_OBJECT
self.server.blockAddress(self.address, self.player.name, reason)
def onTextMessage(self, payload):
#print("Text message received: {0}".format(payload))
packet = json.loads(payload)
type = packet["type"]
if self.stat == "l":
if type == "l00": # Input state ready
if self.pendingStat is None:
self.transport.loseConnection()
return
self.pendingStat = None
self.stopDCTimer()
if self.address != "127.0.0.1" and self.server.getPlayerCountByAddress(self.address) >= self.server.maxSimulIP:
self.exception("Too many connections")
self.transport.loseConnection()
return
for b in self.server.blocked:
if b[0] == self.address:
self.blocked = True
team = packet["team"][:3].strip().upper()
if len(team) == 0:
team = self.server.defaultTeam
self.player = Player(self,
packet["name"],
team,
self.server.getMatch(team, packet["private"] if "private" in packet else False))
self.loginSuccess()
self.server.players.append(self.player)
self.setState("g") # Ingame
elif self.stat == "g":
if type == "g00": # Ingame state ready
if self.player is None or self.pendingStat is None:
self.transport.loseConnection()
return
self.pendingStat = None
self.player.onEnterIngame()
elif type == "g03": # World load completed
if self.player is None:
self.transport.loseConnection()
return
self.player.onLoadComplete()
elif type == "g50": # Vote to start
if self.player is None or self.player.voted or self.player.match.playing:
return
self.player.voted = True
self.player.match.voteStart()
elif type == "g51": # (SPECIAL) Force start
if self.server.mcode and self.server.mcode in packet["code"]:
self.player.match.start(True)
def onBinaryMessage(self):
pktLenDict = { 0x10: 6, 0x11: 0, 0x12: 12, 0x13: 1, 0x17: 2, 0x18: 4, 0x19: 0, 0x20: 7, 0x30: 7 }
code = self.recv[0]
if code not in pktLenDict:
#print("Unknown binary message received: {1} = {0}".format(repr(self.recv[1:]), hex(code)))
self.recv = bytes()
return False
pktLen = pktLenDict[code] + 1
if len(self.recv) < pktLen:
return False
pktData = self.recv[1:pktLen]
self.recv = self.recv[pktLen:]
b = Buffer(pktData)
if not self.player.loaded or self.blocked or (not self.player.match.closed and self.player.match.playing):
self.recv = bytes()
return False
self.player.handlePkt(code, b, pktData)
return True
class MyServerFactory(WebSocketServerFactory):
def __init__(self, url):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"server.cfg"), "r") as f:
self.configHash = hashlib.md5(f.read().encode('utf-8')).hexdigest()
self.readConfig(self.configHash)
WebSocketServerFactory.__init__(self, url.format(self.listenPort))
self.players = list()
self.matches = list()
self.curse = list()
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"words.json"), "r") as f:
self.curse = json.loads(f.read())
except:
pass
self.blocked = list()
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"blocked.json"), "r") as f:
self.blocked = json.loads(f.read())
except:
pass
self.messages = 0
reactor.callLater(5, self.generalUpdate)
def readConfig(self, cfgHash):
self.configHash = cfgHash
config = configparser.ConfigParser()
config.read('server.cfg')
self.listenPort = config.getint('Server', 'ListenPort')
self.mcode = config.get('Server', 'MCode').strip()
self.statusPath = config.get('Server', 'StatusPath').strip()
self.defaultName = config.get('Server', 'DefaultName').strip()
self.defaultTeam = config.get('Server', 'DefaultTeam').strip()
self.maxSimulIP = config.getint('Server', 'MaxSimulIP')
self.playerMin = config.getint('Match', 'PlayerMin')
self.playerCap = config.getint('Match', 'PlayerCap')
self.startTimer = config.getint('Match', 'StartTimer')
self.enableVoteStart = config.getboolean('Match', 'EnableVoteStart')
self.voteRateToStart = config.getfloat('Match', 'VoteRateToStart')
self.allowLateEnter = config.getboolean('Match', 'AllowLateEnter')
self.worlds = config.get('Match', 'Worlds').strip().split(',')
def generalUpdate(self):
playerCount = len(self.players)
print("pc: {0}, mc: {1}, mp5s: {2}".format(playerCount, len(self.matches), self.messages))
self.messages = 0
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"server.cfg"), "r") as f:
cfgHash = hashlib.md5(f.read().encode('utf-8')).hexdigest()
if cfgHash != self.configHash:
self.readConfig(cfgHash)
print("Configuration reloaded.")
except:
print("Failed to reload configuration.")
if self.statusPath:
try:
with open(self.statusPath, "w") as f:
f.write('{"active":' + str(playerCount) + '}')
except:
pass
reactor.callLater(5, self.generalUpdate)
def checkCurse(self, str):
if len(str) <= 3:
return False
str = str.lower()
for w in self.curse:
if len(w) <= 3:
continue
if w in str:
return True
return False
def blockAddress(self, address, playerName, reason):
if not address in self.blocked:
self.blocked.append([address, playerName, reason])
try:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),
"blocked.json"), "w") as f:
f.write(json.dumps(self.blocked))
except:
pass
def getPlayerCountByAddress(self, address):
count = 0
for player in self.players:
if player.client.address == address:
count += 1
return count
def buildProtocol(self, addr):
protocol = MyServerProtocol(self)
protocol.factory = self
return protocol
def getMatch(self, roomName, private):
if roomName == "":
private = False
fmatch = None
for match in self.matches:
if not match.closed and len(match.players) < self.playerCap and private == match.private and (not private or match.roomName == roomName):
if not self.allowLateEnter and match.playing:
continue
fmatch = match
break
if fmatch == None:
fmatch = Match(self, roomName, private)
self.matches.append(fmatch)
return fmatch
def removeMatch(self, match):
if match in self.matches:
self.matches.remove(match)
if __name__ == '__main__':
factory = MyServerFactory(u"ws://127.0.0.1:{0}/royale/ws")
# factory.setProtocolOptions(maxConnections=2)
reactor.listenTCP(factory.listenPort, factory)
reactor.run()