updateFallbackDirs.py 49 KB

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