This repository has been archived by the owner on Mar 12, 2024. It is now read-only.
forked from dalbothek/MVHP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmvhp.py
executable file
·244 lines (208 loc) · 7.09 KB
/
mvhp.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
#!/bin/env python
# This program is free software. It comes without any warranty, to
# the extent permitted by applicable law. You can redistribute it
# and/or modify it under the terms of the Do What The Fuck You Want
# To Public License, Version 2, as published by Sam Hocevar. See
# http://sam.zoy.org/wtfpl/COPYING for more details.
import asyncore
import asynchat
import socket
import re
from struct import pack, unpack
import yaml
# Virtual host definitions
#HOSTS = {
# "localhost": {"host": "localhost", "port": 25566},
# "127.0.0.1": {"port": 25567}, # host defaults to 'localhost'
# None: {"port": 25568} # default / fallback
#}
# Since the host is not sent in the server list query, this is static.
# This might (hopefully) change in the near future.
MOTD = "Minecraft VirtualHost Proxy"
MAX_PLAYERS = 10
CUR_PLAYERS = 3
def load_config():
stream = file('config.yml', 'r')
return yaml.load(stream)
def pack_string(string):
'''
Packs a string into UCS-2 and prefixes it with its length as a short int.
This function can't actually handle UCS-2, therefore kick messages and
the MOTD can't contain special characters.
'''
return (pack(">h", len(string)) +
"".join([pack(">bc", 0, c) for c in string]))
def unpack_string(data):
'''
Extracts a string from a data stream.
Like in the pack method, UCS-2 isn't handled correctly. Since usernames
and hosts can't contain special characters this isn't an issue.
'''
(l,) = unpack(">h", data[:2])
assert len(data) >= 2 + 2 * l
return data[3:l * 2:2]
class Router:
'''
The router finds the target server from the string sent in the handshake.
'''
PATTERN = re.compile("^([^;]+);([^;]+):(\d{1,5})$")
@staticmethod
def route(name):
'''
Finds the target host and port based on the handshake string.
'''
HOSTS = load_config()
host = Router.find_host(name)
target = HOSTS.get(host)
return (target.get("host", "localhost"), target.get("port", 25565))
@staticmethod
def find_host(name):
'''
Extracts the host from the handshake string.
'''
HOSTS = load_config()
match = re.match(Router.PATTERN, name)
if match is None:
return
host = match.group(2)
if host not in HOSTS:
return
return host
class Listener(asyncore.dispatcher):
'''
Listens for connecting clients.
'''
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
print "Listening for connections to %s:%s" % (host, port)
def handle_accept(self):
'''
Accepts a new connections and assigns it to a new ClientTunnel.
'''
pair = self.accept()
if pair is None:
pass
else:
sock, addr = pair
handler = ClientTunnel(sock, addr)
@staticmethod
def loop():
'''
Starts the main I/O loop.
'''
asyncore.loop()
class ClientTunnel(asynchat.async_chat):
'''
Handles a connecting client and assigns it to a server
'''
DELIMITER = chr(0xa7)
def __init__(self, sock, addr):
asynchat.async_chat.__init__(self, sock)
self.set_terminator(None)
self.ibuffer = ""
self.bound = False
self.addr = "%s:%s" % addr
self.log("Incomming connection")
def log(self, message):
'''
Feedback to user
'''
print "%s - %s" % (self.addr, message)
def collect_incoming_data(self, data):
'''
Listens for data and forwards it to the server.
If the client is not yet connected to a server this method waits
for a handshake packet to read the host from. If the client sends
a server list query (0xfe) the connection is closed after sending
the static server list data to the client.
'''
if self.bound:
self.server.push(data)
else:
self.ibuffer += data
if len(self.ibuffer) >= 1:
(packetId,) = unpack(">B", self.ibuffer[0])
if packetId == 0xfe: # Handle server list query
self.log("Received server list query")
self.kick(("%s" * 5) % (MOTD, self.DELIMITER,
CUR_PLAYERS, self.DELIMITER,
MAX_PLAYERS))
elif packetId == 0x02: # Handle handshake
if len(self.ibuffer) >= 3:
(l,) = unpack(">h", self.ibuffer[1:3])
if len(self.ibuffer) >= 3 + l * 2:
self.bind_server(unpack_string(self.ibuffer[1:]))
else:
self.kick("Unexpected packet")
def bind_server(self, name):
'''
Finds the target server and creates a ServerTunnel to it.
'''
(host, port) = Router.route(name)
self.log("Forwarding to %s:%s" % (host, port))
self.server = ServerTunnel(host, port, self, name)
self.bound = True
def kick(self, reason):
'''
Kicks the client.
'''
self.log("Kicking (%s)" % reason)
self.push(pack(">B", 0xff) + pack_string(reason))
self.close()
def handle_close(self):
'''
Terminates the ServerTunnel if the client closes the connection.
'''
self.log("Client closed connection")
self.server.close()
self.close()
class ServerTunnel(asynchat.async_chat):
'''
Represents the server side of a connection.
Data from the server is forwarded to the client.
'''
def __init__(self, host, port, client, handshake):
asynchat.async_chat.__init__(self)
self.set_terminator(None)
self.client = client
self.handshake_msg = handshake
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
def log(self, message):
'''
Feedback to user
'''
self.client.log(message)
def handle_error(self):
'''
Handles socket errors
'''
err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
if err == 61:
self.client.kick("Server unreachable")
else:
self.client.kick("Unexpected error")
def handle_connect(self):
'''
Repeats the handshake packet for the actual server
'''
self.push(pack(">B", 0x02) + pack_string(self.handshake_msg))
def handle_close(self):
'''
Terminates the ClientTunnel if the server closes the connection.
'''
self.log("Server closed connection")
self.client.close()
self.close()
def collect_incoming_data(self, data):
'''
Forwards incoming data to the client
'''
self.client.push(data)
if __name__ == "__main__":
server = Listener('0.0.0.0', 25565)
Listener.loop()