-
Notifications
You must be signed in to change notification settings - Fork 1
/
central_proxy.py
executable file
·208 lines (166 loc) · 5.98 KB
/
central_proxy.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
#!/usr/bin/python3
import jamulus
import argparse
import signal
import sys
from time import time
DEFAULT_INTERVAL = 300
class ServerList(dict):
def format_server(server):
age_seconds = int(time() - server["time_updated"]) if "time_updated" in server.keys() else "?"
return "{:>15}:{:<5} {} {:<20} {:>3}/{:>3} {}/{} ({}/{}) {}s {}".format(
server.get("ip", 0),
server.get("port", 0),
"*" if server.get("permanent", 0) == 1 else " ",
server.get("name", "?"),
server.get("clients", "?"),
server.get("max_clients", "?"),
server.get("city", "?"),
jamulus.COUNTRY_KEYS.get(server.get("country_id"), "?"),
jamulus.OS_KEYS.get(server.get("os"), "?"),
server.get("version", "?"),
age_seconds,
server.get("internal_address", ""),
)
def __str__(self):
return "\n".join(list(map(ServerList.format_server, self.values())))
def update_server(self, key, values):
if key in self.keys():
self[key].update(values)
self[key]["time_updated"] = time()
def create_or_update_server(self, key, values):
if key not in self.keys():
self[key] = {"time_created": time()}
self.update_server(key, values)
def add_single(self, source_host, server):
server["ip"] = source_host[0]
key = (server["ip"], server["port"])
self.create_or_update_server(key, server)
print(ServerList.format_server(self[key]))
def add_list(self, source_host, server_list):
for server in server_list:
if server["ip"] == "0.0.0.0":
# central servers first (own) entry
server["ip"], server["port"] = source_host
server["source_host"] = source_host
key = (server["ip"], server["port"])
self.create_or_update_server(key, server)
def remove_server(self, key):
if key in self.keys():
print(ServerList.format_server(self[key]))
del self[key]
def get_list(self, add_dummy=True):
server_list = list(self.values())
if add_dummy:
server_list.insert(
0,
{
"ip": "0.0.0.0",
"port": 0,
"country_id": 0,
"max_clients": 0,
"permanent": 1,
"name": "Jamulus Proxy",
"internal_address": "",
"city": "",
},
)
return server_list
def filter(self, country_ids):
if len(country_ids) > 0:
filtered = dict((k, s) for k, s in super().items() if s["country_id"] in country_ids)
super().clear()
super().update(filtered)
def copy(self):
return ServerList(super().copy())
class ActionScheduler:
def __init__(self, jamulus, central_servers, interval):
self.jamulus = jamulus
self.central_servers = central_servers
self.interval = interval
self.next_action = time()
def run(self):
# request server lists
if self.next_action <= time():
print("request server lists")
for addr in self.central_servers:
self.jamulus.sendto(addr, "CLM_REQ_SERVER_LIST")
self.next_action += self.interval
# return maximum time after which the scheduler needs to run again
return self.next_action - time()
def argument_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=jamulus.DEFAULT_PORT, help="local port number")
parser.add_argument(
"--centralserver",
type=jamulus.server_argument,
required=True,
action="extend",
nargs="+",
default=[],
help="central servers for collecting server lists",
)
parser.add_argument(
"--interval",
type=int,
default=DEFAULT_INTERVAL,
help="central server collection interval",
)
parser.add_argument(
"--filter",
type=int,
action="extend",
nargs="+",
default=[],
help="country IDs to filter",
)
parser.add_argument(
"--log-data",
action="store_true",
help="log protocol data",
)
return parser.parse_args()
################################################################################
def main():
# get arguments
args = argument_parser()
# create jamulus connector
jc = jamulus.JamulusConnector(port=args.port, log_data=args.log_data)
# create empty server list
server_list = ServerList()
# initiate repeated actions
scheduler = ActionScheduler(
jamulus=jc,
central_servers=args.centralserver,
interval=args.interval,
)
# receive messages indefinitely
while True:
timeout = scheduler.run()
if timeout is not None and timeout <= 0:
print("negative timeout {}".format(timeout))
continue
try:
addr, key, count, values = jc.recvfrom(timeout)
except TimeoutError:
continue
if key == "AUDIO":
# stop clients from connecting
jc.sendto(addr, "CLM_DISCONNECTION")
elif key == "CLM_SERVER_LIST":
# add servers to list
print("add/update {} servers".format(len(values)))
server_list.add_list(addr, values)
elif key == "CLM_REQ_SERVER_LIST":
# get and filter server list
server_list_send = server_list.copy()
server_list_send.filter(args.filter)
# send (filtered) server list
print("sending {} servers\n{}".format(len(server_list_send), server_list_send))
jc.sendto(addr, "CLM_SERVER_LIST", server_list_send.get_list())
def signal_handler(sig, frame):
print()
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signal_handler)
main()