forked from StarryPy/StarryPy-Python2-Deprecated
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
675 lines (568 loc) · 21.6 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
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
# -*- coding: UTF-8 -*-
from _socket import SHUT_RDWR
import gettext
import locale
import logging
from uuid import uuid4
import sys
import socket
import datetime
import construct
from twisted.internet import reactor
from twisted.internet.error import CannotListenError
from twisted.internet.protocol import ClientFactory, ServerFactory, Protocol, connectionDone
from construct import Container
import construct.core
from twisted.internet.task import LoopingCall
from config import ConfigurationManager
from packet_stream import PacketStream
import packets
from plugin_manager import PluginManager, route, FatalPluginError
from utility_functions import build_packet
VERSION = "1.3.2"
def port_check(upstream_hostname, upstream_port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((upstream_hostname, upstream_port))
if result != 0:
sock.close()
return False
else:
sock.shutdown(SHUT_RDWR)
sock.close()
return True
class StarryPyServerProtocol(Protocol):
"""
The main protocol class for handling connections from Starbound clients.
"""
def __init__(self):
"""
"""
self.id = str(uuid4().hex)
self.factory.protocols[self.id] = self
self.player = None
self.state = None
self.config = ConfigurationManager()
self.parsing = False
self.buffering_packet = None
self.after_write_callback = None
self.plugin_manager = None
self.call_mapping = {
packets.Packets.PROTOCOL_VERSION: self.protocol_version,
packets.Packets.CONNECT_RESPONSE: self.connect_response,
packets.Packets.SERVER_DISCONNECT: self.server_disconnect,
packets.Packets.HANDSHAKE_CHALLENGE: self.handshake_challenge,
packets.Packets.CHAT_RECEIVED: self.chat_received,
packets.Packets.UNIVERSE_TIME_UPDATE: self.universe_time_update,
packets.Packets.CLIENT_CONNECT: self.client_connect,
packets.Packets.CLIENT_DISCONNECT: self.client_disconnect,
packets.Packets.HANDSHAKE_RESPONSE: self.handshake_response,
packets.Packets.WARP_COMMAND: self.warp_command,
packets.Packets.CHAT_SENT: self.chat_sent,
packets.Packets.CLIENT_CONTEXT_UPDATE: self.client_context_update,
packets.Packets.WORLD_START: self.world_start,
packets.Packets.WORLD_STOP: self.world_stop,
packets.Packets.TILE_ARRAY_UPDATE: self.tile_array_update,
packets.Packets.TILE_UPDATE: self.tile_update,
packets.Packets.CELESTIALRESPONSE: lambda x: True,
packets.Packets.CELESTIALREQUEST: lambda x: True,
packets.Packets.TILE_LIQUID_UPDATE: self.tile_liquid_update,
packets.Packets.TILE_DAMAGE_UPDATE: self.tile_damage_update,
packets.Packets.TILE_MODIFICATION_FAILURE: self.tile_modification_failure,
packets.Packets.GIVE_ITEM: self.item,
packets.Packets.SWAP_IN_CONTAINER_RESULT: self.swap_in_container_result,
packets.Packets.ENVIRONMENT_UPDATE: self.environment_update,
packets.Packets.ENTITY_INTERACT_RESULT: self.entity_interact_result,
packets.Packets.MODIFY_TILE_LIST: self.modify_tile_list,
packets.Packets.DAMAGE_TILE: self.damage_tile,
packets.Packets.DAMAGE_TILE_GROUP: self.damage_tile_group,
packets.Packets.REQUEST_DROP: self.request_drop,
packets.Packets.SPAWN_ENTITY: self.spawn_entity,
packets.Packets.ENTITY_INTERACT: self.entity_interact,
packets.Packets.CONNECT_WIRE: self.connect_wire,
packets.Packets.DISCONNECT_ALL_WIRES: self.disconnect_all_wires,
packets.Packets.OPEN_CONTAINER: self.open_container,
packets.Packets.CLOSE_CONTAINER: self.close_container,
packets.Packets.SWAP_IN_CONTAINER: self.swap_in_container,
packets.Packets.ITEM_APPLY_IN_CONTAINER: self.item_apply_in_container,
packets.Packets.START_CRAFTING_IN_CONTAINER: self.start_crafting_in_container,
packets.Packets.STOP_CRAFTING_IN_CONTAINER: self.stop_crafting_in_container,
packets.Packets.BURN_CONTAINER: self.burn_container,
packets.Packets.CLEAR_CONTAINER: self.clear_container,
packets.Packets.WORLD_UPDATE: self.world_update,
packets.Packets.ENTITY_CREATE: self.entity_create,
packets.Packets.ENTITY_UPDATE: self.entity_update,
packets.Packets.ENTITY_DESTROY: self.entity_destroy,
packets.Packets.DAMAGE_NOTIFICATION: self.damage_notification,
packets.Packets.STATUS_EFFECT_REQUEST: self.status_effect_request,
packets.Packets.UPDATE_WORLD_PROPERTIES: self.update_world_properties,
packets.Packets.HEARTBEAT: self.heartbeat,
}
self.client_protocol = None
self.packet_stream = PacketStream(self)
self.packet_stream.direction = packets.Direction.CLIENT
self.plugin_manager = self.factory.plugin_manager
def connectionMade(self):
"""
Called when the connection to the requesting client is actually
established.
After the connection is established, it attempts to connect to the
actual starbound server using StarboundClientFactory()
:rtype : None
"""
logger.info("Connection established from IP: %s", self.transport.getPeer().host)
reactor.connectTCP(self.config.upstream_hostname, self.config.upstream_port,
StarboundClientFactory(self), timeout=self.config.server_connect_timeout)
def string_received(self, packet):
"""
This method is called whenever a completed packet is received from the
client going to the Starbound server.
This is the first and only time where these packets can be modified,
stopped, or allowed.
Processing of parsed data is handled in handle_starbound_packets()
:rtype : None
"""
if 48 >= packet.id:
if self.handle_starbound_packets(packet):
self.client_protocol.transport.write(
packet.original_data)
if self.after_write_callback is not None:
self.after_write_callback()
else:
# We received an unknown packet; send it along.
logger.warning(
"Received unknown message ID (%d) from client." %
packet.id)
self.client_protocol.transport.write(
packet.original_data)
def dataReceived(self, data):
"""
Called whenever a packet is received. Generally this should not be
tampered with directly, as it attempts to reconstruct the packet
that Starbound clients send out.
The actual handling of the reconstructed packet should be done in
string_received(), which is called when the packet is built.
:param data: Raw packet data from Twisted.
:rtype : None
"""
if self.config.passthrough:
self.client_protocol.transport.write(data)
else:
self.packet_stream += data
@route
def protocol_version(self, data):
return True
@route
def server_disconnect(self, data):
return True
@route
def handshake_challenge(self, data):
return True
@route
def chat_received(self, data):
return True
@route
def universe_time_update(self, data):
return True
@route
def handshake_response(self, data):
return True
@route
def client_context_update(self, data):
return True
@route
def world_start(self, data):
return True
@route
def world_stop(self, data):
return True
@route
def tile_array_update(self, data):
return True
@route
def tile_update(self, data):
return True
@route
def tile_liquid_update(self, data):
return True
@route
def tile_damage_update(self, data):
return True
@route
def tile_modification_failure(self, data):
return True
@route
def item(self, data):
return True
@route
def swap_in_container_result(self, data):
return True
@route
def environment_update(self, data):
return True
@route
def entity_interact_result(self, data):
return True
@route
def modify_tile_list(self, data):
return True
@route
def damage_tile(self, data):
return True
@route
def damage_tile_group(self, data):
return True
@route
def request_drop(self, data):
return True
@route
def spawn_entity(self, data):
return True
@route
def entity_interact(self, data):
return True
@route
def connect_wire(self, data):
return True
@route
def disconnect_all_wires(self, data):
return True
@route
def open_container(self, data):
return True
@route
def close_container(self, data):
return True
@route
def swap_in_container(self, data):
return True
@route
def item_apply_in_container(self, data):
return True
@route
def start_crafting_in_container(self, data):
return True
@route
def stop_crafting_in_container(self, data):
return True
@route
def burn_container(self, data):
return True
@route
def clear_container(self, data):
return True
@route
def world_update(self, data):
return True
@route
def entity_create(self, data):
return True
@route
def entity_update(self, data):
return True
@route
def entity_destroy(self, data):
return True
@route
def status_effect_request(self, data):
return True
@route
def update_world_properties(self, data):
return True
@route
def heartbeat(self, data):
return True
@route
def connect_response(self, data):
"""
Called when the server responds to the client's connection request
after handshaking.
:param data: Parsed packet.
:rtype : bool
"""
return True
@route
def chat_sent(self, data):
"""
Called when the client attempts to send a chat message/command to the
server.
:param data: Parsed chat packet.
:rtype : bool
"""
return True
@route
def damage_notification(self, data):
return True
@route
def client_connect(self, data):
"""
Called when the client attempts to connect to the Starbound server.
:param data: Parsed client_connect packet.
:rtype : bool
"""
return True
@route
def client_disconnect(self, player):
"""
Called when the client signals that it is about to disconnect from the Starbound server.
:param player: The Player.
:rtype : bool
"""
return True
@route
def warp_command(self, data):
"""
Called when the players issues a warp.
:param data: The warp_command data.
:rtype : bool
"""
return True
def handle_starbound_packets(self, p):
"""
This function is the meat of it all. Every time a full packet with
a derived ID <= 48, it is passed through here.
"""
return self.call_mapping[p.id](p)
def send_chat_message(self, text, channel=0, world='', name=''):
"""
Convenience function to send chat messages to the client. Note that this
does *not* send messages to the server at large; broadcast should be
used for messages to all clients, or manually constructed chat messages
otherwise.
:param text: Message text, may contain multiple lines.
:param channel: The chat channel/context. 0 is global, 1 is planet.
:param world: World
:param name: The name to display before the message. Blank leaves no
brackets, otherwise it will be displayed as `<name>`.
:return: None
"""
if '\n' in text:
lines = text.split('\n')
for line in lines:
self.send_chat_message(line)
return
chat_data = packets.chat_received().build(Container(chat_channel=channel,
world=world,
client_id=0,
name=name,
message=text.encode("utf-8")))
chat_packet = build_packet(packets.Packets.CHAT_RECEIVED,
chat_data)
self.transport.write(chat_packet)
def write(self, data):
"""
Convenience method to send data to the client.
:param data: Data to send.
:return: None
"""
self.transport.write(data)
def connectionLost(self, reason=connectionDone):
"""
Called as a pseudo-destructor when the connection is lost.
:param reason: The reason for the disconnection.
:return: None
"""
try:
if self.client_protocol is not None:
x = build_packet(packets.Packets.CLIENT_DISCONNECT,
packets.client_disconnect().build(Container(data=0)))
if self.player is not None and self.player.logged_in:
self.client_disconnect(x)
self.client_protocol.transport.write(x)
self.client_protocol.transport.abortConnection()
except:
logger.error("Couldn't disconnect protocol.")
finally:
try:
self.factory.protocols.pop(self.id)
except:
logger.info("Protocol was not in factory list. This should not happen.")
finally:
logger.info("Lost connection from IP: %s", self.transport.getPeer().host)
self.transport.abortConnection()
def die(self):
self.connectionLost()
class ClientProtocol(Protocol):
"""
The protocol class which handles the connection to the Starbound server.
"""
def __init__(self):
self.packet_stream = PacketStream(self)
self.packet_stream.direction = packets.Direction.SERVER
def connectionMade(self):
"""
Called when the connection to the Starbound server is initially
established. Inserts a self-reference in the server_protocol to allow
two-way communication.
:return: None
"""
self.server_protocol.client_protocol = self
self.parsing = False
def string_received(self, packet):
"""
This method is called whenever a completed packet is received from the
Starbound server.
This is the first and only time where these packets can be modified,
stopped, or allowed.
Processing of parsed data is handled in handle_starbound_packets()
:return: None
"""
try:
if self.server_protocol.handle_starbound_packets(
packet):
self.server_protocol.write(packet.original_data)
except construct.core.FieldError:
logger.exception("Construct field error in string_received.")
self.server_protocol.write(
packet.original_data)
def dataReceived(self, data):
"""
Called whenever a packet is received. Generally this should not be
tampered with directly, as it attempts to reconstruct the packet
that the Starbound server sent out.
The actual handling of the reconstructed packet should be done in
string_received(), which is called when the packet is built.
:param data: Raw packet data from the Starbound server.
:return: None
"""
if self.server_protocol.config.passthrough:
self.server_protocol.write(data)
else:
self.packet_stream += data
class StarryPyServerFactory(ServerFactory):
"""
Factory which creates `StarryPyServerProtocol` instances.
"""
protocol = StarryPyServerProtocol
def __init__(self):
"""
Initializes persistent objects and prepares a list of connected
protocols.
"""
self.config = ConfigurationManager()
self.protocol.factory = self
self.protocols = {}
try:
self.plugin_manager = PluginManager(factory=self)
except FatalPluginError:
logger.critical("Shutting Down.")
sys.exit()
self.reaper = LoopingCall(self.reap_dead_protocols)
self.reaper.start(self.config.reap_time)
def stopFactory(self):
"""
Called when the factory is stopped. Saves the configuration.
:return: None
"""
self.config.save()
self.plugin_manager.die()
def broadcast(self, text, channel=1, world='', name=''):
"""
Convenience method to send a broadcasted message to all clients on the
server.
:param text: Message text
:param channel: Channel to broadcast on. 0 is global, 1 is planet.
:param world: World
:param name: The name to prepend before the message, format is <name>
:return: None
"""
for p in self.protocols.itervalues():
try:
p.send_chat_message(text)
except:
logger.exception("Exception in broadcast.")
def broadcast_planet(self, text, planet, name=''):
"""
Convenience method to send a broadcasted message to all clients on the
current planet (and ships orbiting it).
:param text: Message text
:param planet: The planet to send the message to
:param name: The name to prepend before the message, format is <name>, not prepanded when empty
:return: None
"""
for p in self.protocols.itervalues():
if p.player.planet == planet:
try:
p.send_chat_message(text)
except:
logger.exception("Exception in broadcast.")
def buildProtocol(self, address):
"""
Builds the protocol to a given address.
:rtype : Protocol
"""
p = ServerFactory.buildProtocol(self, address)
return p
def reap_dead_protocols(self):
count = 0
start_time = datetime.datetime.now()
for protocol in self.protocols.itervalues():
if (
protocol.packet_stream.last_received_timestamp - start_time).total_seconds() > self.config.reap_time:
protocol.connectionLost()
count += 1
continue
if protocol.client_protocol is not None and (
protocol.client_protocol.packet_stream.last_received_timestamp - start_time).total_seconds() > self.config.reap_time:
protocol.connectionLost()
count += 1
if count == 1:
logger.info("1 connection reaped.")
elif count > 1:
logger.info("%d connections reaped.")
class StarboundClientFactory(ClientFactory):
"""
Factory which creates `StarboundClientProtocol` instances.
"""
protocol = ClientProtocol
def __init__(self, server_protocol):
self.server_protocol = server_protocol
def buildProtocol(self, address):
protocol = ClientFactory.buildProtocol(self, address)
protocol.server_protocol = self.server_protocol
return protocol
def init_localization():
try:
locale.setlocale(locale.LC_ALL, '')
except:
locale.setlocale(locale.LC_ALL, 'en_US.utf8')
try:
loc = locale.getlocale()
filename = "res/messages_%s.mo" % locale.getlocale()[0][0:2]
print "Opening message file %s for locale %s." % (filename, loc[0])
trans = gettext.GNUTranslations(open(filename, "rb" ))
except (IOError, TypeError, IndexError):
print "Locale not found. Using default messages."
trans = gettext.NullTranslations()
trans.install()
if __name__ == '__main__':
init_localization()
logger = logging.getLogger('starrypy')
logger.setLevel(9)
fh_w = logging.FileHandler("server.log")
fh_w.setLevel(logging.INFO)
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.INFO)
logger.addHandler(sh)
logger.addHandler(fh_w)
config = ConfigurationManager()
console_formatter = logging.Formatter(config.logging_format_console)
logfile_formatter = logging.Formatter(config.logging_format_logfile)
fh_w.setFormatter(logfile_formatter)
sh.setFormatter(console_formatter)
if config.port_check:
if not port_check(config.upstream_hostname, config.upstream_port):
logger.critical("The starbound server is not connectable at the address %s:%d." % (
config.upstream_hostname, config.upstream_port))
logger.critical(
"Please ensure that you are running starbound_server on the correct port and that is reflected in the StarryPy configuration.")
sys.exit()
logger.info("Started StarryPy server version %s" % VERSION)
factory = StarryPyServerFactory()
try:
reactor.listenTCP(factory.config.bind_port, factory, interface=factory.config.bind_address)
except CannotListenError:
logger.critical("Cannot listen on TCP port %d. Exiting.", factory.config.bind_port)
sys.exit()
logger.info("Listening on port %s" % factory.config.bind_port)
reactor.run()