server.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function, unicode_literals
  4. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  5. import cgi
  6. import json
  7. import logging
  8. import re
  9. import socket
  10. from SocketServer import ThreadingMixIn
  11. import time
  12. import ffstatus
  13. # each match of these regex is removed to normalize an ISP's name
  14. ISP_NORMALIZATIONS = [
  15. # normalize name: strip company indication
  16. re.compile(r'(AG|UG|G?mbH( ?& ?Co\.? ?(OH|K)G)?)$', flags=re.IGNORECASE),
  17. # normalize name: strip "pool" suffixes
  18. re.compile(r'(dynamic )?(customer |subscriber )?(ip )?(pool|(address )?range|addresses)$', flags=re.IGNORECASE),
  19. # normalize name: strip "B2B" and aggregation suffixes
  20. re.compile(r'(aggregate|aggregation)?$', flags=re.IGNORECASE),
  21. re.compile(r'(B2B)?$', flags=re.IGNORECASE),
  22. # normalize name: strip country suffixes (in Germany)
  23. re.compile(r'(' +
  24. 'DE|Deutschland|Germany|' +
  25. 'Nordrhein[- ]Westfalen|NRW|' +
  26. 'Baden[- ]Wuerttemburg|BW|' +
  27. 'Hessen|' +
  28. 'Niedersachsen|' +
  29. 'Rheinland[- ]Pfalz|RLP' +
  30. ')$',
  31. flags=re.IGNORECASE),
  32. ]
  33. REGEX_QUERYPARAM = re.compile(
  34. r'(?P<key>.+?)=(?P<value>.+?)(&|$)')
  35. REGEX_URL_NODEINFO = re.compile(
  36. r'node/(?P<id>[a-fA-F0-9]{12})(?P<cmd>\.json|/[a-zA-Z0-9_\-\.]+)$')
  37. REGEX_URL_NODESTATUS = re.compile(
  38. r'status/([a-f0-9]{12})$')
  39. def normalize_ispname(isp):
  40. """Removes all matches on ISP_NORMALIZATIONS."""
  41. isp = isp.strip()
  42. for regex in ISP_NORMALIZATIONS:
  43. isp = regex.sub('', isp).strip()
  44. return isp
  45. class BatcaveHttpRequestHandler(BaseHTTPRequestHandler):
  46. def __init__(self, request, client_address, server):
  47. self.logger = logging.getLogger('API')
  48. BaseHTTPRequestHandler.__init__(self, request, client_address, server)
  49. def parse_url_pathquery(self):
  50. """Extracts the query parameters from the request path."""
  51. url = re.match(r'^/(?P<path>.*?)(\?(?P<query>.+))?$', self.path.strip())
  52. if url is None:
  53. logging.warn('Failed to parse URL \'' + str(self.path) + '\'.')
  54. return ( None, None )
  55. path = url.group('path')
  56. query = {}
  57. if not url.group('query') is None:
  58. return ( path, query )
  59. for match in REGEX_QUERYPARAM.finditer(url.group('query')):
  60. query[match.group('key')] = match.group('value')
  61. def do_GET(self):
  62. """Handles all HTTP GET requests."""
  63. path, query = self.parse_url_pathquery()
  64. if path is None:
  65. self.send_error(400, 'Could not parse URL (' + str(self.path) + ')')
  66. return
  67. # / - index page, shows generic help
  68. if path == '':
  69. self.respond_index(query)
  70. return
  71. # /list - list stored nodes
  72. if path == 'list':
  73. self.respond_list(query)
  74. return
  75. # /vpn - notification endpoint for gateway's VPN connections
  76. if path == 'vpn':
  77. self.respond_vpn(query)
  78. return
  79. # /providers
  80. if path == 'providers':
  81. self.respond_providers(query)
  82. return
  83. # /node/<id>.json - node's data
  84. # /node/<id>/field - return specific field from node's data
  85. match = REGEX_URL_NODEINFO.match(path)
  86. if match is not None:
  87. cmd = match.group('cmd')
  88. nodeid = match.group('id').lower()
  89. if cmd == '.json':
  90. self.respond_node(nodeid)
  91. else:
  92. self.respond_nodedetail(nodeid, cmd[1:])
  93. return
  94. # /status/<id> - node's status
  95. match = REGEX_URL_NODESTATUS.match(path)
  96. if match is not None:
  97. self.respond_nodestatus(match.group(1))
  98. return
  99. # no match -> 404
  100. self.send_error(404, 'The URL \'{0}\' was not found here.'.format(path))
  101. def do_POST(self):
  102. """Handles all HTTP POST requests."""
  103. path, query = self.parse_url_pathquery()
  104. if path is None:
  105. self.send_error(400, 'Could not parse URL (' + str(self.path) + ')')
  106. return
  107. params = self.parse_post_params()
  108. # node id/mac to name mapping
  109. if path == 'idmac2name':
  110. self.respond_nodeidmac2name(params)
  111. return
  112. # no match -> 404
  113. self.send_error(404, 'The URL \'{0}\' was not found here.'.format(path))
  114. def send_nocache_headers(self):
  115. """Sets HTTP headers indicating that this response shall not be cached."""
  116. self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
  117. self.send_header('Pragma', 'no-cache')
  118. self.send_header('Expires', '0')
  119. def send_headers(self, content_type='text/html; charset=utf-8', nocache=True):
  120. """Send HTTP 200 Response header with the given Content-Type.
  121. Optionally send no-caching headers, too."""
  122. self.send_response(200)
  123. self.send_header('Content-Type', content_type)
  124. if nocache:
  125. self.send_nocache_headers()
  126. self.end_headers()
  127. def parse_post_params(self):
  128. ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
  129. if ctype == 'multipart/form-data':
  130. postvars = cgi.parse_multipart(self.rfile, pdict)
  131. elif ctype == 'application/x-www-form-urlencoded':
  132. length = int(self.headers.getheader('content-length'))
  133. postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
  134. else:
  135. postvars = {}
  136. return postvars
  137. def respond_index(self, query):
  138. """Display the index page."""
  139. storage = self.server.storage
  140. self.send_headers()
  141. self.wfile.write('<!DOCTYPE html><html><head><title>BATCAVE</title></head>\n')
  142. self.wfile.write('<body>\n')
  143. self.wfile.write('<H1 title="Batman/Alfred Transmission Collection, Aggregation & Value Engine">BATCAVE</H1>\n')
  144. self.wfile.write('<p>Dies ist ein interner Hintergrund-Dienst. Er wird nur von anderen Diensten\n')
  145. self.wfile.write('angesprochen und sollte aus einer Mehrzahl von Gr&uuml;nden nicht &ouml;ffentlich\n')
  146. self.wfile.write('zug&auml;nglich sein.</p>\n')
  147. self.wfile.write('<H2>Status</H2>\n')
  148. self.wfile.write('Daten: <span id="datacount" class="value">')
  149. self.wfile.write(len(storage.data))
  150. self.wfile.write('</span>\n')
  151. self.wfile.write('<H2>API</H2>\n')
  152. self.wfile.write('<p>Grundsätzlich ist das Antwort-Format JSON und alle Daten sind Live-Daten (kein Cache) die ggf. etwas Bearbeitungs-Zeit erfordern.</p>')
  153. self.wfile.write('<dl>\n')
  154. self.wfile.write('<dt><a href="/nodes.json">nodes.json</a></dt><dd>zur Verwendung mit ffmap (MACs anonymisiert)</dd>\n')
  155. self.wfile.write('<dt><a href="/node/ff00ff00ff00.json">/node/&lt;id&gt;.json</a></dt><dd><u>alle</u> vorhandenen Information zu der gewünschten Node</dd>\n')
  156. self.wfile.write('</dl>\n')
  157. self.wfile.write('</body></html>')
  158. def respond_list(self, query):
  159. """List stored data."""
  160. self.send_headers()
  161. self.wfile.write('<!DOCTYPE html><html>\n')
  162. self.wfile.write('<head><title>BATCAVE</title></head>\n')
  163. self.wfile.write('<body>\n')
  164. self.wfile.write('<H1>BATCAVE - LIST</H1>\n')
  165. self.wfile.write('<table>\n')
  166. self.wfile.write('<thead><tr><th>ID</th><th>Name</th></tr></thead>\n')
  167. self.wfile.write('<tbody>\n')
  168. sortkey = query['sort'] if 'sort' in query else None
  169. data = self.server.storage.get_nodes(sortby=sortkey)
  170. for node in data:
  171. nodeid = node['node_id']
  172. nodename = node['hostname'] if 'hostname' in node else '&lt;?&gt;'
  173. self.wfile.write('<tr><td><a href="/node/' + nodeid + '.json">' + nodeid + '</a></td><td>' + nodename + '</td></tr>')
  174. self.wfile.write('</tbody>\n')
  175. self.wfile.write('</table>\n')
  176. def respond_node(self, rawid):
  177. """Display node data."""
  178. # search node by the given id
  179. node = self.server.storage.find_node(rawid)
  180. # handle unknown nodes
  181. if node is None:
  182. self.send_error(404, 'No node with id \'' + rawid + '\' present.')
  183. return
  184. # dump node data as JSON
  185. self.send_headers('text/json')
  186. self.wfile.write(json.dumps(node))
  187. def respond_nodestatus(self, rawid):
  188. """Display node status."""
  189. status = self.server.storage.get_nodestatus(rawid)
  190. if status is None:
  191. self.send_error(404, 'No node with id \'' + rawid + '\' present.')
  192. self.send_headers('text/plain')
  193. self.wfile.write(status)
  194. def respond_nodeidmac2name(self, ids):
  195. """Return a mapping of the given IDs (or MACs) into their hostname."""
  196. self.send_headers('text/plain')
  197. for nodeid in ids:
  198. node = self.server.storage.find_node(nodeid) if not ':' in nodeid else self.server.storage.find_node_by_mac(nodeid)
  199. nodename = node['hostname'] if (not node is None) and 'hostname' in node else nodeid
  200. self.wfile.write('{0}={1}\n'.format(nodeid, nodename))
  201. def respond_nodedetail(self, nodeid, field):
  202. """Return a field from the given node - a string is returned as text, all other as JSON."""
  203. node = self.server.storage.find_node(nodeid)
  204. if node is None:
  205. self.send_error(404, 'No node with id \'' + nodeid + '\' present.')
  206. return
  207. return_count = False
  208. if field.endswith('.count'):
  209. return_count = True
  210. field = field[0:-6]
  211. if not field in node:
  212. self.send_error(404, 'The node \'' + nodeid + '\' does not have a field named \'' + str(field) + '\'.')
  213. return
  214. value = node[field]
  215. if return_count:
  216. value = len(value)
  217. self.send_headers('text/plain' if isinstance(value, basestring) or isinstance(value, int) else 'text/json')
  218. self.wfile.write(value if isinstance(value, basestring) else json.dumps(value))
  219. def respond_vpn(self, query):
  220. storage = self.server.storage
  221. peername = query['peer'] if 'peer' in query else None
  222. key = query['key'] if 'key' in query else None
  223. action = query['action'] if 'action' in query else None
  224. remote = query['remote'] if 'remote' in query else None
  225. gw = query['gw'] if 'gw' in query else None
  226. ts = query['ts'] if 'ts' in query else time.time()
  227. if action == 'list':
  228. self.respond_vpnlist()
  229. return
  230. if action != 'establish' and action != 'disestablish':
  231. self.logger.error('VPN: unknown action \'{0}\''.format(action))
  232. self.send_error(400, 'Invalid action.')
  233. return
  234. check = {'peername': peername, 'key': key, 'remote': remote, 'gw': gw}
  235. for k, val in check.items():
  236. if val is None or len(val.strip()) == 0:
  237. self.logger.error('VPN {0}: no or empty {1}'.format(action, k))
  238. self.send_error(400, 'Missing value for ' + str(k))
  239. return
  240. try:
  241. if action == 'establish':
  242. self.server.storage.log_vpn_connect(
  243. key, peername, remote, gw, ts)
  244. elif action == 'disestablish':
  245. self.server.storage.log_vpn_connect(key, gw, ts)
  246. else:
  247. self.logger.error('Unknown VPN action \'%s\' not filtered.',
  248. action)
  249. self.send_error(500)
  250. return
  251. except ffstatus.exceptions.VpnKeyFormatError:
  252. self.logger.error('VPN peer \'{0}\' {1}: bad key \'{2}\''.format(
  253. peername, action, key,
  254. ))
  255. self.send_error(400, 'Bad key.')
  256. return
  257. self.send_headers('text/plain')
  258. self.wfile.write('OK')
  259. storage.save()
  260. def respond_vpnlist(self):
  261. self.send_headers()
  262. self.wfile.write('<!DOCTYPE html>\n')
  263. self.wfile.write('<html><head><title>BATCAVE - VPN LIST</title></head>\n')
  264. self.wfile.write('<body>\n')
  265. self.wfile.write('<style type="text/css">\n')
  266. self.wfile.write('table { border: 2px solid #999; border-collapse: collapse; }\n')
  267. self.wfile.write('th, td { border: 1px solid #CCC; }\n')
  268. self.wfile.write('table tbody tr.online { background-color: #CFC; }\n')
  269. self.wfile.write('table tbody tr.offline { background-color: #FCC; }\n')
  270. self.wfile.write('</style>\n')
  271. self.wfile.write('<table>\n<thead>\n')
  272. gateways = self.server.storage.get_vpn_gateways()
  273. self.wfile.write('<tr><th rowspan="2">names (key)</th><th colspan="' + str(len(gateways)) + '">active</th><th colspan="' + str(len(gateways)) + '">last</th></tr>\n')
  274. self.wfile.write('<tr><th>' + '</th><th>'.join(gateways) + '</th><th>' + '</th><th>'.join(gateways) + '</th></tr>\n')
  275. self.wfile.write('</thead>\n')
  276. for item in self.server.storage.get_vpn_connections():
  277. self.wfile.write('<tr class="{0}">'.format('online' if item['online'] else 'offline'))
  278. self.wfile.write('<td title="{0}">{1}</td>'.format(
  279. item['key'],
  280. ' / '.join(item['names']) if len(item['names']) > 0 else '?',
  281. ))
  282. for conntype in ['active', 'last']:
  283. for gateway in gateways:
  284. remote = ''
  285. if conntype in item['remote'] and gateway in item['remote'][conntype]:
  286. remote = item['remote'][conntype][gateway]
  287. if isinstance(remote, dict):
  288. remote = remote['name']
  289. symbol = '&check;' if len(remote) > 0 else '&times;'
  290. self.wfile.write('<td title="{0}">{1}</td>'.format(
  291. remote, symbol))
  292. self.wfile.write('</tr>\n')
  293. self.wfile.write('</table>\n')
  294. self.wfile.write('</body>')
  295. self.wfile.write('</html>')
  296. def respond_providers(self, query):
  297. """Return a summary of providers."""
  298. outputformat = query['format'].lower() if 'format' in query else 'html'
  299. isps = {}
  300. ispblocks = {}
  301. for item in self.server.storage.get_vpn_connections():
  302. if item['count']['active'] == 0:
  303. continue
  304. remotes = []
  305. for gateway in item['remote']['active']:
  306. remote = item['remote']['active'][gateway]
  307. remotes.append(remote)
  308. if len(remotes) == 0:
  309. self.logger.warn(
  310. 'VPN key \'%s\' is marked with active remotes but 0 found?',
  311. item['key'])
  312. continue
  313. item_isps = set()
  314. for remote in remotes:
  315. isp = "UNKNOWN"
  316. ispblock = remote
  317. if isinstance(remote, dict):
  318. ispblock = remote['name']
  319. desc_lines = remote['description'].split('\n')
  320. isp = normalize_ispname(desc_lines[0])
  321. if not isp in ispblocks:
  322. ispblocks[isp] = set()
  323. ispblocks[isp].add(ispblock)
  324. item_isps.add(isp)
  325. if len(item_isps) == 0:
  326. item_isps.add('unknown')
  327. elif len(item_isps) > 1:
  328. self.logger.warn('VPN key \'{0}\' has {1} active IPs which resolved to {2} ISPs: \'{3}\''.format(key, len(ips), len(item_isps), '\', \''.join(item_isps)))
  329. for isp in item_isps:
  330. if not isp in isps:
  331. isps[isp] = 0
  332. isps[isp] += 1.0 / len(item_isps)
  333. isps_sum = sum([isps[x] for x in isps])
  334. if outputformat == 'csv':
  335. self.send_headers('text/csv')
  336. self.wfile.write('Count;Name\n')
  337. for isp in isps:
  338. self.wfile.write('{0};"{1}"\n'.format(isps[isp], isp))
  339. elif outputformat == 'json':
  340. self.send_headers('text/json')
  341. data = [
  342. {
  343. 'name': isp,
  344. 'count': isps[isp],
  345. 'percentage': isps[isp]*100.0/isps_sum,
  346. 'blocks': [block for block in ispblocks[isp]],
  347. } for isp in isps
  348. ]
  349. self.wfile.write(json.dumps(data))
  350. elif outputformat == 'html':
  351. self.send_headers()
  352. self.wfile.write('<!DOCTYPE html><html>\n')
  353. self.wfile.write('<head><title>BATCAVE - PROVIDERS</title></head>\n')
  354. self.wfile.write('<body>\n')
  355. self.wfile.write('<table border="2">\n')
  356. self.wfile.write('<thead><tr><th>Count</th><th>Percentage</th><th>Name</th><th>Blocks</th></tr></thead>\n')
  357. self.wfile.write('<tbody>\n')
  358. for isp in sorted(isps, key=lambda x: isps[x], reverse=True):
  359. self.wfile.write('<tr><td>{0}</td><td>{1:.1f}%</td><td>{2}</td><td>{3}</td></tr>\n'.format(
  360. isps[isp],
  361. isps[isp]*100.0/isps_sum,
  362. isp,
  363. ', '.join(sorted(ispblocks[isp])) if isp in ispblocks else '?',
  364. ))
  365. self.wfile.write('</tbody></table>\n')
  366. self.wfile.write('<p>Totals: {0} ISPs, {1} connections</p>\n'.format(len(isps), isps_sum))
  367. self.wfile.write('</body></html>')
  368. else:
  369. self.send_error(400, 'Unknown output format.')
  370. class ApiServer(ThreadingMixIn, HTTPServer):
  371. def __init__(self, endpoint, storage):
  372. if ':' in endpoint[0]:
  373. self.address_family = socket.AF_INET6
  374. HTTPServer.__init__(self, endpoint, BatcaveHttpRequestHandler)
  375. self.storage = storage
  376. def __str__(self):
  377. return 'ApiServer on {0}'.format(self.server_address)
  378. if __name__ == '__main__':
  379. dummystorage = ffstatus.basestorage.BaseStorage()
  380. server = ApiServer(('0.0.0.0', 8888), dummystorage)
  381. print("Server:", str(server))
  382. server.serve_forever()