basestorage.py 12 KB

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