basestorage.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. sum_clients = 0
  50. clients = set()
  51. for node in self.get_nodes():
  52. nodes += 1
  53. nodemacs = [x for x in node.get('macs', [])]
  54. if 'mac' in node:
  55. nodemacs.append(node['mac'])
  56. if self.get_nodestatus(node=node) == 'active':
  57. nodes_active += 1
  58. sum_clients += node.get('clientcount', 0)
  59. for client in node.get('clients', []):
  60. if client in nodemacs:
  61. continue
  62. clients.add(client)
  63. return {
  64. 'clients_sum': sum_clients,
  65. 'clients_unique': len(clients),
  66. 'nodes': nodes,
  67. 'nodes_active': nodes_active,
  68. 'now': int(time.time()),
  69. }
  70. def merge_new_data(self, newdata):
  71. """Updates data in the storage by merging the new data."""
  72. if newdata is None or not isinstance(newdata, dict):
  73. raise ValueError("Expected a dict as new data.")
  74. # start merge on a copy of the current data
  75. current = {}
  76. for node in self.get_nodes():
  77. item_id = node['node_id']
  78. current[item_id] = ffstatus.dict_merge(node, {})
  79. current[item_id]['aliases'] = []
  80. current[item_id]['clients'] = []
  81. current[item_id]['neighbours'] = {}
  82. current[item_id]['type'] = 'node'
  83. if not item_id in newdata:
  84. continue
  85. if not '__RAW__' in current[item_id]:
  86. current[item_id]['__RAW__'] = {}
  87. if '__RAW__' in newdata[item_id]:
  88. for key in newdata[item_id]['__RAW__']:
  89. if key in current[item_id]['__RAW__']:
  90. del current[item_id]['__RAW__'][key]
  91. # merge the dictionaries
  92. updated = {}
  93. for itemid in newdata:
  94. if not itemid in current:
  95. # new element which did not exist in storage before, that's easy
  96. updated[itemid] = newdata[itemid]
  97. continue
  98. # merge the old and new element
  99. update = ffstatus.dict_merge(current[itemid], newdata[itemid])
  100. updated[itemid] = update
  101. # sanitize each item's data
  102. for itemid in updated:
  103. if itemid.startswith('__'):
  104. continue
  105. item = updated[itemid]
  106. # ensure 'node_id' is set
  107. if not 'node_id' in item:
  108. item['node_id'] = itemid
  109. # remove node's MACs from clients list
  110. clients = [x for x in item.get('clients', [])]
  111. if 'mac' in item and item['mac'] in clients:
  112. clients.remove(item['mac'])
  113. for mac in item.get('macs', []):
  114. if mac in clients:
  115. clients.remove(mac)
  116. # set clientcount
  117. item['clientcount'] = len(clients)
  118. # finally, set each new data
  119. self.set_node_data(itemid, item)
  120. def get_nodes(self, sortby=None, include_raw_data=False):
  121. """Gets a list of all known nodes."""
  122. nodes = self.get_all_nodes_raw()
  123. sorted_ids = [x for x in nodes]
  124. if sortby is not None:
  125. if sortby == 'name':
  126. sortkey = lambda x: nodes[x]['hostname'].lower()
  127. sorted_ids = sorted(sorted_ids, key=sortkey)
  128. elif sortby == 'id':
  129. sorted_ids = sorted(sorted_ids)
  130. result = []
  131. for nodeid in sorted_ids:
  132. if nodeid.startswith('__'):
  133. continue
  134. node = sanitize_node(nodes[nodeid], include_raw_data)
  135. result.append(node)
  136. return result
  137. def find_node(self, rawid, include_raw_data=False):
  138. """
  139. Fetch node data by given id.
  140. If necessary, look through node aliases.
  141. """
  142. # look through all nodes
  143. found = None
  144. nodes = self.get_all_nodes_raw()
  145. for nodeid in nodes:
  146. node = nodes[nodeid]
  147. # if we have a direct hit, return it immediately
  148. if nodeid == rawid:
  149. return sanitize_node(node, include_raw_data=include_raw_data)
  150. # search through aliases
  151. if 'aliases' in node and rawid in node['aliases']:
  152. found = node
  153. # return found node
  154. if not found is None:
  155. return sanitize_node(found, include_raw_data=include_raw_data)
  156. else:
  157. return None
  158. def find_node_by_mac(self, mac):
  159. """Fetch node data by given MAC address."""
  160. needle = mac.lower()
  161. # iterate over all nodes
  162. for node in self.get_nodes():
  163. # check node's primary MAC
  164. if 'mac' in node and needle == node['mac'].lower():
  165. return sanitize_node(node)
  166. # check alias MACs
  167. if 'macs' in node:
  168. haystack = [x.lower() for x in node['macs']]
  169. if mac in haystack:
  170. return sanitize_node(node)
  171. # MAC address not found
  172. return None
  173. def get_nodestatus(self, rawid=None, node=None):
  174. """Determine node's status."""
  175. # search node by the given id
  176. if node is None and not rawid is None:
  177. node = self.find_node(rawid)
  178. # handle unknown nodes
  179. if node is None:
  180. return None
  181. # check that the last batadv update is noted in the data
  182. updated = node.get(self.FIELDKEY_UPDATED, None)
  183. if updated is None:
  184. return 'unknown'
  185. u = updated.get('batadv', updated.get('batctl'))
  186. if u is None:
  187. return 'unknown'
  188. # make decision based on time of last batadv update
  189. diff = time.time() - u
  190. if diff < 150:
  191. return 'active'
  192. elif diff < 300:
  193. return 'stale'
  194. else:
  195. return 'offline'
  196. def set_node_data(self, key, data):
  197. """Overwrite data for the node with the given key."""
  198. raise NotImplementedError("set_node_data was not overridden")
  199. def check_vpn_key(self, key):
  200. if key is None or re.match(r'^[a-fA-F0-9]+$', key) is None:
  201. raise VpnKeyFormatError(key)
  202. def get_vpn_keys(self):
  203. """Gets a list of VPN keys."""
  204. raise NotImplementedError("get_vpn_keys was not overriden")
  205. def get_vpn_item(self, key, create=False):
  206. self.check_vpn_key(key)
  207. raise NotImplementedError("store_vpn_item was not overriden")
  208. def store_vpn_item(self, key, data):
  209. raise NotImplementedError("store_vpn_item was not overriden")
  210. def resolve_vpn_remotes(self):
  211. """Iterates all remotes and resolves IP blocks not yet resolved."""
  212. vpn = self.get_vpn_keys()
  213. init_vpn_cache = {}
  214. for key in vpn:
  215. entry = self.get_vpn_item(key)
  216. entry_modified = False
  217. for mode in entry:
  218. if not isinstance(entry[mode], dict):
  219. continue
  220. for gateway in entry[mode]:
  221. if not isinstance(entry[mode][gateway], dict):
  222. continue
  223. item = entry[mode][gateway]
  224. if 'remote' in item and not 'remote_raw' in item:
  225. item['remote_raw'] = item['remote']
  226. resolved = None
  227. if item['remote'] in init_vpn_cache:
  228. resolved = init_vpn_cache[item['remote']]
  229. else:
  230. resolved = ffstatus.resolve_ipblock(item['remote'])
  231. init_vpn_cache[item['remote']] = resolved
  232. if resolved is not None:
  233. logging.info(
  234. 'Resolved VPN entry \'%s\' to net \'%s\'.',
  235. item['remote'],
  236. resolved['name'],
  237. )
  238. if resolved is not None:
  239. item['remote'] = resolved
  240. entry_modified = True
  241. if entry_modified:
  242. self.store_vpn_item(key, entry)
  243. def get_vpn_gateways(self):
  244. gateways = set()
  245. vpn = self.get_vpn_keys()
  246. for key in vpn:
  247. entry = self.get_vpn_item(key)
  248. for conntype in entry:
  249. for gateway in entry[conntype]:
  250. gateways.add(gateway)
  251. return sorted(gateways)
  252. def get_vpn_connections(self):
  253. conntypes = ['active', 'last']
  254. result = []
  255. vpnkeys = self.get_vpn_keys()
  256. for key in vpnkeys:
  257. vpn_entry = self.get_vpn_item(key)
  258. if not isinstance(vpn_entry, dict):
  259. continue
  260. item = {
  261. 'key': key,
  262. 'count': {},
  263. 'remote': {},
  264. }
  265. names = set()
  266. for conntype in conntypes:
  267. item['count'][conntype] = 0
  268. item['remote'][conntype] = {}
  269. if conntype in vpn_entry:
  270. for gateway in vpn_entry[conntype]:
  271. if 'remote' in vpn_entry[conntype][gateway]:
  272. remote = vpn_entry[conntype][gateway]['remote']
  273. if remote is None or remote == '':
  274. continue
  275. item['count'][conntype] += 1
  276. item['remote'][conntype][gateway] = remote
  277. if 'peer' in vpn_entry[conntype][gateway]:
  278. names.add(vpn_entry[conntype][gateway]['peer'])
  279. item['names'] = sorted(names)
  280. item['online'] = item['count']['active'] > 0
  281. result.append(item)
  282. return result
  283. def log_vpn_connect(self, key, peername, remote, gateway, timestamp):
  284. item = self.get_vpn_item(key, create=True)
  285. # resolve remote addr to its netblock
  286. remote_raw = remote
  287. remote_resolved = None
  288. if remote is not None:
  289. remote_resolved = ffstatus.resolve_ipblock(remote)
  290. if remote_resolved is not None:
  291. logging.debug('Resolved IP \'{0}\' to block \'{1}\'.'.format(
  292. remote, remote_resolved['name'],
  293. ))
  294. remote = remote_resolved
  295. # store connection info
  296. item['active'][gateway] = {
  297. 'establish': timestamp,
  298. 'peer': peername,
  299. 'remote': remote,
  300. 'remote_raw': remote_raw,
  301. }
  302. self.store_vpn_item(key, item)
  303. def log_vpn_disconnect(self, key, gateway, timestamp):
  304. item = self.get_vpn_item(key, create=True)
  305. active = {}
  306. if gateway in item['active']:
  307. active = item['active'][gateway]
  308. del item['active'][gateway]
  309. active['disestablish'] = timestamp
  310. item['last'][gateway] = active
  311. self.store_vpn_item(key, item)