updateFallbackDirs.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  1. #!/usr/bin/python
  2. # Usage: scripts/maint/updateFallbackDirs.py > src/or/fallback_dirs.inc
  3. # Needs stem available in your PYTHONPATH, or just ln -s ../stem/stem .
  4. #
  5. # Then read the generated list to ensure no-one slipped anything funny into
  6. # their name or contactinfo
  7. # Script by weasel, April 2015
  8. # Portions by gsathya & karsten, 2013
  9. # https://trac.torproject.org/projects/tor/attachment/ticket/8374/dir_list.2.py
  10. # Modifications by teor, 2015
  11. import StringIO
  12. import string
  13. import re
  14. import datetime
  15. import gzip
  16. import os.path
  17. import json
  18. import math
  19. import sys
  20. import urllib
  21. import urllib2
  22. import hashlib
  23. import dateutil.parser
  24. # bson_lazy provides bson
  25. #from bson import json_util
  26. from stem.descriptor.remote import DescriptorDownloader
  27. import logging
  28. # INFO tells you why each relay was included or excluded
  29. # WARN tells you about potential misconfigurations
  30. logging.basicConfig(level=logging.WARNING)
  31. ## Top-Level Configuration
  32. # Output all candidate fallbacks, or only output selected fallbacks?
  33. OUTPUT_CANDIDATES = False
  34. # Perform DirPort checks over IPv4?
  35. # Change this to False if IPv4 doesn't work for you, or if you don't want to
  36. # download a consensus for each fallback
  37. # Don't check ~1000 candidates when OUTPUT_CANDIDATES is True
  38. PERFORM_IPV4_DIRPORT_CHECKS = False if OUTPUT_CANDIDATES else True
  39. # Perform DirPort checks over IPv6?
  40. # If you know IPv6 works for you, set this to True
  41. # This will exclude IPv6 relays without an IPv6 DirPort configured
  42. # So it's best left at False until #18394 is implemented
  43. # Don't check ~1000 candidates when OUTPUT_CANDIDATES is True
  44. PERFORM_IPV6_DIRPORT_CHECKS = False if OUTPUT_CANDIDATES else False
  45. ## OnionOO Settings
  46. ONIONOO = 'https://onionoo.torproject.org/'
  47. #ONIONOO = 'https://onionoo.thecthulhu.com/'
  48. # Don't bother going out to the Internet, just use the files available locally,
  49. # even if they're very old
  50. LOCAL_FILES_ONLY = False
  51. ## Whitelist / Blacklist Filter Settings
  52. # The whitelist contains entries that are included if all attributes match
  53. # (IPv4, dirport, orport, id, and optionally IPv6 and IPv6 orport)
  54. # The blacklist contains (partial) entries that are excluded if any
  55. # sufficiently specific group of attributes matches:
  56. # IPv4 & DirPort
  57. # IPv4 & ORPort
  58. # ID
  59. # IPv6 & DirPort
  60. # IPv6 & IPv6 ORPort
  61. # If neither port is included in the blacklist, the entire IP address is
  62. # blacklisted.
  63. # What happens to entries in neither list?
  64. # When True, they are included, when False, they are excluded
  65. INCLUDE_UNLISTED_ENTRIES = True if OUTPUT_CANDIDATES else False
  66. # If an entry is in both lists, what happens?
  67. # When True, it is excluded, when False, it is included
  68. BLACKLIST_EXCLUDES_WHITELIST_ENTRIES = True
  69. WHITELIST_FILE_NAME = 'scripts/maint/fallback.whitelist'
  70. BLACKLIST_FILE_NAME = 'scripts/maint/fallback.blacklist'
  71. # The number of bytes we'll read from a filter file before giving up
  72. MAX_LIST_FILE_SIZE = 1024 * 1024
  73. ## Eligibility Settings
  74. # Reduced due to a bug in tor where a relay submits a 0 DirPort when restarted
  75. # This causes OnionOO to (correctly) reset its stability timer
  76. # This issue will be fixed in 0.2.7.7 and 0.2.8.2
  77. # Until then, the CUTOFFs below ensure a decent level of stability.
  78. ADDRESS_AND_PORT_STABLE_DAYS = 7
  79. # What time-weighted-fraction of these flags must FallbackDirs
  80. # Equal or Exceed?
  81. CUTOFF_RUNNING = .95
  82. CUTOFF_V2DIR = .95
  83. CUTOFF_GUARD = .95
  84. # What time-weighted-fraction of these flags must FallbackDirs
  85. # Equal or Fall Under?
  86. # .00 means no bad exits
  87. PERMITTED_BADEXIT = .00
  88. # Clients will time out after 30 seconds trying to download a consensus
  89. # So allow fallback directories half that to deliver a consensus
  90. # The exact download times might change based on the network connection
  91. # running this script, but only by a few seconds
  92. # There is also about a second of python overhead
  93. CONSENSUS_DOWNLOAD_SPEED_MAX = 15.0
  94. # If the relay fails a consensus check, retry the download
  95. # This avoids delisting a relay due to transient network conditions
  96. CONSENSUS_DOWNLOAD_RETRY = True
  97. ## List Length Limits
  98. # The target for these parameters is 20% of the guards in the network
  99. # This is around 200 as of October 2015
  100. _FB_POG = 0.2
  101. FALLBACK_PROPORTION_OF_GUARDS = None if OUTPUT_CANDIDATES else _FB_POG
  102. # Limit the number of fallbacks (eliminating lowest by weight)
  103. MAX_FALLBACK_COUNT = None if OUTPUT_CANDIDATES else 500
  104. # Emit a C #error if the number of fallbacks is below
  105. MIN_FALLBACK_COUNT = 100
  106. ## Fallback Weight Settings
  107. # Any fallback with the Exit flag has its consensus weight multipled by this
  108. EXIT_WEIGHT_FRACTION = 1.0
  109. # If a single fallback's consensus weight is too low, it's pointless adding it
  110. # We expect fallbacks to handle an extra 30 kilobytes per second of traffic
  111. # Make sure they support a hundred times that
  112. MIN_CONSENSUS_WEIGHT = 30.0 * 100.0
  113. # All fallback weights are equal, and set to the value below
  114. # Authorities are weighted 1.0 by default
  115. # Clients use these weights to select fallbacks and authorities at random
  116. # If there are 100 fallbacks and 9 authorities:
  117. # - each fallback is chosen with probability 10/(1000 + 9) ~= 0.99%
  118. # - each authority is chosen with probability 1/(1000 + 9) ~= 0.09%
  119. FALLBACK_OUTPUT_WEIGHT = 10.0
  120. ## Other Configuration Parameters
  121. # older entries' weights are adjusted with ALPHA^(age in days)
  122. AGE_ALPHA = 0.99
  123. # this factor is used to scale OnionOO entries to [0,1]
  124. ONIONOO_SCALE_ONE = 999.
  125. ## Parsing Functions
  126. def parse_ts(t):
  127. return datetime.datetime.strptime(t, "%Y-%m-%d %H:%M:%S")
  128. def remove_bad_chars(raw_string, bad_char_list):
  129. # Remove each character in the bad_char_list
  130. cleansed_string = raw_string
  131. for c in bad_char_list:
  132. cleansed_string = cleansed_string.replace(c, '')
  133. return cleansed_string
  134. def cleanse_unprintable(raw_string):
  135. # Remove all unprintable characters
  136. cleansed_string = ''
  137. for c in raw_string:
  138. if (c in string.ascii_letters or c in string.digits
  139. or c in string.punctuation or c in string.whitespace):
  140. cleansed_string += c
  141. return cleansed_string
  142. def cleanse_whitespace(raw_string):
  143. # Replace all whitespace characters with a space
  144. cleansed_string = raw_string
  145. for c in string.whitespace:
  146. cleansed_string = cleansed_string.replace(c, ' ')
  147. return cleansed_string
  148. def cleanse_c_multiline_comment(raw_string):
  149. cleansed_string = raw_string
  150. # Embedded newlines should be removed by tor/onionoo, but let's be paranoid
  151. cleansed_string = cleanse_whitespace(cleansed_string)
  152. # ContactInfo and Version can be arbitrary binary data
  153. cleansed_string = cleanse_unprintable(cleansed_string)
  154. # Prevent a malicious / unanticipated string from breaking out
  155. # of a C-style multiline comment
  156. # This removes '/*' and '*/' and '//'
  157. bad_char_list = '*/'
  158. # Prevent a malicious string from using C nulls
  159. bad_char_list += '\0'
  160. # Be safer by removing bad characters entirely
  161. cleansed_string = remove_bad_chars(cleansed_string, bad_char_list)
  162. # Some compilers may further process the content of comments
  163. # There isn't much we can do to cover every possible case
  164. # But comment-based directives are typically only advisory
  165. return cleansed_string
  166. def cleanse_c_string(raw_string):
  167. cleansed_string = raw_string
  168. # Embedded newlines should be removed by tor/onionoo, but let's be paranoid
  169. cleansed_string = cleanse_whitespace(cleansed_string)
  170. # ContactInfo and Version can be arbitrary binary data
  171. cleansed_string = cleanse_unprintable(cleansed_string)
  172. # Prevent a malicious address/fingerprint string from breaking out
  173. # of a C-style string
  174. bad_char_list = '"'
  175. # Prevent a malicious string from using escapes
  176. bad_char_list += '\\'
  177. # Prevent a malicious string from using C nulls
  178. bad_char_list += '\0'
  179. # Be safer by removing bad characters entirely
  180. cleansed_string = remove_bad_chars(cleansed_string, bad_char_list)
  181. # Some compilers may further process the content of strings
  182. # There isn't much we can do to cover every possible case
  183. # But this typically only results in changes to the string data
  184. return cleansed_string
  185. ## OnionOO Source Functions
  186. # a dictionary of source metadata for each onionoo query we've made
  187. fetch_source = {}
  188. # register source metadata for 'what'
  189. # assumes we only retrieve one document for each 'what'
  190. def register_fetch_source(what, url, relays_published, version):
  191. fetch_source[what] = {}
  192. fetch_source[what]['url'] = url
  193. fetch_source[what]['relays_published'] = relays_published
  194. fetch_source[what]['version'] = version
  195. # list each registered source's 'what'
  196. def fetch_source_list():
  197. return sorted(fetch_source.keys())
  198. # given 'what', provide a multiline C comment describing the source
  199. def describe_fetch_source(what):
  200. desc = '/*'
  201. desc += '\n'
  202. desc += 'Onionoo Source: '
  203. desc += cleanse_c_multiline_comment(what)
  204. desc += ' Date: '
  205. desc += cleanse_c_multiline_comment(fetch_source[what]['relays_published'])
  206. desc += ' Version: '
  207. desc += cleanse_c_multiline_comment(fetch_source[what]['version'])
  208. desc += '\n'
  209. desc += 'URL: '
  210. desc += cleanse_c_multiline_comment(fetch_source[what]['url'])
  211. desc += '\n'
  212. desc += '*/'
  213. return desc
  214. ## File Processing Functions
  215. def write_to_file(str, file_name, max_len):
  216. try:
  217. with open(file_name, 'w') as f:
  218. f.write(str[0:max_len])
  219. except EnvironmentError, error:
  220. logging.warning('Writing file %s failed: %d: %s'%
  221. (file_name,
  222. error.errno,
  223. error.strerror)
  224. )
  225. def read_from_file(file_name, max_len):
  226. try:
  227. if os.path.isfile(file_name):
  228. with open(file_name, 'r') as f:
  229. return f.read(max_len)
  230. except EnvironmentError, error:
  231. logging.info('Loading file %s failed: %d: %s'%
  232. (file_name,
  233. error.errno,
  234. error.strerror)
  235. )
  236. return None
  237. def load_possibly_compressed_response_json(response):
  238. if response.info().get('Content-Encoding') == 'gzip':
  239. buf = StringIO.StringIO( response.read() )
  240. f = gzip.GzipFile(fileobj=buf)
  241. return json.load(f)
  242. else:
  243. return json.load(response)
  244. def load_json_from_file(json_file_name):
  245. # An exception here may be resolved by deleting the .last_modified
  246. # and .json files, and re-running the script
  247. try:
  248. with open(json_file_name, 'r') as f:
  249. return json.load(f)
  250. except EnvironmentError, error:
  251. raise Exception('Reading not-modified json file %s failed: %d: %s'%
  252. (json_file_name,
  253. error.errno,
  254. error.strerror)
  255. )
  256. ## OnionOO Functions
  257. def datestr_to_datetime(datestr):
  258. # Parse datetimes like: Fri, 02 Oct 2015 13:34:14 GMT
  259. if datestr is not None:
  260. dt = dateutil.parser.parse(datestr)
  261. else:
  262. # Never modified - use start of epoch
  263. dt = datetime.datetime.utcfromtimestamp(0)
  264. # strip any timezone out (in case they're supported in future)
  265. dt = dt.replace(tzinfo=None)
  266. return dt
  267. def onionoo_fetch(what, **kwargs):
  268. params = kwargs
  269. params['type'] = 'relay'
  270. #params['limit'] = 10
  271. params['first_seen_days'] = '%d-'%(ADDRESS_AND_PORT_STABLE_DAYS,)
  272. params['last_seen_days'] = '-7'
  273. params['flag'] = 'V2Dir'
  274. url = ONIONOO + what + '?' + urllib.urlencode(params)
  275. # Unfortunately, the URL is too long for some OS filenames,
  276. # but we still don't want to get files from different URLs mixed up
  277. base_file_name = what + '-' + hashlib.sha1(url).hexdigest()
  278. full_url_file_name = base_file_name + '.full_url'
  279. MAX_FULL_URL_LENGTH = 1024
  280. last_modified_file_name = base_file_name + '.last_modified'
  281. MAX_LAST_MODIFIED_LENGTH = 64
  282. json_file_name = base_file_name + '.json'
  283. if LOCAL_FILES_ONLY:
  284. # Read from the local file, don't write to anything
  285. response_json = load_json_from_file(json_file_name)
  286. else:
  287. # store the full URL to a file for debugging
  288. # no need to compare as long as you trust SHA-1
  289. write_to_file(url, full_url_file_name, MAX_FULL_URL_LENGTH)
  290. request = urllib2.Request(url)
  291. request.add_header('Accept-encoding', 'gzip')
  292. # load the last modified date from the file, if it exists
  293. last_mod_date = read_from_file(last_modified_file_name,
  294. MAX_LAST_MODIFIED_LENGTH)
  295. if last_mod_date is not None:
  296. request.add_header('If-modified-since', last_mod_date)
  297. # Parse last modified date
  298. last_mod = datestr_to_datetime(last_mod_date)
  299. # Not Modified and still recent enough to be useful
  300. # Onionoo / Globe used to use 6 hours, but we can afford a day
  301. required_freshness = datetime.datetime.utcnow()
  302. # strip any timezone out (to match dateutil.parser)
  303. required_freshness = required_freshness.replace(tzinfo=None)
  304. required_freshness -= datetime.timedelta(hours=24)
  305. # Make the OnionOO request
  306. response_code = 0
  307. try:
  308. response = urllib2.urlopen(request)
  309. response_code = response.getcode()
  310. except urllib2.HTTPError, error:
  311. response_code = error.code
  312. if response_code == 304: # not modified
  313. pass
  314. else:
  315. raise Exception("Could not get " + url + ": "
  316. + str(error.code) + ": " + error.reason)
  317. if response_code == 200: # OK
  318. last_mod = datestr_to_datetime(response.info().get('Last-Modified'))
  319. # Check for freshness
  320. if last_mod < required_freshness:
  321. if last_mod_date is not None:
  322. # This check sometimes fails transiently, retry the script if it does
  323. date_message = "Outdated data: last updated " + last_mod_date
  324. else:
  325. date_message = "No data: never downloaded "
  326. raise Exception(date_message + " from " + url)
  327. # Process the data
  328. if response_code == 200: # OK
  329. response_json = load_possibly_compressed_response_json(response)
  330. with open(json_file_name, 'w') as f:
  331. # use the most compact json representation to save space
  332. json.dump(response_json, f, separators=(',',':'))
  333. # store the last modified date in its own file
  334. if response.info().get('Last-modified') is not None:
  335. write_to_file(response.info().get('Last-Modified'),
  336. last_modified_file_name,
  337. MAX_LAST_MODIFIED_LENGTH)
  338. elif response_code == 304: # Not Modified
  339. response_json = load_json_from_file(json_file_name)
  340. else: # Unexpected HTTP response code not covered in the HTTPError above
  341. raise Exception("Unexpected HTTP response code to " + url + ": "
  342. + str(response_code))
  343. register_fetch_source(what,
  344. url,
  345. response_json['relays_published'],
  346. response_json['version'])
  347. return response_json
  348. def fetch(what, **kwargs):
  349. #x = onionoo_fetch(what, **kwargs)
  350. # don't use sort_keys, as the order of or_addresses is significant
  351. #print json.dumps(x, indent=4, separators=(',', ': '))
  352. #sys.exit(0)
  353. return onionoo_fetch(what, **kwargs)
  354. ## Fallback Candidate Class
  355. class Candidate(object):
  356. CUTOFF_ADDRESS_AND_PORT_STABLE = (datetime.datetime.utcnow()
  357. - datetime.timedelta(ADDRESS_AND_PORT_STABLE_DAYS))
  358. def __init__(self, details):
  359. for f in ['fingerprint', 'nickname', 'last_changed_address_or_port',
  360. 'consensus_weight', 'or_addresses', 'dir_address']:
  361. if not f in details: raise Exception("Document has no %s field."%(f,))
  362. if not 'contact' in details:
  363. details['contact'] = None
  364. if not 'flags' in details or details['flags'] is None:
  365. details['flags'] = []
  366. details['last_changed_address_or_port'] = parse_ts(
  367. details['last_changed_address_or_port'])
  368. self._data = details
  369. self._stable_sort_or_addresses()
  370. self._fpr = self._data['fingerprint']
  371. self._running = self._guard = self._v2dir = 0.
  372. self._split_dirport()
  373. self._compute_orport()
  374. if self.orport is None:
  375. raise Exception("Failed to get an orport for %s."%(self._fpr,))
  376. self._compute_ipv6addr()
  377. if self.ipv6addr is None:
  378. logging.debug("Failed to get an ipv6 address for %s."%(self._fpr,))
  379. # Reduce the weight of exits to EXIT_WEIGHT_FRACTION * consensus_weight
  380. if self.is_exit():
  381. exit_weight = self._data['consensus_weight'] * EXIT_WEIGHT_FRACTION
  382. self._data['consensus_weight'] = exit_weight
  383. def _stable_sort_or_addresses(self):
  384. # replace self._data['or_addresses'] with a stable ordering,
  385. # sorting the secondary addresses in string order
  386. # leave the received order in self._data['or_addresses_raw']
  387. self._data['or_addresses_raw'] = self._data['or_addresses']
  388. or_address_primary = self._data['or_addresses'][:1]
  389. # subsequent entries in the or_addresses array are in an arbitrary order
  390. # so we stabilise the addresses by sorting them in string order
  391. or_addresses_secondaries_stable = sorted(self._data['or_addresses'][1:])
  392. or_addresses_stable = or_address_primary + or_addresses_secondaries_stable
  393. self._data['or_addresses'] = or_addresses_stable
  394. def get_fingerprint(self):
  395. return self._fpr
  396. # is_valid_ipv[46]_address by gsathya, karsten, 2013
  397. @staticmethod
  398. def is_valid_ipv4_address(address):
  399. if not isinstance(address, (str, unicode)):
  400. return False
  401. # check if there are four period separated values
  402. if address.count(".") != 3:
  403. return False
  404. # checks that each value in the octet are decimal values between 0-255
  405. for entry in address.split("."):
  406. if not entry.isdigit() or int(entry) < 0 or int(entry) > 255:
  407. return False
  408. elif entry[0] == "0" and len(entry) > 1:
  409. return False # leading zeros, for instance in "1.2.3.001"
  410. return True
  411. @staticmethod
  412. def is_valid_ipv6_address(address):
  413. if not isinstance(address, (str, unicode)):
  414. return False
  415. # remove brackets
  416. address = address[1:-1]
  417. # addresses are made up of eight colon separated groups of four hex digits
  418. # with leading zeros being optional
  419. # https://en.wikipedia.org/wiki/IPv6#Address_format
  420. colon_count = address.count(":")
  421. if colon_count > 7:
  422. return False # too many groups
  423. elif colon_count != 7 and not "::" in address:
  424. return False # not enough groups and none are collapsed
  425. elif address.count("::") > 1 or ":::" in address:
  426. return False # multiple groupings of zeros can't be collapsed
  427. found_ipv4_on_previous_entry = False
  428. for entry in address.split(":"):
  429. # If an IPv6 address has an embedded IPv4 address,
  430. # it must be the last entry
  431. if found_ipv4_on_previous_entry:
  432. return False
  433. if not re.match("^[0-9a-fA-f]{0,4}$", entry):
  434. if not Candidate.is_valid_ipv4_address(entry):
  435. return False
  436. else:
  437. found_ipv4_on_previous_entry = True
  438. return True
  439. def _split_dirport(self):
  440. # Split the dir_address into dirip and dirport
  441. (self.dirip, _dirport) = self._data['dir_address'].split(':', 2)
  442. self.dirport = int(_dirport)
  443. def _compute_orport(self):
  444. # Choose the first ORPort that's on the same IPv4 address as the DirPort.
  445. # In rare circumstances, this might not be the primary ORPort address.
  446. # However, _stable_sort_or_addresses() ensures we choose the same one
  447. # every time, even if onionoo changes the order of the secondaries.
  448. self._split_dirport()
  449. self.orport = None
  450. for i in self._data['or_addresses']:
  451. if i != self._data['or_addresses'][0]:
  452. logging.debug('Secondary IPv4 Address Used for %s: %s'%(self._fpr, i))
  453. (ipaddr, port) = i.rsplit(':', 1)
  454. if (ipaddr == self.dirip) and Candidate.is_valid_ipv4_address(ipaddr):
  455. self.orport = int(port)
  456. return
  457. def _compute_ipv6addr(self):
  458. # Choose the first IPv6 address that uses the same port as the ORPort
  459. # Or, choose the first IPv6 address in the list
  460. # _stable_sort_or_addresses() ensures we choose the same IPv6 address
  461. # every time, even if onionoo changes the order of the secondaries.
  462. self.ipv6addr = None
  463. self.ipv6orport = None
  464. # Choose the first IPv6 address that uses the same port as the ORPort
  465. for i in self._data['or_addresses']:
  466. (ipaddr, port) = i.rsplit(':', 1)
  467. if (port == self.orport) and Candidate.is_valid_ipv6_address(ipaddr):
  468. self.ipv6addr = ipaddr
  469. self.ipv6orport = port
  470. return
  471. # Choose the first IPv6 address in the list
  472. for i in self._data['or_addresses']:
  473. (ipaddr, port) = i.rsplit(':', 1)
  474. if Candidate.is_valid_ipv6_address(ipaddr):
  475. self.ipv6addr = ipaddr
  476. self.ipv6orport = port
  477. return
  478. @staticmethod
  479. def _extract_generic_history(history, which='unknown'):
  480. # given a tree like this:
  481. # {
  482. # "1_month": {
  483. # "count": 187,
  484. # "factor": 0.001001001001001001,
  485. # "first": "2015-02-27 06:00:00",
  486. # "interval": 14400,
  487. # "last": "2015-03-30 06:00:00",
  488. # "values": [
  489. # 999,
  490. # 999
  491. # ]
  492. # },
  493. # "1_week": {
  494. # "count": 169,
  495. # "factor": 0.001001001001001001,
  496. # "first": "2015-03-23 07:30:00",
  497. # "interval": 3600,
  498. # "last": "2015-03-30 07:30:00",
  499. # "values": [ ...]
  500. # },
  501. # "1_year": {
  502. # "count": 177,
  503. # "factor": 0.001001001001001001,
  504. # "first": "2014-04-11 00:00:00",
  505. # "interval": 172800,
  506. # "last": "2015-03-29 00:00:00",
  507. # "values": [ ...]
  508. # },
  509. # "3_months": {
  510. # "count": 185,
  511. # "factor": 0.001001001001001001,
  512. # "first": "2014-12-28 06:00:00",
  513. # "interval": 43200,
  514. # "last": "2015-03-30 06:00:00",
  515. # "values": [ ...]
  516. # }
  517. # },
  518. # extract exactly one piece of data per time interval,
  519. # using smaller intervals where available.
  520. #
  521. # returns list of (age, length, value) dictionaries.
  522. generic_history = []
  523. periods = history.keys()
  524. periods.sort(key = lambda x: history[x]['interval'])
  525. now = datetime.datetime.utcnow()
  526. newest = now
  527. for p in periods:
  528. h = history[p]
  529. interval = datetime.timedelta(seconds = h['interval'])
  530. this_ts = parse_ts(h['last'])
  531. if (len(h['values']) != h['count']):
  532. logging.warn('Inconsistent value count in %s document for %s'
  533. %(p, which))
  534. for v in reversed(h['values']):
  535. if (this_ts <= newest):
  536. agt1 = now - this_ts
  537. agt2 = interval
  538. agetmp1 = (agt1.microseconds + (agt1.seconds + agt1.days * 24 * 3600)
  539. * 10**6) / 10**6
  540. agetmp2 = (agt2.microseconds + (agt2.seconds + agt2.days * 24 * 3600)
  541. * 10**6) / 10**6
  542. generic_history.append(
  543. { 'age': agetmp1,
  544. 'length': agetmp2,
  545. 'value': v
  546. })
  547. newest = this_ts
  548. this_ts -= interval
  549. if (this_ts + interval != parse_ts(h['first'])):
  550. logging.warn('Inconsistent time information in %s document for %s'
  551. %(p, which))
  552. #print json.dumps(generic_history, sort_keys=True,
  553. # indent=4, separators=(',', ': '))
  554. return generic_history
  555. @staticmethod
  556. def _avg_generic_history(generic_history):
  557. a = []
  558. for i in generic_history:
  559. if i['age'] > (ADDRESS_AND_PORT_STABLE_DAYS * 24 * 3600):
  560. continue
  561. if (i['length'] is not None
  562. and i['age'] is not None
  563. and i['value'] is not None):
  564. w = i['length'] * math.pow(AGE_ALPHA, i['age']/(3600*24))
  565. a.append( (i['value'] * w, w) )
  566. sv = math.fsum(map(lambda x: x[0], a))
  567. sw = math.fsum(map(lambda x: x[1], a))
  568. if sw == 0.0:
  569. svw = 0.0
  570. else:
  571. svw = sv/sw
  572. return svw
  573. def _add_generic_history(self, history):
  574. periods = r['read_history'].keys()
  575. periods.sort(key = lambda x: r['read_history'][x]['interval'] )
  576. print periods
  577. def add_running_history(self, history):
  578. pass
  579. def add_uptime(self, uptime):
  580. logging.debug('Adding uptime %s.'%(self._fpr,))
  581. # flags we care about: Running, V2Dir, Guard
  582. if not 'flags' in uptime:
  583. logging.debug('No flags in document for %s.'%(self._fpr,))
  584. return
  585. for f in ['Running', 'Guard', 'V2Dir']:
  586. if not f in uptime['flags']:
  587. logging.debug('No %s in flags for %s.'%(f, self._fpr,))
  588. return
  589. running = self._extract_generic_history(uptime['flags']['Running'],
  590. '%s-Running'%(self._fpr))
  591. guard = self._extract_generic_history(uptime['flags']['Guard'],
  592. '%s-Guard'%(self._fpr))
  593. v2dir = self._extract_generic_history(uptime['flags']['V2Dir'],
  594. '%s-V2Dir'%(self._fpr))
  595. if 'BadExit' in uptime['flags']:
  596. badexit = self._extract_generic_history(uptime['flags']['BadExit'],
  597. '%s-BadExit'%(self._fpr))
  598. self._running = self._avg_generic_history(running) / ONIONOO_SCALE_ONE
  599. self._guard = self._avg_generic_history(guard) / ONIONOO_SCALE_ONE
  600. self._v2dir = self._avg_generic_history(v2dir) / ONIONOO_SCALE_ONE
  601. self._badexit = None
  602. if 'BadExit' in uptime['flags']:
  603. self._badexit = self._avg_generic_history(badexit) / ONIONOO_SCALE_ONE
  604. def is_candidate(self):
  605. must_be_running_now = (PERFORM_IPV4_DIRPORT_CHECKS
  606. or PERFORM_IPV6_DIRPORT_CHECKS)
  607. if (must_be_running_now and not self.is_running()):
  608. logging.info('%s not a candidate: not running now, unable to check ' +
  609. 'DirPort consensus download', self._fpr)
  610. return False
  611. if (self._data['last_changed_address_or_port'] >
  612. self.CUTOFF_ADDRESS_AND_PORT_STABLE):
  613. logging.info('%s not a candidate: changed address/port recently (%s)',
  614. self._fpr, self._data['last_changed_address_or_port'])
  615. return False
  616. if self._running < CUTOFF_RUNNING:
  617. logging.info('%s not a candidate: running avg too low (%lf)',
  618. self._fpr, self._running)
  619. return False
  620. if self._v2dir < CUTOFF_V2DIR:
  621. logging.info('%s not a candidate: v2dir avg too low (%lf)',
  622. self._fpr, self._v2dir)
  623. return False
  624. if self._badexit is not None and self._badexit > PERMITTED_BADEXIT:
  625. logging.info('%s not a candidate: badexit avg too high (%lf)',
  626. self._fpr, self._badexit)
  627. return False
  628. # if the relay doesn't report a version, also exclude the relay
  629. if (not self._data.has_key('recommended_version')
  630. or not self._data['recommended_version']):
  631. logging.info('%s not a candidate: version not recommended', self._fpr)
  632. return False
  633. if self._guard < CUTOFF_GUARD:
  634. logging.info('%s not a candidate: guard avg too low (%lf)',
  635. self._fpr, self._guard)
  636. return False
  637. if (MIN_CONSENSUS_WEIGHT is not None
  638. and self._data['consensus_weight'] < MIN_CONSENSUS_WEIGHT):
  639. logging.info('%s not a candidate: consensus weight %.0f too low, must ' +
  640. 'be at least %.0f', self._fpr,
  641. self._data['consensus_weight'], MIN_CONSENSUS_WEIGHT)
  642. return False
  643. return True
  644. def is_in_whitelist(self, relaylist):
  645. """ A fallback matches if each key in the whitelist line matches:
  646. ipv4
  647. dirport
  648. orport
  649. id
  650. ipv6 address and port (if present)
  651. If the fallback has an ipv6 key, the whitelist line must also have
  652. it, and vice versa, otherwise they don't match. """
  653. for entry in relaylist:
  654. if entry['id'] != self._fpr:
  655. # can't log here, every relay's fingerprint is compared to the entry
  656. continue
  657. if entry['ipv4'] != self.dirip:
  658. logging.info('%s is not in the whitelist: fingerprint matches, but ' +
  659. 'IPv4 (%s) does not match entry IPv4 (%s)',
  660. self._fpr, self.dirip, entry['ipv4'])
  661. continue
  662. if int(entry['dirport']) != self.dirport:
  663. logging.info('%s is not in the whitelist: fingerprint matches, but ' +
  664. 'DirPort (%d) does not match entry DirPort (%d)',
  665. self._fpr, self.dirport, int(entry['dirport']))
  666. continue
  667. if int(entry['orport']) != self.orport:
  668. logging.info('%s is not in the whitelist: fingerprint matches, but ' +
  669. 'ORPort (%d) does not match entry ORPort (%d)',
  670. self._fpr, self.orport, int(entry['orport']))
  671. continue
  672. has_ipv6 = self.ipv6addr is not None and self.ipv6orport is not None
  673. if (entry.has_key('ipv6') and has_ipv6):
  674. ipv6 = self.ipv6addr + ':' + self.ipv6orport
  675. # if both entry and fallback have an ipv6 address, compare them
  676. if entry['ipv6'] != ipv6:
  677. logging.info('%s is not in the whitelist: fingerprint matches, ' +
  678. 'but IPv6 (%s) does not match entry IPv6 (%s)',
  679. self._fpr, ipv6, entry['ipv6'])
  680. continue
  681. # if the fallback has an IPv6 address but the whitelist entry
  682. # doesn't, or vice versa, the whitelist entry doesn't match
  683. elif entry.has_key('ipv6') and not has_ipv6:
  684. logging.info('%s is not in the whitelist: fingerprint matches, but ' +
  685. 'it has no IPv6, and entry has IPv6 (%s)', self._fpr,
  686. entry['ipv6'])
  687. logging.warning('%s excluded: has it lost its former IPv6 address %s?',
  688. self._fpr, entry['ipv6'])
  689. continue
  690. elif not entry.has_key('ipv6') and has_ipv6:
  691. logging.info('%s is not in the whitelist: fingerprint matches, but ' +
  692. 'it has IPv6 (%s), and entry has no IPv6', self._fpr,
  693. ipv6)
  694. logging.warning('%s excluded: has it gained an IPv6 address %s?',
  695. self._fpr, ipv6)
  696. continue
  697. return True
  698. return False
  699. def is_in_blacklist(self, relaylist):
  700. """ A fallback matches a blacklist line if a sufficiently specific group
  701. of attributes matches:
  702. ipv4 & dirport
  703. ipv4 & orport
  704. id
  705. ipv6 & dirport
  706. ipv6 & ipv6 orport
  707. If the fallback and the blacklist line both have an ipv6 key,
  708. their values will be compared, otherwise, they will be ignored.
  709. If there is no dirport and no orport, the entry matches all relays on
  710. that ip. """
  711. for entry in relaylist:
  712. for key in entry:
  713. value = entry[key]
  714. if key == 'id' and value == self._fpr:
  715. logging.info('%s is in the blacklist: fingerprint matches',
  716. self._fpr)
  717. return True
  718. if key == 'ipv4' and value == self.dirip:
  719. # if the dirport is present, check it too
  720. if entry.has_key('dirport'):
  721. if int(entry['dirport']) == self.dirport:
  722. logging.info('%s is in the blacklist: IPv4 (%s) and ' +
  723. 'DirPort (%d) match', self._fpr, self.dirip,
  724. self.dirport)
  725. return True
  726. # if the orport is present, check it too
  727. elif entry.has_key('orport'):
  728. if int(entry['orport']) == self.orport:
  729. logging.info('%s is in the blacklist: IPv4 (%s) and ' +
  730. 'ORPort (%d) match', self._fpr, self.dirip,
  731. self.orport)
  732. return True
  733. else:
  734. logging.info('%s is in the blacklist: IPv4 (%s) matches, and ' +
  735. 'entry has no DirPort or ORPort', self._fpr,
  736. self.dirip)
  737. return True
  738. has_ipv6 = self.ipv6addr is not None and self.ipv6orport is not None
  739. ipv6 = (self.ipv6addr + ':' + self.ipv6orport) if has_ipv6 else None
  740. if (key == 'ipv6' and has_ipv6):
  741. # if both entry and fallback have an ipv6 address, compare them,
  742. # otherwise, disregard ipv6 addresses
  743. if value == ipv6:
  744. # if the dirport is present, check it too
  745. if entry.has_key('dirport'):
  746. if int(entry['dirport']) == self.dirport:
  747. logging.info('%s is in the blacklist: IPv6 (%s) and ' +
  748. 'DirPort (%d) match', self._fpr, ipv6,
  749. self.dirport)
  750. return True
  751. # we've already checked the ORPort, it's part of entry['ipv6']
  752. else:
  753. logging.info('%s is in the blacklist: IPv6 (%s) matches, and' +
  754. 'entry has no DirPort', self._fpr, ipv6)
  755. return True
  756. elif (key == 'ipv6' or has_ipv6):
  757. # only log if the fingerprint matches but the IPv6 doesn't
  758. if entry.has_key('id') and entry['id'] == self._fpr:
  759. logging.info('%s skipping IPv6 blacklist comparison: relay ' +
  760. 'has%s IPv6%s, but entry has%s IPv6%s', self._fpr,
  761. '' if has_ipv6 else ' no',
  762. (' (' + ipv6 + ')') if has_ipv6 else '',
  763. '' if key == 'ipv6' else ' no',
  764. (' (' + value + ')') if key == 'ipv6' else '')
  765. logging.warning('Has %s %s IPv6 address %s?', self._fpr,
  766. 'gained an' if has_ipv6 else 'lost its former',
  767. ipv6 if has_ipv6 else value)
  768. return False
  769. def is_exit(self):
  770. return 'Exit' in self._data['flags']
  771. def is_guard(self):
  772. return 'Guard' in self._data['flags']
  773. def is_running(self):
  774. return 'Running' in self._data['flags']
  775. @staticmethod
  776. def fallback_consensus_dl_speed(dirip, dirport, nickname, max_time):
  777. download_failed = False
  778. downloader = DescriptorDownloader()
  779. start = datetime.datetime.utcnow()
  780. # some directory mirrors respond to requests in ways that hang python
  781. # sockets, which is why we long this line here
  782. logging.info('Initiating consensus download from %s (%s:%d).', nickname,
  783. dirip, dirport)
  784. # there appears to be about 1 second of overhead when comparing stem's
  785. # internal trace time and the elapsed time calculated here
  786. TIMEOUT_SLOP = 1.0
  787. try:
  788. downloader.get_consensus(endpoints = [(dirip, dirport)],
  789. timeout = (max_time + TIMEOUT_SLOP),
  790. validate = True,
  791. retries = 0,
  792. fall_back_to_authority = False).run()
  793. except Exception, stem_error:
  794. logging.debug('Unable to retrieve a consensus from %s: %s', nickname,
  795. stem_error)
  796. status = 'error: "%s"' % (stem_error)
  797. level = logging.WARNING
  798. download_failed = True
  799. elapsed = (datetime.datetime.utcnow() - start).total_seconds()
  800. if elapsed > max_time:
  801. status = 'too slow'
  802. level = logging.WARNING
  803. download_failed = True
  804. else:
  805. status = 'ok'
  806. level = logging.DEBUG
  807. logging.log(level, 'Consensus download: %0.1fs %s from %s (%s:%d), ' +
  808. 'max download time %0.1fs.', elapsed, status, nickname,
  809. dirip, dirport, max_time)
  810. return download_failed
  811. def fallback_consensus_dl_check(self):
  812. # include the relay if we're not doing a check, or we can't check (IPv6)
  813. ipv4_failed = False
  814. ipv6_failed = False
  815. if PERFORM_IPV4_DIRPORT_CHECKS:
  816. ipv4_failed = Candidate.fallback_consensus_dl_speed(self.dirip,
  817. self.dirport,
  818. self._data['nickname'],
  819. CONSENSUS_DOWNLOAD_SPEED_MAX)
  820. if self.ipv6addr is not None and PERFORM_IPV6_DIRPORT_CHECKS:
  821. # Clients assume the IPv6 DirPort is the same as the IPv4 DirPort
  822. ipv6_failed = Candidate.fallback_consensus_dl_speed(self.ipv6addr,
  823. self.dirport,
  824. self._data['nickname'],
  825. CONSENSUS_DOWNLOAD_SPEED_MAX)
  826. # Now retry the relay if it took too long the first time
  827. if (PERFORM_IPV4_DIRPORT_CHECKS and ipv4_failed
  828. and CONSENSUS_DOWNLOAD_RETRY):
  829. ipv4_failed = Candidate.fallback_consensus_dl_speed(self.dirip,
  830. self.dirport,
  831. self._data['nickname'],
  832. CONSENSUS_DOWNLOAD_SPEED_MAX)
  833. if (self.ipv6addr is not None and PERFORM_IPV6_DIRPORT_CHECKS
  834. and ipv6_failed and CONSENSUS_DOWNLOAD_RETRY):
  835. ipv6_failed = Candidate.fallback_consensus_dl_speed(self.ipv6addr,
  836. self.dirport,
  837. self._data['nickname'],
  838. CONSENSUS_DOWNLOAD_SPEED_MAX)
  839. return ((not ipv4_failed) and (not ipv6_failed))
  840. def fallbackdir_line(self, dl_speed_ok):
  841. # /*
  842. # nickname
  843. # flags
  844. # [contact]
  845. # */
  846. # "address:dirport orport=port id=fingerprint"
  847. # "[ipv6=addr:orport]"
  848. # "weight=FALLBACK_OUTPUT_WEIGHT",
  849. #
  850. # Multiline C comment
  851. s = '/*'
  852. s += '\n'
  853. s += cleanse_c_multiline_comment(self._data['nickname'])
  854. s += '\n'
  855. s += 'Flags: '
  856. s += cleanse_c_multiline_comment(' '.join(sorted(self._data['flags'])))
  857. s += '\n'
  858. if self._data['contact'] is not None:
  859. s += cleanse_c_multiline_comment(self._data['contact'])
  860. s += '\n'
  861. s += '*/'
  862. s += '\n'
  863. # Comment out the fallback directory entry if it's too slow
  864. # See the debug output for which address and port is failing
  865. if not dl_speed_ok:
  866. s += '/* Consensus download failed or was too slow:\n'
  867. # Multi-Line C string with trailing comma (part of a string list)
  868. # This makes it easier to diff the file, and remove IPv6 lines using grep
  869. # Integers don't need escaping
  870. s += '"%s orport=%d id=%s"'%(
  871. cleanse_c_string(self._data['dir_address']),
  872. self.orport,
  873. cleanse_c_string(self._fpr))
  874. s += '\n'
  875. if self.ipv6addr is not None:
  876. s += '" ipv6=%s:%s"'%(
  877. cleanse_c_string(self.ipv6addr), cleanse_c_string(self.ipv6orport))
  878. s += '\n'
  879. s += '" weight=%d",'%(FALLBACK_OUTPUT_WEIGHT)
  880. if not dl_speed_ok:
  881. s += '\n'
  882. s += '*/'
  883. return s
  884. ## Fallback Candidate List Class
  885. class CandidateList(dict):
  886. def __init__(self):
  887. pass
  888. def _add_relay(self, details):
  889. if not 'dir_address' in details: return
  890. c = Candidate(details)
  891. self[ c.get_fingerprint() ] = c
  892. def _add_uptime(self, uptime):
  893. try:
  894. fpr = uptime['fingerprint']
  895. except KeyError:
  896. raise Exception("Document has no fingerprint field.")
  897. try:
  898. c = self[fpr]
  899. except KeyError:
  900. logging.debug('Got unknown relay %s in uptime document.'%(fpr,))
  901. return
  902. c.add_uptime(uptime)
  903. def _add_details(self):
  904. logging.debug('Loading details document.')
  905. d = fetch('details',
  906. fields=('fingerprint,nickname,contact,last_changed_address_or_port,' +
  907. 'consensus_weight,or_addresses,dir_address,' +
  908. 'recommended_version,flags'))
  909. logging.debug('Loading details document done.')
  910. if not 'relays' in d: raise Exception("No relays found in document.")
  911. for r in d['relays']: self._add_relay(r)
  912. def _add_uptimes(self):
  913. logging.debug('Loading uptime document.')
  914. d = fetch('uptime')
  915. logging.debug('Loading uptime document done.')
  916. if not 'relays' in d: raise Exception("No relays found in document.")
  917. for r in d['relays']: self._add_uptime(r)
  918. def add_relays(self):
  919. self._add_details()
  920. self._add_uptimes()
  921. def count_guards(self):
  922. guard_count = 0
  923. for fpr in self.keys():
  924. if self[fpr].is_guard():
  925. guard_count += 1
  926. return guard_count
  927. # Find fallbacks that fit the uptime, stability, and flags criteria
  928. def compute_fallbacks(self):
  929. self.fallbacks = map(lambda x: self[x],
  930. sorted(
  931. filter(lambda x: self[x].is_candidate(),
  932. self.keys()),
  933. key=lambda x: self[x]._data['consensus_weight'],
  934. reverse=True)
  935. )
  936. @staticmethod
  937. def load_relaylist(file_name):
  938. """ Read each line in the file, and parse it like a FallbackDir line:
  939. an IPv4 address and optional port:
  940. <IPv4 address>:<port>
  941. which are parsed into dictionary entries:
  942. ipv4=<IPv4 address>
  943. dirport=<port>
  944. followed by a series of key=value entries:
  945. orport=<port>
  946. id=<fingerprint>
  947. ipv6=<IPv6 address>:<IPv6 orport>
  948. each line's key/value pairs are placed in a dictonary,
  949. (of string -> string key/value pairs),
  950. and these dictionaries are placed in an array.
  951. comments start with # and are ignored """
  952. relaylist = []
  953. file_data = read_from_file(file_name, MAX_LIST_FILE_SIZE)
  954. if file_data is None:
  955. return relaylist
  956. for line in file_data.split('\n'):
  957. relay_entry = {}
  958. # ignore comments
  959. line_comment_split = line.split('#')
  960. line = line_comment_split[0]
  961. # cleanup whitespace
  962. line = cleanse_whitespace(line)
  963. line = line.strip()
  964. if len(line) == 0:
  965. continue
  966. for item in line.split(' '):
  967. item = item.strip()
  968. if len(item) == 0:
  969. continue
  970. key_value_split = item.split('=')
  971. kvl = len(key_value_split)
  972. if kvl < 1 or kvl > 2:
  973. print '#error Bad %s item: %s, format is key=value.'%(
  974. file_name, item)
  975. if kvl == 1:
  976. # assume that entries without a key are the ipv4 address,
  977. # perhaps with a dirport
  978. ipv4_maybe_dirport = key_value_split[0]
  979. ipv4_maybe_dirport_split = ipv4_maybe_dirport.split(':')
  980. dirl = len(ipv4_maybe_dirport_split)
  981. if dirl < 1 or dirl > 2:
  982. print '#error Bad %s IPv4 item: %s, format is ipv4:port.'%(
  983. file_name, item)
  984. if dirl >= 1:
  985. relay_entry['ipv4'] = ipv4_maybe_dirport_split[0]
  986. if dirl == 2:
  987. relay_entry['dirport'] = ipv4_maybe_dirport_split[1]
  988. elif kvl == 2:
  989. relay_entry[key_value_split[0]] = key_value_split[1]
  990. relaylist.append(relay_entry)
  991. return relaylist
  992. # apply the fallback whitelist and blacklist
  993. def apply_filter_lists(self):
  994. excluded_count = 0
  995. logging.debug('Applying whitelist and blacklist.')
  996. # parse the whitelist and blacklist
  997. whitelist = self.load_relaylist(WHITELIST_FILE_NAME)
  998. blacklist = self.load_relaylist(BLACKLIST_FILE_NAME)
  999. filtered_fallbacks = []
  1000. for f in self.fallbacks:
  1001. in_whitelist = f.is_in_whitelist(whitelist)
  1002. in_blacklist = f.is_in_blacklist(blacklist)
  1003. if in_whitelist and in_blacklist:
  1004. if BLACKLIST_EXCLUDES_WHITELIST_ENTRIES:
  1005. # exclude
  1006. excluded_count += 1
  1007. logging.warning('Excluding %s: in both blacklist and whitelist.',
  1008. f._fpr)
  1009. else:
  1010. # include
  1011. filtered_fallbacks.append(f)
  1012. elif in_whitelist:
  1013. # include
  1014. filtered_fallbacks.append(f)
  1015. elif in_blacklist:
  1016. # exclude
  1017. excluded_count += 1
  1018. logging.debug('Excluding %s: in blacklist.', f._fpr)
  1019. else:
  1020. if INCLUDE_UNLISTED_ENTRIES:
  1021. # include
  1022. filtered_fallbacks.append(f)
  1023. else:
  1024. # exclude
  1025. excluded_count += 1
  1026. logging.info('Excluding %s: in neither blacklist nor whitelist.',
  1027. f._fpr)
  1028. self.fallbacks = filtered_fallbacks
  1029. return excluded_count
  1030. @staticmethod
  1031. def summarise_filters(initial_count, excluded_count):
  1032. return '/* Whitelist & blacklist excluded %d of %d candidates. */'%(
  1033. excluded_count, initial_count)
  1034. # Remove any fallbacks in excess of MAX_FALLBACK_COUNT,
  1035. # starting with the lowest-weighted fallbacks
  1036. # this changes total weight
  1037. def exclude_excess_fallbacks(self):
  1038. if MAX_FALLBACK_COUNT is not None:
  1039. self.fallbacks = self.fallbacks[:MAX_FALLBACK_COUNT]
  1040. def fallback_min_weight(self):
  1041. if len(self.fallbacks) > 0:
  1042. return self.fallbacks[-1]
  1043. else:
  1044. return None
  1045. def fallback_max_weight(self):
  1046. if len(self.fallbacks) > 0:
  1047. return self.fallbacks[0]
  1048. else:
  1049. return None
  1050. def summarise_fallbacks(self, eligible_count, guard_count, target_count,
  1051. max_count):
  1052. # Report:
  1053. # the number of fallback directories (with min & max limits);
  1054. # #error if below minimum count
  1055. # min & max fallback weights
  1056. # Multiline C comment with #error if things go bad
  1057. s = '/*'
  1058. s += '\n'
  1059. s += 'Fallback Directory Summary'
  1060. s += '\n'
  1061. # Integers don't need escaping in C comments
  1062. fallback_count = len(self.fallbacks)
  1063. if FALLBACK_PROPORTION_OF_GUARDS is None:
  1064. fallback_proportion = ' (none)'
  1065. else:
  1066. fallback_proportion = '%d (%d * %f)'%(target_count, guard_count,
  1067. FALLBACK_PROPORTION_OF_GUARDS)
  1068. s += 'Final Count: %d (Eligible %d, Target %d%s'%(
  1069. min(max_count, fallback_count),
  1070. eligible_count,
  1071. fallback_count,
  1072. fallback_proportion)
  1073. if MAX_FALLBACK_COUNT is not None:
  1074. s += ', Clamped to %d'%(MAX_FALLBACK_COUNT)
  1075. s += ')\n'
  1076. if fallback_count < MIN_FALLBACK_COUNT:
  1077. s += '*/'
  1078. s += '\n'
  1079. # We must have a minimum number of fallbacks so they are always
  1080. # reachable, and are in diverse locations
  1081. s += '#error Fallback Count %d is too low. '%(fallback_count)
  1082. s += 'Must be at least %d for diversity. '%(MIN_FALLBACK_COUNT)
  1083. s += 'Try adding entries to the whitelist, '
  1084. s += 'or setting INCLUDE_UNLISTED_ENTRIES = True.'
  1085. s += '\n'
  1086. s += '/*'
  1087. s += '\n'
  1088. min_fb = self.fallback_min_weight()
  1089. min_weight = min_fb._data['consensus_weight']
  1090. max_fb = self.fallback_max_weight()
  1091. max_weight = max_fb._data['consensus_weight']
  1092. s += 'Max Weight: %d'%(max_weight)
  1093. s += '\n'
  1094. s += 'Min Weight: %d'%(min_weight)
  1095. s += '\n'
  1096. if eligible_count != fallback_count:
  1097. s += 'Excluded: %d (Eligible Count Exceeded Target Count)'%(
  1098. eligible_count - fallback_count)
  1099. s += '\n'
  1100. s += '*/'
  1101. if PERFORM_IPV4_DIRPORT_CHECKS or PERFORM_IPV6_DIRPORT_CHECKS:
  1102. s += '/* Checked %s%s%s DirPorts served a consensus within %.1fs. */'%(
  1103. 'IPv4' if PERFORM_IPV4_DIRPORT_CHECKS else '',
  1104. ' and ' if (PERFORM_IPV4_DIRPORT_CHECKS
  1105. and PERFORM_IPV6_DIRPORT_CHECKS) else '',
  1106. 'IPv6' if PERFORM_IPV6_DIRPORT_CHECKS else '',
  1107. CONSENSUS_DOWNLOAD_SPEED_MAX)
  1108. else:
  1109. s += '/* Did not check IPv4 or IPv6 DirPort consensus downloads. */'
  1110. return s
  1111. ## Main Function
  1112. def list_fallbacks():
  1113. """ Fetches required onionoo documents and evaluates the
  1114. fallback directory criteria for each of the relays """
  1115. # find relays that could be fallbacks
  1116. candidates = CandidateList()
  1117. candidates.add_relays()
  1118. # work out how many fallbacks we want
  1119. guard_count = candidates.count_guards()
  1120. if FALLBACK_PROPORTION_OF_GUARDS is None:
  1121. target_count = guard_count
  1122. else:
  1123. target_count = int(guard_count * FALLBACK_PROPORTION_OF_GUARDS)
  1124. # the maximum number of fallbacks is the least of:
  1125. # - the target fallback count (FALLBACK_PROPORTION_OF_GUARDS * guard count)
  1126. # - the maximum fallback count (MAX_FALLBACK_COUNT)
  1127. if MAX_FALLBACK_COUNT is None:
  1128. max_count = guard_count
  1129. else:
  1130. max_count = min(target_count, MAX_FALLBACK_COUNT)
  1131. candidates.compute_fallbacks()
  1132. # filter with the whitelist and blacklist
  1133. initial_count = len(candidates.fallbacks)
  1134. excluded_count = candidates.apply_filter_lists()
  1135. print candidates.summarise_filters(initial_count, excluded_count)
  1136. eligible_count = len(candidates.fallbacks)
  1137. # print the raw fallback list
  1138. #for x in candidates.fallbacks:
  1139. # print x.fallbackdir_line(True)
  1140. # exclude low-weight fallbacks if we have more than we want
  1141. candidates.exclude_excess_fallbacks()
  1142. if len(candidates.fallbacks) > 0:
  1143. print candidates.summarise_fallbacks(eligible_count, guard_count,
  1144. target_count, max_count)
  1145. else:
  1146. print '/* No Fallbacks met criteria */'
  1147. for s in fetch_source_list():
  1148. print describe_fetch_source(s)
  1149. for x in candidates.fallbacks[:max_count]:
  1150. dl_speed_ok = x.fallback_consensus_dl_check()
  1151. print x.fallbackdir_line(dl_speed_ok)
  1152. #print json.dumps(candidates[x]._data, sort_keys=True, indent=4,
  1153. # separators=(',', ': '), default=json_util.default)
  1154. if __name__ == "__main__":
  1155. list_fallbacks()