basestorage.py 11 KB

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