basestorage.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function, unicode_literals
  4. import logging
  5. import re
  6. import time
  7. import ffstatus
  8. from .exceptions import VpnKeyFormatError
  9. def sanitize_node(data, include_raw_data=False):
  10. """
  11. Filters potentially harmful entries from the node's data.
  12. """
  13. export = ffstatus.dict_merge({}, data)
  14. # remove fields from output: __RAW__
  15. if '__RAW__' in export and not include_raw_data:
  16. del export['__RAW__']
  17. return export
  18. class BaseStorage(object):
  19. """
  20. Provides operations on the storage data.
  21. This class gets subclassed to actually write the data
  22. to a file, database, whatever.
  23. """
  24. DATAKEY_VPN = '__VPN__'
  25. FIELDKEY_UPDATED = '__UPDATED__'
  26. def open(self):
  27. """
  28. When overridden in a subclass,
  29. opens the persistent storage.
  30. """
  31. pass
  32. def save(self):
  33. """
  34. When overriden in a subclass,
  35. stores the data to a persistent storage.
  36. """
  37. pass
  38. def close(self):
  39. """
  40. When overridden in a subclass,
  41. closes the persistent storage.
  42. """
  43. pass
  44. @property
  45. def status(self):
  46. """Gets status information on the storage."""
  47. nodes = 0
  48. nodes_active = 0
  49. gateways = 0
  50. gateways_active = 0
  51. sum_clients = 0
  52. clients = set()
  53. for node in self.get_nodes():
  54. nodetype = node.get('type', 'node')
  55. if nodetype == 'gateway':
  56. gateways += 1
  57. if self.get_nodestatus(node=node) == 'active':
  58. gateways_active += 1
  59. continue
  60. nodes += 1
  61. nodemacs = [x for x in node.get('macs', [])]
  62. if 'mac' in node:
  63. nodemacs.append(node['mac'])
  64. if self.get_nodestatus(node=node) == 'active':
  65. nodes_active += 1
  66. sum_clients += node.get('clientcount', 0)
  67. for client in node.get('clients', []):
  68. if client in nodemacs:
  69. continue
  70. clients.add(client)
  71. return {
  72. 'clients_sum': sum_clients,
  73. 'clients_unique': len(clients),
  74. 'gateways': gateways,
  75. 'gateways_active': gateways_active,
  76. 'nodes': nodes,
  77. 'nodes_active': nodes_active,
  78. 'now': int(time.time()),
  79. }
  80. def merge_new_data(self, newdata):
  81. """Updates data in the storage by merging the new data."""
  82. if newdata is None or not isinstance(newdata, dict):
  83. raise ValueError("Expected a dict as new data.")
  84. # start merge on a copy of the current data
  85. current = {}
  86. for node in self.get_nodes():
  87. item_id = node['node_id']
  88. current[item_id] = ffstatus.dict_merge(node, {})
  89. current[item_id]['aliases'] = []
  90. current[item_id]['clients'] = []
  91. current[item_id]['neighbours'] = {}
  92. current[item_id]['type'] = 'node'
  93. if not item_id in newdata:
  94. continue
  95. if not '__RAW__' in current[item_id]:
  96. current[item_id]['__RAW__'] = {}
  97. if '__RAW__' in newdata[item_id]:
  98. for key in newdata[item_id]['__RAW__']:
  99. if key in current[item_id]['__RAW__']:
  100. del current[item_id]['__RAW__'][key]
  101. # merge the dictionaries
  102. updated = {}
  103. for itemid in newdata:
  104. if not itemid in current:
  105. # new element which did not exist in storage before, that's easy
  106. updated[itemid] = newdata[itemid]
  107. continue
  108. # merge the old and new element
  109. update = ffstatus.dict_merge(current[itemid], newdata[itemid])
  110. updated[itemid] = update
  111. # sanitize each item's data
  112. for itemid in updated:
  113. if itemid.startswith('__'):
  114. continue
  115. item = updated[itemid]
  116. # ensure 'node_id' is set
  117. if not 'node_id' in item:
  118. item['node_id'] = itemid
  119. # remove node's MACs from clients list
  120. clients = [x for x in item.get('clients', [])]
  121. if 'mac' in item and item['mac'] in clients:
  122. clients.remove(item['mac'])
  123. for mac in item.get('macs', []):
  124. if mac in clients:
  125. clients.remove(mac)
  126. # set clientcount
  127. item['clientcount'] = len(clients)
  128. # finally, set each new data
  129. self.set_node_data(itemid, item)
  130. def get_nodes(self, sortby=None, include_raw_data=False):
  131. """Gets a list of all known nodes."""
  132. nodes = self.get_all_nodes_raw()
  133. sorted_ids = [x for x in nodes]
  134. if sortby is not None:
  135. if sortby == 'name':
  136. sortkey = lambda x: nodes[x]['hostname'].lower()
  137. sorted_ids = sorted(sorted_ids, key=sortkey)
  138. elif sortby == 'id':
  139. sorted_ids = sorted(sorted_ids)
  140. result = []
  141. for nodeid in sorted_ids:
  142. if nodeid.startswith('__'):
  143. continue
  144. node = sanitize_node(nodes[nodeid], include_raw_data)
  145. result.append(node)
  146. return result
  147. def find_node(self, rawid, include_raw_data=False, search_aliases=True):
  148. """
  149. Fetch node data by given id.
  150. If necessary, look through node aliases.
  151. """
  152. # try direct match, first
  153. node = self.get_node(rawid)
  154. if node is not None:
  155. return sanitize_node(node, include_raw_data=include_raw_data)
  156. # look through all nodes
  157. found = None
  158. nodes = self.get_all_nodes_raw()
  159. for nodeid in nodes:
  160. node = nodes[nodeid]
  161. # if we have a direct hit, return it immediately
  162. if nodeid == rawid:
  163. return sanitize_node(node, include_raw_data=include_raw_data)
  164. # search through aliases
  165. if search_aliases and rawid in node.get('aliases', []):
  166. found = node
  167. # return found node
  168. if not found is None:
  169. return sanitize_node(found, include_raw_data=include_raw_data)
  170. else:
  171. return None
  172. def find_node_by_mac(self, mac):
  173. """Fetch node data by given MAC address."""
  174. needle = mac.lower()
  175. # iterate over all nodes
  176. for node in self.get_nodes():
  177. # check node's primary MAC
  178. if 'mac' in node and needle == node['mac'].lower():
  179. return sanitize_node(node)
  180. # check alias MACs
  181. if 'macs' in node:
  182. haystack = [x.lower() for x in node['macs']]
  183. if mac in haystack:
  184. return sanitize_node(node)
  185. # MAC address not found
  186. return None
  187. def get_nodestatus(self, rawid=None, node=None):
  188. """Determine node's status."""
  189. # search node by the given id
  190. if node is None and not rawid is None:
  191. node = self.find_node(rawid)
  192. # handle unknown nodes
  193. if node is None:
  194. return None
  195. # check that the last batadv update is noted in the data
  196. updated = node.get(self.FIELDKEY_UPDATED, None)
  197. if updated is None:
  198. return 'unknown'
  199. u = updated.get('batadv', updated.get('batctl'))
  200. if u is None:
  201. return 'unknown'
  202. # make decision based on time of last batadv update
  203. diff = time.time() - u
  204. if diff < 150:
  205. return 'active'
  206. elif diff < 300:
  207. return 'stale'
  208. else:
  209. return 'offline'
  210. def set_node_data(self, key, data):
  211. """
  212. Overwrite data for the node with the given key.
  213. Specifying 'None' as data effectively means deleting the key.
  214. """
  215. raise NotImplementedError("set_node_data was not overridden")
  216. def check_vpn_key(self, key):
  217. if key is None or re.match(r'^[a-fA-F0-9]+$', key) is None:
  218. raise VpnKeyFormatError(key)
  219. def get_vpn_keys(self):
  220. """Gets a list of VPN keys."""
  221. raise NotImplementedError("get_vpn_keys was not overriden")
  222. def get_vpn_item(self, key, create=False):
  223. self.check_vpn_key(key)
  224. raise NotImplementedError("store_vpn_item was not overriden")
  225. def store_vpn_item(self, key, data):
  226. raise NotImplementedError("store_vpn_item was not overriden")
  227. def resolve_vpn_remotes(self):
  228. """Iterates all remotes and resolves IP blocks not yet resolved."""
  229. vpn = self.get_vpn_keys()
  230. init_vpn_cache = {}
  231. for key in vpn:
  232. entry = self.get_vpn_item(key)
  233. entry_modified = False
  234. for mode in entry:
  235. if not isinstance(entry[mode], dict):
  236. continue
  237. for gateway in entry[mode]:
  238. if not isinstance(entry[mode][gateway], dict):
  239. continue
  240. item = entry[mode][gateway]
  241. if 'remote' in item and not 'remote_raw' in item:
  242. item['remote_raw'] = item['remote']
  243. resolved = None
  244. if item['remote'] in init_vpn_cache:
  245. resolved = init_vpn_cache[item['remote']]
  246. else:
  247. resolved = ffstatus.resolve_ipblock(item['remote'])
  248. init_vpn_cache[item['remote']] = resolved
  249. if resolved is not None:
  250. logging.info(
  251. 'Resolved VPN entry \'%s\' to net \'%s\'.',
  252. item['remote'],
  253. resolved['name'],
  254. )
  255. if resolved is not None:
  256. item['remote'] = resolved
  257. entry_modified = True
  258. if entry_modified:
  259. self.store_vpn_item(key, entry)
  260. def get_vpn_gateways(self):
  261. gateways = set()
  262. vpn = self.get_vpn_keys()
  263. for key in vpn:
  264. entry = self.get_vpn_item(key)
  265. for conntype in entry:
  266. for gateway in entry[conntype]:
  267. gateways.add(gateway)
  268. return sorted(gateways)
  269. def get_vpn_connections(self):
  270. conntypes = ['active', 'last']
  271. result = []
  272. vpnkeys = self.get_vpn_keys()
  273. for key in vpnkeys:
  274. vpn_entry = self.get_vpn_item(key)
  275. if not isinstance(vpn_entry, dict):
  276. continue
  277. item = {
  278. 'key': key,
  279. 'count': {},
  280. 'remote': {},
  281. }
  282. names = set()
  283. for conntype in conntypes:
  284. item['count'][conntype] = 0
  285. item['remote'][conntype] = {}
  286. if conntype in vpn_entry:
  287. for gateway in vpn_entry[conntype]:
  288. if 'remote' in vpn_entry[conntype][gateway]:
  289. remote = vpn_entry[conntype][gateway]['remote']
  290. if remote is None or remote == '':
  291. continue
  292. item['count'][conntype] += 1
  293. item['remote'][conntype][gateway] = remote
  294. if 'peer' in vpn_entry[conntype][gateway]:
  295. names.add(vpn_entry[conntype][gateway]['peer'])
  296. item['names'] = sorted(names)
  297. item['online'] = item['count']['active'] > 0
  298. result.append(item)
  299. return result
  300. def log_vpn_connect(self, key, peername, remote, gateway, timestamp):
  301. item = self.get_vpn_item(key, create=True)
  302. # resolve remote addr to its netblock
  303. remote_raw = remote
  304. remote_resolved = None
  305. if remote is not None:
  306. remote_resolved = ffstatus.resolve_ipblock(remote)
  307. if remote_resolved is not None:
  308. logging.debug('Resolved IP \'{0}\' to block \'{1}\'.'.format(
  309. remote, remote_resolved['name'],
  310. ))
  311. remote = remote_resolved
  312. # store connection info
  313. item['active'][gateway] = {
  314. 'establish': timestamp,
  315. 'peer': peername,
  316. 'remote': remote,
  317. 'remote_raw': remote_raw,
  318. }
  319. self.store_vpn_item(key, item)
  320. def log_vpn_disconnect(self, key, gateway, timestamp):
  321. item = self.get_vpn_item(key, create=True)
  322. active = {}
  323. if gateway in item['active']:
  324. active = item['active'][gateway]
  325. del item['active'][gateway]
  326. active['disestablish'] = timestamp
  327. item['last'][gateway] = active
  328. self.store_vpn_item(key, item)