updateFallbackDirs.py 55 KB

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