-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackEnd.py
354 lines (313 loc) · 13.2 KB
/
BackEnd.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
# !/usr/bin/python3
__author__ = "Simon Blandford"
from Log import log
import ipaddress
import math
import json
try:
import config
except ImportError:
import config_dist as config
import re
import threading
import MulticastRxUniTx
import IpBroadcaster
import urllib.request
import json
lock = None
privChannelDict = None
channelDict = None
ipLocationDict = {}
def importLocks(lockIn, privChannelDictIn):
global lock
global privChannelDict
lock = lockIn
privChannelDict = privChannelDictIn
def setupUuid(channelDictIn, channelStatDictIn):
global channelDict
global channelStatDict
global lock
with lock:
channelDict = channelDictIn
channelStatDict = channelStatDictIn
"""
API commands in GET variables (URL encoded):
callback=<callbackname>, the JSONP callback name to use
chname=XX<New name>, where XX is the channel number, sets channel name, blank for default
adminpw=<New PW>, set new admin password
id=XX<+/-><UUID>, where XX is the channel number <+/-> indicates add or remove followed by the UUID
headphones=true/false, enable or disable the mandatory headphones flag
open=XX<+/->, where XX is the channel number, open or close channel to allow new UUID to transmit or to lock
"""
def respond(path, params, fullPath, onLan = True):
global channelDict
global channelStatDict
global privChannelDict
callback = "parseResponse"
cacheSeconds = -1
if 'callback' in params:
callback = params['callback']
if "json/admin.json" in path:
code = 200
content = ''
problem = ''
if not onLan:
code = 400
problem = "Attempt to access admin page from WAN"
log().warning(problem)
return code, problem, callback + '(' + content + ')', cacheSeconds
log().debug("Full status requested")
password = config.DEFAULT_ADMIN_PASSWORD
if 'adminPassword' in channelDict:
password = channelDict['adminPassword']
fullPath = re.sub(r"&?hash=[^&]+", "", fullPath)
hashCode = hash(fullPath + password)
if not 'hash' in params or params['hash'] != hashCode:
problem = "Forbidden: incorrect or missing authorisation hash"
content = json.dumps(
{'problem': problem}
)
log().warning(problem)
else:
# Only consider commands if authentication checks out
if 'chname' in params:
if params['chname'][0].isdigit() and params['chname'][1].isdigit():
channel = int(params['chname'][0:2])
if channel >= config.MAX_CHANNELS:
code = 400
problem = "chname channel number too large, must be in range 00 to " + \
format(config.MAX_CHANNELS - 1, '02d')
log().warning(problem)
else:
chName = params['chname'][2:]
with privChannelDict['channels'][channel]['lock']:
if chName != "":
channelDict['channels'][channel]['name'] = chName
else:
if 'name' in channelDict['channels'][channel]:
del channelDict['channels'][channel]['name']
else:
code = 400
problem = "chname parameter must by two decimal digits followed by name, got " + params['chname']
log().warning(problem)
if code == 200 and 'adminpw' in params:
if len(params['adminpw']) >= config.ADMIN_PASSWORD_MIN_LENGTH:
channelDict['adminPassword'] = params['adminpw']
log().info("Password changed")
else:
code = 400
problem = "Password less than minimum acceptable length of " + str(config.ADMIN_PASSWORD_MIN_LENGTH) + " characters"
log().warning(problem)
if code == 200 and 'id' in params:
channel = int(params['id'][0:2])
if channel >= config.MAX_CHANNELS:
code = 400
problem = "chname channel number too large, must be in range 00 to " + \
format(config.MAX_CHANNELS - 1, '02d')
log().warning(problem)
else:
id = params['id'][3:]
if len(id) < 1:
code = 400
problem = "id too short : " + id
if params['id'][2:3] == "+":
if not 'allowedIds' in channelDict['channels'][channel]:
channelDict['channels'][channel]['allowedIds'] = []
if not id in channelDict['channels'][channel]['allowedIds']:
channelDict['channels'][channel]['allowedIds'].append(id)
elif params['id'][2:3] == "-":
if 'allowedIds' in channelDict['channels'][channel] and id in channelDict['channels'][channel]['allowedIds']:
channelDict['channels'][channel]['allowedIds'].remove(id)
else:
code = 400
problem = "Expecting + or - after channel number"
if code == 200 and 'idrename' and 'name' in params:
id = params['idrename']
name = params['name']
# Create frienly name dictionary if not there
if not 'friendlyNames' in channelDict:
channelDict['friendlyNames'] = {}
if len(name) > 0:
# Add new name for UUID
channelDict['friendlyNames'][id] = name
else:
# Clear name for UUID
if id in channelDict['friendlyNames']:
del channelDict['friendlyNames'][id]
if code == 200 and 'headphones' in params:
if params['headphones'] == "false" or params['headphones'] == "0":
channelDict['mandatoryHeadphones'] = False
else:
channelDict['mandatoryHeadphones'] = True
if code == 200 and 'open' in params:
if params['open'][0].isdigit() and params['open'][1].isdigit():
channel = int(params['open'][0:2])
if channel >= config.MAX_CHANNELS:
code = 400
problem = "open channel number too large, must be in range 00 to " + \
format(config.MAX_CHANNELS - 1, '02d')
log().warning(problem)
else:
if params['open'][2:3] == "+":
channelDict['channels'][channel]['open'] = True
elif params['open'][2:3] == "-":
channelDict['channels'][channel]['open'] = False
else:
code = 400
problem = "Expecting + or - after channel number"
log().warning(problem)
else:
code = 400
problem = "chname parameter must by two decimal digits followed by name, got " + params['chname']
log().warning(problem)
if code == 200:
content = json.dumps(
channelDict
)
# Remove the admin password from the response
content = re.sub(r',\s"adminPassword[^,}]+', '', content)
elif "json/stat.json" in path:
code = 200
cacheSeconds = config.HTTP_STAT_CACHE_SECONDS
content = ''
problem = ''
log().debug("Short status requested")
if not 'channelStatLock' in channelStatDict:
channelStatDict['channelStatLock'] = threading.Lock()
with channelStatDict['channelStatLock']:
dictfilt = lambda x, y: dict([(i, x[i]) for i in x if i != y])
content = json.dumps(
dictfilt(channelStatDict, 'channelStatLock')
)
elif "json/lanrange.json" in path:
code, problem = checkRange(params)
# If the problem is "out of range" then it is not a problem in this case
problem = ""
content = json.dumps ({'onLan': onLan, 'inRange': (code == 200) or onLan })
code = 200
else:
content = ""
code = 404
problem = "Not found"
return code, problem, callback + '(' + content + ')', cacheSeconds
def RtpRefesh (channel, params, onLan):
callback = "parseResponse"
if 'callback' in params:
callback = params['callback']
clientInfo = {'uuid': params['uuid'], 'channel': channel}
MulticastRxUniTx.addHttpClientIfNot(clientInfo, onLan)
content = json.dumps(
{
'seq': MulticastRxUniTx.getSeq(channel)
}
)
return callback + '(' + content + ')'
# Based on Java hashcode but with unsigned hex output
def hash(s):
h = 0
for c in s:
h = (31 * h + ord(c)) & 0xFFFFFFFF
return format(abs(((h + 0x80000000) & 0xFFFFFFFF) - 0x80000000), 'x')
# Calculate distance from venue centre from coordinates and return in range or not
def inRange(lat, lon, range):
# If no range specified then range testing is disabled
if range == 0:
return True
radLat = math.radians(lat)
radVenueLat = math.radians(config.HUB_WAN_LOCATION_LATITUDE_DEGREES)
deltaLat = math.radians(config.HUB_WAN_LOCATION_LATITUDE_DEGREES - lat)
deltaLon = math.radians(config.HUB_WAN_LOCATION_LONGITUDE_DEGREES - lon)
a = math.sin(deltaLat / 2) * math.sin(deltaLat / 2) + \
math.cos(radLat) * math.cos(radVenueLat) * \
math.sin(deltaLon / 2) * math.sin(deltaLon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = config.HUB_WAN_LOCATION_EARTH_RADIUS_METERS * c
if range <= d:
log().info("Attempt to connect from client %f meters away outside limit of %f meters", d, range)
return (range > d)
def checkRange(params):
code = 200
problem = ""
if 'lat' in params and 'lon' in params:
try:
lat = float(params['lat'])
lon = float(params['lon'])
except ValueError:
code = 400
problem = "Malformed co-ordinates"
return code, problem
else:
if not inRange(lat, lon, config.HUB_WAN_LOCATION_RADIUS_METERS):
code = 403
problem = "Client out of range of venue"
else:
code = 403
problem = "Unable to assess if client is at venue"
return code, problem
def findIpLocationThread(ip):
global ipLocationDict
# Try geolocation service
try:
url = "http://ipinfo.io/" + ip + "/geo"
req = urllib.request.Request(url)
r = urllib.request.urlopen(req).read()
cont = json.loads(r.decode('utf-8'))
except Exception as e:
log().warning("Unable to locate IP for %s", ip)
log().warning(str(e))
else:
if 'loc' in cont and len(cont['loc'].split(",")) > 1:
lat = float(cont['loc'].split(",")[0])
lon = float(cont['loc'].split(",")[1])
rangeOk = inRange(lat, lon, config.HUB_WAN_LOCATION_IP_CHECK_RADIUS_METERS)
log().info("IP %s in range : %r", ip, rangeOk)
ipLocationDict[ip] = rangeOk
else:
log().warning("Unable to find Location field, 'loc' for %s", ip)
ipLocationDict[ip] = False
def checkIpLocationRange(ips):
global ipLocationDict
#Pass everything if not checking
if config.HUB_WAN_LOCATION_IP_CHECK_RADIUS_METERS == 0:
return True
ip = getSingleIp(ips)
if ip in ipLocationDict:
return ipLocationDict[ip]
else:
# Innocent until proven guilty
ipLocationDict[ip] = True
ipLocationThread = threading.Thread(target = findIpLocationThread, args = (ip,))
ipLocationThread.start()
return True
def isLan(ips):
ip = getSingleIp(ips)
for ipRange in config.LAN_RANGES:
net = ipaddress.ip_network(ipRange)
if ipaddress.ip_address(ip) in net:
return True
for ipAddress in config.HUB_CONSIDER_LAN_ADDRESSES:
if ip == ipAddress:
return True
return False
def rewritable(ips):
ip = getSingleIp(ips)
return ip in config.HUB_REWRITE_TO_LAN_URL
# First IPv4 is the one we want
def getSingleIp(ips):
ip = ips
if len(ips.split(",")) > 1:
ip = re.search("([0-9]{1,3}\.){3}[0-9]{1,3}",ips.split(",")[0])
if ip == None:
return ips.split(",")[0]
else:
ip = ip.group(0)
return ip
def linkAddress():
serverPort = config.WEB_SERVER_PORT
if config.HUB_ACCESS_PORT > 0:
serverPort = config.HUB_ACCESS_PORT
serverPortText = ":" + str(serverPort)
if (serverPort == 80 and config.HUB_LAN_PROTOCOL == "http") or (
serverPort == 443 and config.HUB_LAN_PROTOCOL == "https"):
serverPortText = ""
return config.HUB_LAN_PROTOCOL + "://" + IpBroadcaster.hubAddress + serverPortText