updateFallbackDirs.py 49 KB

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