basestorage.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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_alias_node(self, item, alias):
  81. # start by using standard dict_merge()
  82. update = ffstatus.dict_merge(item, alias, overwrite_lists=False)
  83. # extract some fields for further inspection
  84. update_macs = update.get('macs', []) or []
  85. # field 'node_id': keep original value
  86. update['node_id'] = item['node_id']
  87. # field 'mac': keep original value
  88. if 'mac' in item:
  89. update['mac'] = item['mac']
  90. if 'mac' in alias:
  91. update_macs.append(alias['mac'])
  92. # field 'macs': get rid of duplicates and primary mac
  93. primary_mac = update.get('mac')
  94. macs = []
  95. for x in update_macs:
  96. if x != primary_mac and x not in macs:
  97. macs.append(x)
  98. update['macs'] = update_macs = macs
  99. # field 'type': keep special node type
  100. item_type = item.get('type', 'node')
  101. if item_type != 'node' and update.get('type', 'node') == 'node':
  102. update['type'] = item_type
  103. return update
  104. def merge_new_data(self, newdata):
  105. """Updates data in the storage by merging the new data."""
  106. if newdata is None or not isinstance(newdata, dict):
  107. raise ValueError("Expected a dict as new data.")
  108. # keep a list of aliased nodes so they can be removed from the result
  109. aliased_nodes = {}
  110. # start merge on a copy of the current data
  111. current = {}
  112. for node in self.get_nodes():
  113. item_id = node['node_id']
  114. current[item_id] = ffstatus.dict_merge(node, {})
  115. current[item_id]['aliases'] = []
  116. current[item_id]['clients'] = []
  117. current[item_id]['neighbours'] = {}
  118. current[item_id]['type'] = 'node'
  119. if not item_id in newdata:
  120. continue
  121. if not '__RAW__' in current[item_id]:
  122. current[item_id]['__RAW__'] = {}
  123. if '__RAW__' in newdata[item_id]:
  124. for key in newdata[item_id]['__RAW__']:
  125. if key in current[item_id]['__RAW__']:
  126. del current[item_id]['__RAW__'][key]
  127. # merge the dictionaries
  128. updated = {}
  129. for itemid in newdata:
  130. if not itemid in current:
  131. # new element which did not exist in storage before, that's easy
  132. updated[itemid] = newdata[itemid]
  133. else:
  134. # merge the old and new element
  135. update = ffstatus.dict_merge(current[itemid], newdata[itemid])
  136. updated[itemid] = update
  137. for alias_id in updated[itemid].get('aliases', []):
  138. if alias_id in aliased_nodes:
  139. aliased_nodes[alias_id].append(itemid)
  140. else:
  141. aliased_nodes[alias_id] = [itemid]
  142. # merge aliased nodes
  143. for alias_id in aliased_nodes:
  144. if len(aliased_nodes[alias_id]) != 1:
  145. logging.warn("Node '%s' is aliased by multiple nodes: %s",
  146. alias_id, aliased_nodes[alias_id])
  147. continue
  148. # target's id is the single entry of the alias list
  149. item_id = aliased_nodes[alias_id][0]
  150. if alias_id == item_id:
  151. # the node has itself as alias -> remove the alias entry
  152. if alias_id in updated and 'aliases' in updated[alias_id]:
  153. updated[alias_id]['aliases'].remove(alias_id)
  154. logging.debug("Removed self-alias of '%s'.", alias_id)
  155. continue
  156. # look for alias node
  157. alias = updated.get(alias_id, current.get(alias_id))
  158. if alias is None:
  159. # no alias node present already, as we're trying to achieve here
  160. continue
  161. # look for target node
  162. item = updated.get(item_id, current.get(item_id))
  163. if item is None:
  164. logging.warn("Alias node '%s' is missing its target '%s.",
  165. alias_id, item_id)
  166. continue
  167. # merge data
  168. alias['node_id'] = alias_id
  169. update = self.__merge_alias_node(item, alias)
  170. updated[item_id] = update
  171. logging.debug("Merged alias '%s' into '%s'.", alias_id, item_id)
  172. # mark alias node for deletion
  173. updated[alias_id] = None
  174. # sanitize each item's data
  175. for itemid in updated:
  176. if itemid.startswith('__'):
  177. continue
  178. item = updated[itemid]
  179. # delete node if requested
  180. if item is None:
  181. self.set_node_data(itemid, None)
  182. continue
  183. # ensure 'node_id' is set
  184. if not 'node_id' in item:
  185. item['node_id'] = itemid
  186. # remove node's MACs from clients list
  187. clients = [x for x in item.get('clients', [])]
  188. if 'mac' in item and item['mac'] in clients:
  189. clients.remove(item['mac'])
  190. for mac in item.get('macs', []):
  191. if mac in clients:
  192. clients.remove(mac)
  193. # set clientcount
  194. item['clientcount'] = len(clients)
  195. # finally, set each new data
  196. self.set_node_data(itemid, item)
  197. def get_nodes(self, sortby=None, include_raw_data=False):
  198. """Gets a list of all known nodes."""
  199. nodes = self.get_all_nodes_raw()
  200. sorted_ids = [x for x in nodes]
  201. if sortby is not None:
  202. if sortby == 'name':
  203. sortkey = lambda x: nodes[x]['hostname'].lower()
  204. sorted_ids = sorted(sorted_ids, key=sortkey)
  205. elif sortby == 'id':
  206. sorted_ids = sorted(sorted_ids)
  207. result = []
  208. for nodeid in sorted_ids:
  209. if nodeid.startswith('__'):
  210. continue
  211. node = sanitize_node(nodes[nodeid], include_raw_data)
  212. result.append(node)
  213. return result
  214. def find_node(self, rawid, include_raw_data=False, search_aliases=True):
  215. """
  216. Fetch node data by given id.
  217. If necessary, look through node aliases.
  218. """
  219. # try direct match, first
  220. node = self.get_node(rawid)
  221. if node is not None:
  222. return sanitize_node(node, include_raw_data=include_raw_data)
  223. # look through all nodes
  224. found = None
  225. nodes = self.get_all_nodes_raw()
  226. for nodeid in nodes:
  227. node = nodes[nodeid]
  228. # if we have a direct hit, return it immediately
  229. if nodeid == rawid:
  230. return sanitize_node(node, include_raw_data=include_raw_data)
  231. # search through aliases
  232. if search_aliases and rawid in node.get('aliases', []):
  233. found = node
  234. # return found node
  235. if not found is None:
  236. return sanitize_node(found, include_raw_data=include_raw_data)
  237. else:
  238. return None
  239. def find_node_by_mac(self, mac):
  240. """Fetch node data by given MAC address."""
  241. needle = mac.lower()
  242. # iterate over all nodes
  243. for node in self.get_nodes():
  244. # check node's primary MAC
  245. if 'mac' in node and needle == node['mac'].lower():
  246. return sanitize_node(node)
  247. # check alias MACs
  248. if 'macs' in node:
  249. haystack = [x.lower() for x in node['macs']]
  250. if mac in haystack:
  251. return sanitize_node(node)
  252. # MAC address not found
  253. return None
  254. def get_nodestatus(self, rawid=None, node=None):
  255. """Determine node's status."""
  256. # search node by the given id
  257. if node is None and not rawid is None:
  258. node = self.find_node(rawid)
  259. # handle unknown nodes
  260. if node is None:
  261. return None
  262. # check that the last batadv update is noted in the data
  263. updated = node.get(self.FIELDKEY_UPDATED, None)
  264. if updated is None:
  265. return 'unknown'
  266. u = updated.get('batadv', updated.get('batctl'))
  267. if u is None:
  268. return 'unknown'
  269. # make decision based on time of last batadv update
  270. diff = time.time() - u
  271. if diff < 150:
  272. return 'active'
  273. elif diff < 300:
  274. return 'stale'
  275. else:
  276. return 'offline'
  277. def set_node_data(self, key, data):
  278. """
  279. Overwrite data for the node with the given key.
  280. Specifying 'None' as data effectively means deleting the key.
  281. """
  282. raise NotImplementedError("set_node_data was not overridden")
  283. def check_vpn_key(self, key):
  284. if key is None or re.match(r'^[a-fA-F0-9]+$', key) is None:
  285. raise VpnKeyFormatError(key)
  286. def get_vpn_keys(self):
  287. """Gets a list of VPN keys."""
  288. raise NotImplementedError("get_vpn_keys was not overriden")
  289. def get_vpn_item(self, key, create=False):
  290. self.check_vpn_key(key)
  291. raise NotImplementedError("store_vpn_item was not overriden")
  292. def store_vpn_item(self, key, data):
  293. raise NotImplementedError("store_vpn_item was not overriden")
  294. def resolve_vpn_remotes(self):
  295. """Iterates all remotes and resolves IP blocks not yet resolved."""
  296. vpn = self.get_vpn_keys()
  297. init_vpn_cache = {}
  298. for key in vpn:
  299. entry = self.get_vpn_item(key)
  300. entry_modified = False
  301. for mode in entry:
  302. if not isinstance(entry[mode], dict):
  303. continue
  304. for gateway in entry[mode]:
  305. if not isinstance(entry[mode][gateway], dict):
  306. continue
  307. item = entry[mode][gateway]
  308. if 'remote' in item and not 'remote_raw' in item:
  309. item['remote_raw'] = item['remote']
  310. resolved = None
  311. if item['remote'] in init_vpn_cache:
  312. resolved = init_vpn_cache[item['remote']]
  313. else:
  314. resolved = ffstatus.resolve_ipblock(item['remote'])
  315. init_vpn_cache[item['remote']] = resolved
  316. if resolved is not None:
  317. logging.info(
  318. 'Resolved VPN entry \'%s\' to net \'%s\'.',
  319. item['remote'],
  320. resolved['name'],
  321. )
  322. if resolved is not None:
  323. item['remote'] = resolved
  324. entry_modified = True
  325. if entry_modified:
  326. self.store_vpn_item(key, entry)
  327. def get_vpn_gateways(self):
  328. gateways = set()
  329. vpn = self.get_vpn_keys()
  330. for key in vpn:
  331. entry = self.get_vpn_item(key)
  332. for conntype in entry:
  333. for gateway in entry[conntype]:
  334. gateways.add(gateway)
  335. return sorted(gateways)
  336. def get_vpn_connections(self):
  337. conntypes = ['active', 'last']
  338. result = []
  339. vpnkeys = self.get_vpn_keys()
  340. for key in vpnkeys:
  341. vpn_entry = self.get_vpn_item(key)
  342. if not isinstance(vpn_entry, dict):
  343. continue
  344. item = {
  345. 'key': key,
  346. 'count': {},
  347. 'remote': {},
  348. }
  349. names = set()
  350. for conntype in conntypes:
  351. item['count'][conntype] = 0
  352. item['remote'][conntype] = {}
  353. if conntype in vpn_entry:
  354. for gateway in vpn_entry[conntype]:
  355. if 'remote' in vpn_entry[conntype][gateway]:
  356. remote = vpn_entry[conntype][gateway]['remote']
  357. if remote is None or remote == '':
  358. continue
  359. item['count'][conntype] += 1
  360. item['remote'][conntype][gateway] = remote
  361. if 'peer' in vpn_entry[conntype][gateway]:
  362. names.add(vpn_entry[conntype][gateway]['peer'])
  363. item['names'] = sorted(names)
  364. item['online'] = item['count']['active'] > 0
  365. result.append(item)
  366. return result
  367. def log_vpn_connect(self, key, peername, remote, gateway, timestamp):
  368. item = self.get_vpn_item(key, create=True)
  369. # resolve remote addr to its netblock
  370. remote_raw = remote
  371. remote_resolved = None
  372. if remote is not None:
  373. remote_resolved = ffstatus.resolve_ipblock(remote)
  374. if remote_resolved is not None:
  375. logging.debug('Resolved IP \'{0}\' to block \'{1}\'.'.format(
  376. remote, remote_resolved['name'],
  377. ))
  378. remote = remote_resolved
  379. # store connection info
  380. item['active'][gateway] = {
  381. 'establish': timestamp,
  382. 'peer': peername,
  383. 'remote': remote,
  384. 'remote_raw': remote_raw,
  385. }
  386. self.store_vpn_item(key, item)
  387. def log_vpn_disconnect(self, key, gateway, timestamp):
  388. item = self.get_vpn_item(key, create=True)
  389. active = {}
  390. if gateway in item['active']:
  391. active = item['active'][gateway]
  392. del item['active'][gateway]
  393. active['disestablish'] = timestamp
  394. item['last'][gateway] = active
  395. self.store_vpn_item(key, item)