forked from bombsquad-community/plugin-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnatpmp_upnp.py
291 lines (257 loc) · 10.6 KB
/
natpmp_upnp.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
# ba_meta require api 8
import babase
import bauiv1 as bui
import bascenev1 as bs
import shutil
import hashlib
import threading
import ast
import time
from pathlib import Path
from os import remove, getcwd
from urllib.request import urlretrieve, urlopen
# Plucked from https://github.com/ethereum/upnp-port-forward/blob/master/upnp_port_forward/
WAN_SERVICE_NAMES = (
"WANIPConn1",
"WANIPConnection.1", # Nighthawk C7800
"WANPPPConnection.1", # CenturyLink C1100Z
"WANPPPConn1", # Huawei B528s-23a
)
BS_PORT = bs.get_game_port()
def threaded(func):
def wrapper(*args, **kwargs):
thread = threading.Thread(
target=func, args=args, kwargs=kwargs, name=func.__name__
)
thread.start()
return wrapper
@threaded
def get_modules() -> None:
install_path = Path(f"{getcwd()}/ba_data/python") # For the guys like me on windows
upnpy_path = Path(f"{install_path}/upnp.tar.gz")
nat_pmp_path = Path(f"{install_path}/natpmp.tar.gz")
upnpy_file_path = Path(f"{install_path}/upnpy")
nat_pmp_file_path = Path(f"{install_path}/natpmp")
nat_pmp_source_dir = Path(f"{install_path}/NAT-PMP-1.3.2/natpmp")
upnpy_source_dir = Path(f"{install_path}/UPnPy-1.1.8/upnpy")
if (
not Path(f"{nat_pmp_file_path}/__init__.py").exists()
and not Path(f"{upnpy_file_path}/__init__.py").exists()
): # YouKnowDev
nat_pmp_url = "https://files.pythonhosted.org/packages/dc/0c/28263fb4a623e6718a179bca1f360a6ae38f0f716a6cacdf47e15a5fa23e/NAT-PMP-1.3.2.tar.gz"
upnpy_url = "https://files.pythonhosted.org/packages/80/66/d4e721ff8766ea3e78730574669f6feeb71e438a8c2d7a62b2c3456a5c12/UPnPy-1.1.8.tar.gz"
try:
# fix issue where the file delete themselves
try:
shutil.rmtree(nat_pmp_file_path)
shutil.rmtree(upnpy_file_path)
except:
pass
nat_pmp_filename, headers = urlretrieve(nat_pmp_url, filename=nat_pmp_path)
upnpy_filename, headers = urlretrieve(upnpy_url, filename=upnpy_path)
with open(nat_pmp_filename, "rb") as f:
content = f.read()
assert (
hashlib.md5(content).hexdigest()
== "7e5faa22acb0935f75664e9c4941fda4"
)
with open(upnpy_filename, "rb") as f:
content = f.read()
assert (
hashlib.md5(content).hexdigest()
== "b33ad0b38e39af258e2c8f38813abf7b"
)
shutil.unpack_archive(nat_pmp_filename, install_path)
shutil.unpack_archive(upnpy_filename, install_path)
remove(upnpy_path)
remove(nat_pmp_path)
shutil.copytree(nat_pmp_source_dir, nat_pmp_file_path)
shutil.copytree(upnpy_source_dir, upnpy_file_path)
shutil.rmtree(Path(f"{install_path}/NAT-PMP-1.3.2"))
shutil.rmtree(Path(f"{install_path}/UPnPy-1.1.8"))
except Exception as e:
if type(e) == shutil.Error:
shutil.rmtree(Path(f"{install_path}/NAT-PMP-1.3.2"))
shutil.rmtree(Path(f"{install_path}/UPnPy-1.1.8"))
else:
pass
# Patch to natpmp to work without netifaces
with open(f"{nat_pmp_file_path}/__init__.py", "r") as f:
lines = f.readlines()
# Define the new function as a string
new_function = '''
# Plucked from https://github.com/tenable/upnp_info/blob/d20a1fda8ca4877d61b89fe7126077a3a5f0b322/upnp_info.py#L23
def get_gateway_addr():
"""Returns the gateway ip of the router if upnp service is available"""
try:
locations = set()
location_regex = re.compile("location:[ ]*(.+)"+ chr(13) + chr(10), re.IGNORECASE)
ssdpDiscover = (
"M-SEARCH * HTTP/1.1"+ chr(13) + chr(10)
+ "HOST: 239.255.255.250:1900"+ chr(13) + chr(10)
+ 'MAN: "ssdp:discover"'+ chr(13) + chr(10)
+ "MX: 1"+ chr(13) + chr(10)
+ "ST: ssdp:all"+ chr(13) + chr(10)
+ chr(13) + chr(10)
)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(ssdpDiscover.encode("ASCII"), ("239.255.255.250", 1900))
sock.settimeout(3)
try:
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
location_result = location_regex.search(data.decode("ASCII"))
if location_result and (location_result.group(1) in locations) == False:
locations.add(location_result.group(1))
except socket.error:
sock.close()
if locations:
for location in locations:
parsed_url = urlparse(location)
if parsed_url.path.endswith("xml"):
gateway_ip_address = parsed_url.netloc.split(':')[0]
return gateway_ip_address
except:
pass
'''
# Replace the function
lines[224:229] = new_function
lines[21] = "import socket\nimport re\nfrom urllib.parse import urlparse"
with open(f"{nat_pmp_file_path}/__init__.py", "w") as f:
f.writelines(lines)
add_port_mapping()
@threaded
def confirm_port():
time.sleep(5)
with urlopen("https://legacy.ballistica.net/bsAccessCheck") as resp:
resp = resp.read().decode()
resp = ast.literal_eval(resp)
return resp["accessible"]
@threaded
def add_port_mapping():
# Try to add UDP port using NAT-PMP
import socket
import natpmp
from natpmp import NATPMPUnsupportedError, NATPMPNetworkError
try:
natpmp.map_port(
natpmp.NATPMP_PROTOCOL_UDP,
BS_PORT,
BS_PORT,
14400,
gateway_ip=natpmp.get_gateway_addr(),
)
if confirm_port():
babase.screenmessage(
"You are now joinable from the internet", (0.2, 1, 0.2)
)
except (NATPMPUnsupportedError, NATPMPNetworkError):
import upnpy
from upnpy.exceptions import SOAPError
from urllib.error import HTTPError
upnp = upnpy.UPnP()
devices = upnp.discover()
if devices == []:
babase.screenmessage(
"Please enable upnp service on your router", (1.00, 0.15, 0.15)
)
# bui.getsound('shieldDown').play() -> RuntimeError : Sound creation failed
return
local_ip = (
(
[
ip
for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")
]
or [
[
(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close())
for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]
][0][1]
]
)
+ ["no IP found"]
)[0]
try:
for upnp_dev in devices:
for service in upnp_dev.services:
if service in WAN_SERVICE_NAMES:
service = upnp_dev[service]
try:
result = service.GetSpecificPortMappingEntry(
NewRemoteHost="", NewExternalPort=BS_PORT, NewProtocol="UDP"
)
if result and not confirm_port():
if babase.do_once():
babase.screenmessage(
"Oops seems like your network doesn't support upnp",
(1.0, 0.15, 0.15),
)
babase.pushcall(
bui.getsound("error").play(), from_other_thread=True
)
return
except SOAPError:
if confirm_port():
return
service.AddPortMapping(
NewRemoteHost="",
NewExternalPort=BS_PORT,
NewProtocol="UDP",
NewInternalPort=BS_PORT,
NewInternalClient=str(local_ip),
NewEnabled="1",
NewPortMappingDescription="Bombsquad",
NewLeaseDuration=14400,
)
if confirm_port():
babase.screenmessage(
"You are now joinable from the internet", (0.2, 1, 0.2)
)
bui.getsound("shieldUp").play()
except (SOAPError, HTTPError, UnicodeDecodeError):
babase.screenmessage('You will need to manualy add the port at the router :(')
@threaded
def delete_port_mapping():
import socket
import natpmp
from natpmp import NATPMPUnsupportedError, NATPMPNetworkError
try:
natpmp.map_port(
natpmp.NATPMP_PROTOCOL_UDP,
BS_PORT,
BS_PORT,
0,
gateway_ip=natpmp.get_gateway_addr(),
)
except (NATPMPUnsupportedError, NATPMPNetworkError):
import upnpy
from upnpy.exceptions import SOAPError
upnp = upnpy.UPnP()
devices = upnp.discover()
if devices == []:
return
try:
for upnp_dev in devices:
for service in upnp_dev.services:
if service in WAN_SERVICE_NAMES:
service = upnp_dev[service]
service.DeletePortMapping(
NewRemoteHost="", NewExternalPort=BS_PORT, NewProtocol="UDP")
except:
pass
# ba_meta export babase.Plugin
class Joinable(babase.Plugin):
def on_app_running(self) -> None:
get_modules()
if confirm_port():
return
else:
add_port_mapping()
def on_app_shutdown(self) -> None:
delete_port_mapping()
def on_app_pause(self) -> None:
delete_port_mapping()
def on_app_resume(self) -> None:
add_port_mapping()