updateFallbackDirs.py 44 KB

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