updateFallbackDirs.py 49 KB

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