server.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 difflib
  7. import json
  8. import logging
  9. import re
  10. import socket
  11. from SocketServer import ThreadingMixIn
  12. import time
  13. import ffstatus
  14. # each match of these regex is removed to normalize an ISP's name
  15. ISP_NORMALIZATIONS = [
  16. # normalize name: strip company indication
  17. re.compile(r'(AG|UG|G?mbH( ?& ?Co\.? ?(OH|K)G)?)$', flags=re.IGNORECASE),
  18. # normalize name: strip "pool" suffixes
  19. re.compile(r'(dynamic )?(customer |subscriber )?(ip )?(pool|(address )?range|addresses)$', flags=re.IGNORECASE),
  20. # normalize name: strip "B2B" and aggregation suffixes
  21. re.compile(r'(aggregate|aggregation)?$', flags=re.IGNORECASE),
  22. re.compile(r'(B2B)?$', flags=re.IGNORECASE),
  23. # normalize name: strip country suffixes (in Germany)
  24. re.compile(r'(' +
  25. 'DE|Deutschland|Germany|' +
  26. 'Nordrhein[- ]Westfalen|NRW|' +
  27. 'Baden[- ]Wuerttemburg|BW|' +
  28. 'Hessen|' +
  29. 'Niedersachsen|' +
  30. 'Rheinland[- ]Pfalz|RLP' +
  31. ')$',
  32. flags=re.IGNORECASE),
  33. ]
  34. REGEX_QUERYPARAM = re.compile(
  35. r'(?P<key>.+?)=(?P<value>.+?)(&|$)')
  36. REGEX_URL_NODEINFO = re.compile(
  37. r'node/(?P<id>[a-fA-F0-9]{12})(?P<cmd>\.json|/[a-zA-Z0-9_\-\.]+)$')
  38. REGEX_URL_NODESTATUS = re.compile(
  39. r'status/([a-f0-9]{12})$')
  40. def normalize_ispname(isp):
  41. """Removes all matches on ISP_NORMALIZATIONS."""
  42. isp = isp.strip()
  43. for regex in ISP_NORMALIZATIONS:
  44. isp = regex.sub('', isp).strip()
  45. return isp
  46. class BatcaveHttpRequestHandler(BaseHTTPRequestHandler):
  47. """Handles a single HTTP request to the BATCAVE."""
  48. def __init__(self, request, client_address, sockserver):
  49. self.logger = logging.getLogger('API')
  50. BaseHTTPRequestHandler.__init__(
  51. self, request, client_address, sockserver)
  52. def __parse_url_pathquery(self):
  53. """Extracts the query parameters from the request path."""
  54. url = re.match(r'^/(?P<path>.*?)(\?(?P<query>.+))?$', self.path.strip())
  55. if url is None:
  56. logging.warn('Failed to parse URL \'' + str(self.path) + '\'.')
  57. return (None, None)
  58. path = url.group('path')
  59. query = {}
  60. if not url.group('query') is None:
  61. for match in REGEX_QUERYPARAM.finditer(url.group('query')):
  62. query[match.group('key')] = match.group('value')
  63. return (path, query)
  64. def do_GET(self):
  65. """Handles all HTTP GET requests."""
  66. path, query = self.__parse_url_pathquery()
  67. if path is None:
  68. self.send_error(400, 'Could not parse URL (' + str(self.path) + ')')
  69. return
  70. # / - index page, shows generic help
  71. if path == '':
  72. self.__respond_index(query)
  73. return
  74. # /nodes.json
  75. if path == 'nodes.json':
  76. self.__respond_nodes(query)
  77. return
  78. # /list - list stored nodes
  79. if path == 'list':
  80. self.__respond_list(query)
  81. return
  82. # /vpn - notification endpoint for gateway's VPN connections
  83. if path == 'vpn':
  84. self.__respond_vpn(query)
  85. return
  86. # /providers
  87. if path == 'providers':
  88. self.__respond_providers(query)
  89. return
  90. # /find?name=foo&fuzzy=1
  91. if path == 'find':
  92. self.__respond_findnode(query)
  93. return
  94. # /identify?ident=xyz
  95. if path == 'identify':
  96. self.__respond_identify([query.get('ident')])
  97. return
  98. # /node/<id>.json - node's data
  99. # /node/<id>/field - return specific field from node's data
  100. match = REGEX_URL_NODEINFO.match(path)
  101. if match is not None:
  102. cmd = match.group('cmd')
  103. nodeid = match.group('id').lower()
  104. if cmd == '.json':
  105. self.__respond_node(nodeid, query)
  106. else:
  107. self.__respond_nodedetail(nodeid, cmd[1:], query)
  108. return
  109. # /status - overall status (incl. node and client count)
  110. if path == 'status.json':
  111. self.__respond_status()
  112. return
  113. # /status/<id> - node's status
  114. match = REGEX_URL_NODESTATUS.match(path)
  115. if match is not None:
  116. self.__respond_nodestatus(match.group(1))
  117. return
  118. # no match -> 404
  119. self.send_error(404, 'The URL \'{0}\' was not found here.'.format(path))
  120. def do_POST(self):
  121. """Handles all HTTP POST requests."""
  122. path, query = self.__parse_url_pathquery()
  123. if path is None:
  124. self.send_error(400, 'Could not parse URL (' + str(self.path) + ')')
  125. return
  126. params = self.__parse_post_params()
  127. # identify listed macs
  128. if path == 'identify':
  129. self.__respond_identify(params)
  130. return
  131. # node id/mac to name mapping
  132. if path == 'idmac2name':
  133. self.__respond_nodeidmac2name(params)
  134. return
  135. # no match -> 404
  136. self.send_error(404, 'The URL \'{0}\' was not found here.'.format(path))
  137. def __send_nocache_headers(self):
  138. """
  139. Sets HTTP headers indicating that this response shall not be cached.
  140. """
  141. self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
  142. self.send_header('Pragma', 'no-cache')
  143. self.send_header('Expires', '0')
  144. def __send_headers(self,
  145. content_type='text/html; charset=utf-8',
  146. nocache=True, extra={}):
  147. """Send HTTP 200 Response header with the given Content-Type.
  148. Optionally send no-caching headers, too."""
  149. self.send_response(200)
  150. self.send_header('Content-Type', content_type)
  151. if nocache:
  152. self.__send_nocache_headers()
  153. for key in extra:
  154. self.send_header(key, extra[key])
  155. self.end_headers()
  156. def __parse_post_params(self):
  157. ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
  158. if ctype == 'multipart/form-data':
  159. postvars = cgi.parse_multipart(self.rfile, pdict)
  160. elif ctype == 'application/x-www-form-urlencoded':
  161. length = int(self.headers.getheader('content-length'))
  162. postvars = cgi.parse_qs(
  163. self.rfile.read(length),
  164. keep_blank_values=1,
  165. )
  166. else:
  167. postvars = {}
  168. return postvars
  169. def __respond_index(self, query):
  170. """Display the index page."""
  171. self.__send_headers()
  172. index_page = '''<!DOCTYPE html>
  173. <html><head><title>BATCAVE</title></head>
  174. <body>
  175. <H1 title="Batman/Alfred Transmission Collection, Aggregation & Value Engine">
  176. BATCAVE
  177. </H1>
  178. <p>Dies ist ein interner Hintergrund-Dienst. Er wird nur von anderen Diensten
  179. angesprochen und sollte aus einer Mehrzahl von Gr&uuml;nden nicht
  180. &ouml;ffentlich zug&auml;nglich sein.</p>
  181. <H2>API</H2>
  182. <p>
  183. Grunds&auml;tzlich ist das Antwort-Format JSON und alle Daten sind
  184. Live-Daten (kein Cache) die ggf. etwas Bearbeitungs-Zeit erfordern.
  185. </p>
  186. <dl>
  187. <dt>GET <a href="/nodes.json">nodes.json</a></dt>
  188. <dd>zur Verwendung mit ffmap (MACs anonymisiert)</dd>
  189. <dt>GET /node/&lt;id&gt;.json</dt>
  190. <dd>alle Daten zu dem gew&uuml;nschten Knoten</dd>
  191. <dt>GET /providers?format=json</dt>
  192. <dd>Liste der Provider</dd>
  193. <dt>GET <a href="/status">/status</a></dt>
  194. <dd>Status der BATCAVE inkl. Zahl der Nodes+Clients (JSON)</dd>
  195. <dt>GET /status/&lt;id&gt;</dt>
  196. <dd>Status des Knotens</dd>
  197. </dl>
  198. </body></html>'''
  199. self.wfile.write(index_page)
  200. def __respond_list(self, query):
  201. """List stored data."""
  202. list_header_info = {
  203. # Caption => ('field', 'sortkey-or-None'),
  204. "ID": ('node_id', 'id'),
  205. "Name": ('hostname', 'name'),
  206. "Status": ('status', None),
  207. "Type": ('type', None),
  208. }
  209. list_headers = ('ID', 'Name', 'Status', 'Type')
  210. sortkey = query.get('sort')
  211. self.__send_headers()
  212. self.wfile.write('<!DOCTYPE html><html>\n')
  213. self.wfile.write('<head><title>BATCAVE</title></head>\n')
  214. self.wfile.write('<body>\n')
  215. self.wfile.write('<H1>BATCAVE - LIST</H1>\n')
  216. self.wfile.write('<table>\n')
  217. self.wfile.write('<thead><tr>')
  218. for caption in list_headers:
  219. info = list_header_info[caption]
  220. th_attrib, th_prefix, th_suffix = '', '', ''
  221. if info[1] is not None:
  222. th_prefix = '<a href=\"/list?sort=' + info[1] + '\">'
  223. th_suffix = '</a>'
  224. if sortkey == info[1]:
  225. th_attrib = ' class="sorted"'
  226. self.wfile.write(
  227. '<th' + th_attrib + '>' +
  228. th_prefix + caption + th_suffix +
  229. '</th>')
  230. self.wfile.write('</tr></thead>\n')
  231. self.wfile.write('<tbody>\n')
  232. data = self.server.storage.get_nodes(sortby=sortkey)
  233. count_status = {'active': 0}
  234. count_type = {'gateway': 0, 'node': 0}
  235. for node in data:
  236. nodestatus = self.server.storage.get_nodestatus(node=node)
  237. nodetype = node.get('type', 'node')
  238. count_status[nodestatus] = count_status.get(nodestatus, 0) + 1
  239. count_type[nodetype] = count_type.get(nodetype, 0) + 1
  240. self.wfile.write('<tr>')
  241. for caption in list_headers:
  242. info = list_header_info[caption]
  243. value = node.get(info[0], '<?>')
  244. cellcontent = value
  245. # special cell contents
  246. if info[0] == 'node_id':
  247. cellcontent = \
  248. '<a href="/node/{0}.json">{0}</a>'.format(value)
  249. elif info[0] == 'status':
  250. cellcontent = nodestatus
  251. self.wfile.write('<td>' + cellcontent + '</td>')
  252. self.wfile.write('</tr>\n')
  253. self.wfile.write('</tbody>\n')
  254. self.wfile.write('<tfoot><tr><td colspan="{0}">'.format(
  255. len(list_headers)))
  256. self.wfile.write('<p>{0} entries</p>'.format(len(data)))
  257. self.wfile.write('<p>status: ' + ', '.join(
  258. ['{0}={1}'.format(x, count_status[x]) for x in count_status]) +
  259. '</p>')
  260. self.wfile.write('<p>type: ' + ', '.join(
  261. ['{0}={1}'.format(x, count_type[x]) for x in count_type]) +
  262. '</p>')
  263. self.wfile.write('</td></tr></tfoot>')
  264. self.wfile.write('</table>\n')
  265. def __map_item(self, haystack, needle, prefix=None):
  266. if not isinstance(haystack, dict):
  267. raise Exception("haystack must be a dict")
  268. if needle in haystack:
  269. return haystack[needle]
  270. idx = len(haystack) + 1
  271. name = prefix + str(idx)
  272. while name in haystack:
  273. idx += 1
  274. name = prefix + str(idx)
  275. haystack[needle] = name
  276. return name
  277. def __respond_nodes(self, query):
  278. indent = 2 if query.get('pretty', 0) == '1' else None
  279. nodes = []
  280. clientmapping = {}
  281. for node in self.server.storage.get_nodes():
  282. sw = node.get('software', {})
  283. entry = {
  284. 'id': node.get('node_id'),
  285. 'name': node.get('hostname'),
  286. 'clients': [self.__map_item(clientmapping, x, "c")
  287. for x in node.get('clients', [])],
  288. 'autoupdater': sw.get('autoupdater', 'unknown'),
  289. 'firmware': sw.get('firmware'),
  290. 'neighbours': node.get('neighbours', {}),
  291. 'status': self.server.storage.get_nodestatus(node=node),
  292. }
  293. nodetype = node.get('type', 'node')
  294. if nodetype != 'node':
  295. entry['type'] = nodetype
  296. geo = node.get('location', None)
  297. if geo is not None:
  298. entry['geo'] = geo if isinstance(geo, list) else [geo['latitude'], geo['longitude']]
  299. nodes.append(entry)
  300. result = {'nodes': nodes}
  301. self.__send_headers(content_type='application/json', nocache=True,
  302. extra={'Content-Disposition': 'inline'})
  303. self.wfile.write(json.dumps(result, indent=indent))
  304. def __respond_node(self, rawid, query):
  305. """Display node data."""
  306. use_aliases = query.get('search_aliases', '1') != '0'
  307. # search node by the given id
  308. node = self.server.storage.find_node(rawid, search_aliases=use_aliases)
  309. # handle unknown nodes
  310. if node is None:
  311. self.send_error(404, 'No node with id \'' + rawid + '\' present.')
  312. return
  313. # add node's status
  314. node['status'] = self.server.storage.get_nodestatus(node=node)
  315. # dump node data as JSON
  316. self.__send_headers('application/json',
  317. extra={'Content-Disposition': 'inline'})
  318. self.wfile.write(json.dumps(node))
  319. def __respond_nodestatus(self, rawid):
  320. """Display node status."""
  321. status = self.server.storage.get_nodestatus(rawid)
  322. if status is None:
  323. self.send_error(404, 'No node with id \'' + rawid + '\' present.')
  324. self.__send_headers('text/plain')
  325. self.wfile.write(status)
  326. def __respond_findnode(self, query):
  327. """Find nodes matching the supplied name."""
  328. self.__send_headers('application/json',
  329. extra={'Content-Disposition': 'inline'})
  330. name = query.get('name')
  331. mac = query.get('mac')
  332. if name is not None:
  333. fuzzy = query.get('fuzzy', '0') == '1'
  334. return self.__respond_findnode_name(name, fuzzy)
  335. if mac is not None:
  336. return self.__respond_findnode_mac(mac)
  337. self.logger.error('/find called without name or mac parameter')
  338. self.wfile.write('null')
  339. def __respond_findnode_name(self, name, fuzzy):
  340. name = name.lower()
  341. names = {}
  342. for node in self.server.storage.get_nodes():
  343. nodename = node.get('hostname')
  344. if nodename is None:
  345. continue
  346. nodename = nodename.lower()
  347. if nodename not in names:
  348. # first time we see this name
  349. names[nodename] = [node]
  350. else:
  351. # we've seen this name before
  352. names[nodename].append(node)
  353. allnames = [x for x in names]
  354. resultnames = []
  355. # check for exact match
  356. if name in allnames:
  357. # write the exact matches and we're done
  358. resultnames = [name]
  359. else:
  360. # are we allowed to fuzzy match?
  361. if not fuzzy:
  362. # no -> return zero matches
  363. self.wfile.write('[]')
  364. return
  365. # let's do fuzzy matching
  366. resultnames = difflib.get_close_matches(name, allnames,
  367. cutoff=0.75)
  368. result = []
  369. for possibility in resultnames:
  370. for x in names[possibility]:
  371. x_id = x.get('node_id')
  372. result.append({
  373. 'id': x_id,
  374. 'name': x.get('hostname'),
  375. 'status': self.server.storage.get_nodestatus(x_id),
  376. })
  377. self.wfile.write(json.dumps(result))
  378. def __respond_findnode_mac(self, mac):
  379. mac = mac.lower()
  380. result = []
  381. for node in self.server.storage.get_nodes():
  382. if node.get('mac', '').lower() == mac or \
  383. mac in [x.lower() for x in node.get('macs', [])]:
  384. node_id = node.get('node_id')
  385. result.append({
  386. 'id': node_id,
  387. 'name': node.get('hostname'),
  388. 'status': self.server.storage.get_nodestatus(node_id),
  389. })
  390. self.wfile.write(json.dumps(result))
  391. def __respond_nodeidmac2name(self, ids):
  392. """Return a mapping of the given IDs (or MACs) into their hostname."""
  393. self.__send_headers('text/plain')
  394. for nodeid in ids:
  395. node = None
  396. if not ':' in nodeid:
  397. node = self.server.storage.find_node(nodeid)
  398. else:
  399. node = self.server.storage.find_node_by_mac(nodeid)
  400. nodename = node.get('hostname', nodeid) if node is not None else nodeid
  401. self.wfile.write('{0}={1}\n'.format(nodeid, nodename))
  402. def __respond_identify(self, idents):
  403. self.__send_headers('application/json')
  404. nodes = {n['node_id']: n for n in self.server.storage.get_nodes()}
  405. answers = {}
  406. for ident in idents:
  407. ident = ident.lower()
  408. answer = []
  409. answers[ident] = answer
  410. if ident in nodes:
  411. answer.append('node id of "%s"' % nodes[ident].get('hostname'))
  412. continue
  413. for nodeid in nodes:
  414. node = nodes[nodeid]
  415. nodename = node.get('hostname', '?')
  416. nodeinfo = 'node "%s" (id %s)' % (nodename, nodeid)
  417. if ident == node.get('mac', '').lower():
  418. answer.append('primary mac of ' + nodeinfo)
  419. elif ident in [x.lower() for x in node.get('macs', [])]:
  420. answer.append('mac of ' + nodeinfo)
  421. if ident in [c.lower() for c in node.get('clients', [])]:
  422. answer.append('client at ' + nodeinfo)
  423. self.wfile.write(json.dumps(answers))
  424. def __respond_nodedetail(self, nodeid, field, query):
  425. """
  426. Return a field from the given node.
  427. String and integers are returned as text/plain,
  428. all other as JSON.
  429. """
  430. use_aliases = query.get('search_aliases', 1) != 0
  431. # search node by given id
  432. node = self.server.storage.find_node(nodeid,
  433. include_raw_data=True,
  434. search_aliases=use_aliases)
  435. if node is None:
  436. self.send_error(404, 'No node with id \'' + nodeid + '\' present.')
  437. return
  438. return_count = False
  439. if field.endswith('.count'):
  440. return_count = True
  441. field = field[0:-6]
  442. if not field in node:
  443. self.send_error(
  444. 404,
  445. 'The node \'{0}\' does not have a field named \'{1}\'.'.format(
  446. nodeid, field
  447. )
  448. )
  449. return
  450. value = node[field]
  451. if return_count:
  452. value = len(value)
  453. no_json = isinstance(value, basestring) or isinstance(value, int)
  454. self.__send_headers('text/plain' if no_json else 'application/json',
  455. extra={'Content-Disposition': 'inline'})
  456. self.wfile.write(value if no_json else json.dumps(value))
  457. def __respond_status(self):
  458. status = self.server.storage.status
  459. self.__send_headers('application/json',
  460. extra={'Content-Disposition': 'inline'})
  461. self.wfile.write(json.dumps(status, indent=2))
  462. def __respond_vpn(self, query):
  463. storage = self.server.storage
  464. peername = query.get('peer')
  465. key = query.get('key')
  466. action = query.get('action')
  467. remote = query.get('remote')
  468. gateway = query.get('gw')
  469. timestamp = query.get('ts', time.time())
  470. if action == 'list':
  471. self.__respond_vpnlist()
  472. return
  473. if action != 'establish' and action != 'disestablish':
  474. self.logger.error('VPN: unknown action \'{0}\''.format(action))
  475. self.send_error(400, 'Invalid action.')
  476. return
  477. check = {
  478. 'peername': peername,
  479. 'key': key,
  480. 'remote': remote,
  481. 'gw': gateway,
  482. }
  483. for k, val in check.items():
  484. if val is None or len(val.strip()) == 0:
  485. self.logger.error('VPN {0}: no or empty {1}'.format(action, k))
  486. self.send_error(400, 'Missing value for ' + str(k))
  487. return
  488. try:
  489. if action == 'establish':
  490. self.server.storage.log_vpn_connect(
  491. key, peername, remote, gateway, timestamp)
  492. elif action == 'disestablish':
  493. self.server.storage.log_vpn_disconnect(key, gateway, timestamp)
  494. else:
  495. self.logger.error('Unknown VPN action \'%s\' not filtered.',
  496. action)
  497. self.send_error(500)
  498. return
  499. except ffstatus.exceptions.VpnKeyFormatError:
  500. self.logger.error('VPN peer \'{0}\' {1}: bad key \'{2}\''.format(
  501. peername, action, key,
  502. ))
  503. self.send_error(400, 'Bad key.')
  504. return
  505. self.__send_headers('text/plain')
  506. self.wfile.write('OK')
  507. storage.save()
  508. def __respond_vpnlist(self):
  509. self.__send_headers()
  510. self.wfile.write('''<!DOCTYPE html>
  511. <html><head><title>BATCAVE - VPN LIST</title></head>
  512. <body>
  513. <style type="text/css">
  514. table { border: 2px solid #999; border-collapse: collapse; }
  515. th, td { border: 1px solid #CCC; }
  516. table tbody tr.online { background-color: #CFC; }
  517. table tbody tr.offline { background-color: #FCC; }
  518. </style>
  519. <table>''')
  520. gateways = self.server.storage.get_vpn_gateways()
  521. gws_header = '<th>' + '</th><th>'.join(gateways) + '</th>'
  522. self.wfile.write('<thead>\n')
  523. self.wfile.write('<tr><th rowspan="2">names (key)</th>')
  524. self.wfile.write('<th colspan="' + str(len(gateways)) + '">active</th>')
  525. self.wfile.write('<th colspan="' + str(len(gateways)) + '">last</th>')
  526. self.wfile.write('</tr>\n')
  527. self.wfile.write('<tr>' + gws_header + gws_header + '</tr>\n')
  528. self.wfile.write('</thead>\n')
  529. for item in self.server.storage.get_vpn_connections():
  530. row_class = 'online' if item['online'] else 'offline'
  531. self.wfile.write('<tr class="{0}">'.format(row_class))
  532. self.wfile.write('<td title="{0}">{1}</td>'.format(
  533. item['key'],
  534. ' / '.join(item['names']) if len(item['names']) > 0 else '?',
  535. ))
  536. for conntype in ['active', 'last']:
  537. for gateway in gateways:
  538. remote = ''
  539. if conntype in item['remote'] and \
  540. gateway in item['remote'][conntype]:
  541. remote = item['remote'][conntype][gateway]
  542. if isinstance(remote, dict):
  543. remote = remote['name']
  544. symbol = '&check;' if len(remote) > 0 else '&times;'
  545. self.wfile.write('<td title="{0}">{1}</td>'.format(
  546. remote, symbol))
  547. self.wfile.write('</tr>\n')
  548. self.wfile.write('</table>\n')
  549. self.wfile.write('</body>')
  550. self.wfile.write('</html>')
  551. def __respond_providers(self, query):
  552. """Return a summary of providers."""
  553. outputformat = query['format'].lower() if 'format' in query else 'html'
  554. isps = {}
  555. ispblocks = {}
  556. for item in self.server.storage.get_vpn_connections():
  557. if item['count']['active'] == 0:
  558. continue
  559. remotes = []
  560. for gateway in item['remote']['active']:
  561. remote = item['remote']['active'][gateway]
  562. remotes.append(remote)
  563. if len(remotes) == 0:
  564. self.logger.warn(
  565. 'VPN key \'%s\' is marked with active remotes but 0 found?',
  566. item['key'])
  567. continue
  568. item_isps = set()
  569. for remote in remotes:
  570. isp = "UNKNOWN"
  571. ispblock = remote
  572. if isinstance(remote, dict):
  573. ispblock = remote['name']
  574. desc_lines = remote['description'].split('\n')
  575. isp = normalize_ispname(desc_lines[0])
  576. if not isp in ispblocks:
  577. ispblocks[isp] = set()
  578. ispblocks[isp].add(ispblock)
  579. item_isps.add(isp)
  580. if len(item_isps) == 0:
  581. item_isps.add('unknown')
  582. elif len(item_isps) > 1:
  583. self.logger.warn(
  584. 'VPN key \'%s\' has %d active IPs ' +
  585. 'which resolved to %d ISPs: \'%s\'',
  586. item['key'],
  587. len(remotes),
  588. len(item_isps),
  589. '\', \''.join(item_isps)
  590. )
  591. for isp in item_isps:
  592. if not isp in isps:
  593. isps[isp] = 0
  594. isps[isp] += 1.0 / len(item_isps)
  595. isps_sum = sum([isps[x] for x in isps])
  596. if outputformat == 'csv':
  597. self.__send_headers('text/csv')
  598. self.wfile.write('Count;Name\n')
  599. for isp in isps:
  600. self.wfile.write('{0};"{1}"\n'.format(isps[isp], isp))
  601. elif outputformat == 'json':
  602. self.__send_headers('application/json',
  603. extra={'Content-Disposition': 'inline'})
  604. data = [
  605. {
  606. 'name': isp,
  607. 'count': isps[isp],
  608. 'percentage': isps[isp]*100.0/isps_sum,
  609. 'blocks': [block for block in ispblocks[isp]],
  610. } for isp in isps
  611. ]
  612. self.wfile.write(json.dumps(data))
  613. elif outputformat == 'html':
  614. self.__send_headers()
  615. self.wfile.write('''<!DOCTYPE html>
  616. <html>
  617. <head><title>BATCAVE - PROVIDERS</title></head>
  618. <body>
  619. <table border="2">
  620. <thead>
  621. <tr><th>Count</th><th>Percentage</th><th>Name</th><th>Blocks</th></tr>
  622. </thead>
  623. <tbody>\n''')
  624. for isp in sorted(isps, key=lambda x: isps[x], reverse=True):
  625. self.wfile.write('<tr><td>{0}</td><td>{1:.1f}%</td><td>{2}</td><td>{3}</td></tr>\n'.format(
  626. isps[isp],
  627. isps[isp]*100.0/isps_sum,
  628. isp,
  629. ', '.join(sorted(ispblocks[isp])) if isp in ispblocks else '?',
  630. ))
  631. self.wfile.write('</tbody></table>\n')
  632. self.wfile.write('<p>Totals: {0} ISPs, {1} connections</p>\n'.format(len(isps), isps_sum))
  633. self.wfile.write('</body></html>')
  634. else:
  635. self.send_error(400, 'Unknown output format.')
  636. class ApiServer(ThreadingMixIn, HTTPServer):
  637. def __init__(self, endpoint, storage):
  638. if ':' in endpoint[0]:
  639. self.address_family = socket.AF_INET6
  640. HTTPServer.__init__(self, endpoint, BatcaveHttpRequestHandler)
  641. self.storage = storage
  642. def __str__(self):
  643. return 'ApiServer on {0}'.format(self.server_address)
  644. if __name__ == '__main__':
  645. dummystorage = ffstatus.basestorage.BaseStorage()
  646. server = ApiServer(('0.0.0.0', 8888), dummystorage)
  647. print("Server:", str(server))
  648. server.serve_forever()