updateFallbackDirs.py 54 KB

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