updateFallbackDirs.py 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013
  1. #!/usr/bin/python
  2. # Usage: scripts/maint/updateFallbackDirs.py > src/or/fallback_dirs.inc
  3. #
  4. # This script should be run from a stable, reliable network connection,
  5. # with no other network activity (and not over tor).
  6. # If this is not possible, please disable:
  7. # PERFORM_IPV4_DIRPORT_CHECKS and PERFORM_IPV6_DIRPORT_CHECKS
  8. #
  9. # Needs dateutil (and potentially other python packages)
  10. # Needs stem available in your PYTHONPATH, or just ln -s ../stem/stem .
  11. # Optionally uses ipaddress (python 3 builtin) or py2-ipaddress (package)
  12. # for netblock analysis, in PYTHONPATH, or just
  13. # ln -s ../py2-ipaddress-3.4.1/ipaddress.py .
  14. #
  15. # Then read the logs to make sure the fallbacks aren't dominated by a single
  16. # netblock or port
  17. # Script by weasel, April 2015
  18. # Portions by gsathya & karsten, 2013
  19. # https://trac.torproject.org/projects/tor/attachment/ticket/8374/dir_list.2.py
  20. # Modifications by teor, 2015
  21. import StringIO
  22. import string
  23. import re
  24. import datetime
  25. import gzip
  26. import os.path
  27. import json
  28. import math
  29. import sys
  30. import urllib
  31. import urllib2
  32. import hashlib
  33. import dateutil.parser
  34. # bson_lazy provides bson
  35. #from bson import json_util
  36. import copy
  37. from stem.descriptor.remote import DescriptorDownloader
  38. import logging
  39. # INFO tells you why each relay was included or excluded
  40. # WARN tells you about potential misconfigurations and relay detail changes
  41. logging.basicConfig(level=logging.WARNING)
  42. logging.root.name = ''
  43. # INFO tells you about each consensus download attempt
  44. logging.getLogger('stem').setLevel(logging.WARNING)
  45. HAVE_IPADDRESS = False
  46. try:
  47. # python 3 builtin, or install package py2-ipaddress
  48. # there are several ipaddress implementations for python 2
  49. # with slightly different semantics with str typed text
  50. # fortunately, all our IP addresses are in unicode
  51. import ipaddress
  52. HAVE_IPADDRESS = True
  53. except ImportError:
  54. # if this happens, we avoid doing netblock analysis
  55. logging.warning('Unable to import ipaddress, please install py2-ipaddress.' +
  56. ' A fallback list will be created, but optional netblock' +
  57. ' analysis will not be performed.')
  58. ## Top-Level Configuration
  59. # Output all candidate fallbacks, or only output selected fallbacks?
  60. OUTPUT_CANDIDATES = False
  61. # Perform DirPort checks over IPv4?
  62. # Change this to False if IPv4 doesn't work for you, or if you don't want to
  63. # download a consensus for each fallback
  64. # Don't check ~1000 candidates when OUTPUT_CANDIDATES is True
  65. PERFORM_IPV4_DIRPORT_CHECKS = False if OUTPUT_CANDIDATES else True
  66. # Perform DirPort checks over IPv6?
  67. # If you know IPv6 works for you, set this to True
  68. # This will exclude IPv6 relays without an IPv6 DirPort configured
  69. # So it's best left at False until #18394 is implemented
  70. # Don't check ~1000 candidates when OUTPUT_CANDIDATES is True
  71. PERFORM_IPV6_DIRPORT_CHECKS = False if OUTPUT_CANDIDATES else False
  72. # Output fallback name, flags, bandwidth, and ContactInfo in a C comment?
  73. OUTPUT_COMMENTS = True if OUTPUT_CANDIDATES else False
  74. # Output matching ContactInfo in fallbacks list or the blacklist?
  75. # Useful if you're trying to contact operators
  76. CONTACT_COUNT = True if OUTPUT_CANDIDATES else False
  77. CONTACT_BLACKLIST_COUNT = True if OUTPUT_CANDIDATES else False
  78. # How the list should be sorted:
  79. # fingerprint: is useful for stable diffs of fallback lists
  80. # measured_bandwidth: is useful when pruning the list based on bandwidth
  81. # contact: is useful for contacting operators once the list has been pruned
  82. OUTPUT_SORT_FIELD = 'contact' if OUTPUT_CANDIDATES else 'fingerprint'
  83. ## OnionOO Settings
  84. ONIONOO = 'https://onionoo.torproject.org/'
  85. #ONIONOO = 'https://onionoo.thecthulhu.com/'
  86. # Don't bother going out to the Internet, just use the files available locally,
  87. # even if they're very old
  88. LOCAL_FILES_ONLY = False
  89. ## Whitelist / Blacklist Filter Settings
  90. # The whitelist contains entries that are included if all attributes match
  91. # (IPv4, dirport, orport, id, and optionally IPv6 and IPv6 orport)
  92. # The blacklist contains (partial) entries that are excluded if any
  93. # sufficiently specific group of attributes matches:
  94. # IPv4 & DirPort
  95. # IPv4 & ORPort
  96. # ID
  97. # IPv6 & DirPort
  98. # IPv6 & IPv6 ORPort
  99. # If neither port is included in the blacklist, the entire IP address is
  100. # blacklisted.
  101. # What happens to entries in neither list?
  102. # When True, they are included, when False, they are excluded
  103. INCLUDE_UNLISTED_ENTRIES = True if OUTPUT_CANDIDATES else False
  104. # If an entry is in both lists, what happens?
  105. # When True, it is excluded, when False, it is included
  106. BLACKLIST_EXCLUDES_WHITELIST_ENTRIES = True
  107. WHITELIST_FILE_NAME = 'scripts/maint/fallback.whitelist'
  108. BLACKLIST_FILE_NAME = 'scripts/maint/fallback.blacklist'
  109. # The number of bytes we'll read from a filter file before giving up
  110. MAX_LIST_FILE_SIZE = 1024 * 1024
  111. ## Eligibility Settings
  112. # Reduced due to a bug in tor where a relay submits a 0 DirPort when restarted
  113. # This causes OnionOO to (correctly) reset its stability timer
  114. # This issue will be fixed in 0.2.7.7 and 0.2.8.2
  115. # Until then, the CUTOFFs below ensure a decent level of stability.
  116. ADDRESS_AND_PORT_STABLE_DAYS = 7
  117. # What time-weighted-fraction of these flags must FallbackDirs
  118. # Equal or Exceed?
  119. CUTOFF_RUNNING = .95
  120. CUTOFF_V2DIR = .95
  121. CUTOFF_GUARD = .95
  122. # What time-weighted-fraction of these flags must FallbackDirs
  123. # Equal or Fall Under?
  124. # .00 means no bad exits
  125. PERMITTED_BADEXIT = .00
  126. # older entries' weights are adjusted with ALPHA^(age in days)
  127. AGE_ALPHA = 0.99
  128. # this factor is used to scale OnionOO entries to [0,1]
  129. ONIONOO_SCALE_ONE = 999.
  130. ## Fallback Count Limits
  131. # The target for these parameters is 20% of the guards in the network
  132. # This is around 200 as of October 2015
  133. _FB_POG = 0.2
  134. FALLBACK_PROPORTION_OF_GUARDS = None if OUTPUT_CANDIDATES else _FB_POG
  135. # Limit the number of fallbacks (eliminating lowest by advertised bandwidth)
  136. MAX_FALLBACK_COUNT = None if OUTPUT_CANDIDATES else 200
  137. # Emit a C #error if the number of fallbacks is more than 10% below MAX
  138. MIN_FALLBACK_COUNT = 0 if OUTPUT_CANDIDATES else MAX_FALLBACK_COUNT*0.9
  139. ## Fallback Bandwidth Requirements
  140. # Any fallback with the Exit flag has its bandwidth multipled by this fraction
  141. # to make sure we aren't further overloading exits
  142. # (Set to 1.0, because we asked that only lightly loaded exits opt-in,
  143. # and the extra load really isn't that much for large relays.)
  144. EXIT_BANDWIDTH_FRACTION = 1.0
  145. # If a single fallback's bandwidth is too low, it's pointless adding it
  146. # We expect fallbacks to handle an extra 30 kilobytes per second of traffic
  147. # Make sure they can support a hundred times the expected extra load
  148. # (Use 102.4 to make it come out nicely in MByte/s)
  149. # We convert this to a consensus weight before applying the filter,
  150. # because all the bandwidth amounts are specified by the relay
  151. MIN_BANDWIDTH = 102.4 * 30.0 * 1024.0
  152. # Clients will time out after 30 seconds trying to download a consensus
  153. # So allow fallback directories half that to deliver a consensus
  154. # The exact download times might change based on the network connection
  155. # running this script, but only by a few seconds
  156. # There is also about a second of python overhead
  157. CONSENSUS_DOWNLOAD_SPEED_MAX = 15.0
  158. # If the relay fails a consensus check, retry the download
  159. # This avoids delisting a relay due to transient network conditions
  160. CONSENSUS_DOWNLOAD_RETRY = True
  161. ## Fallback Weights for Client Selection
  162. # All fallback weights are equal, and set to the value below
  163. # Authorities are weighted 1.0 by default
  164. # Clients use these weights to select fallbacks and authorities at random
  165. # If there are 100 fallbacks and 9 authorities:
  166. # - each fallback is chosen with probability 10.0/(10.0*100 + 1.0*9) ~= 0.99%
  167. # - each authority is chosen with probability 1.0/(10.0*100 + 1.0*9) ~= 0.09%
  168. # A client choosing a bootstrap directory server will choose a fallback for
  169. # 10.0/(10.0*100 + 1.0*9) * 100 = 99.1% of attempts, and an authority for
  170. # 1.0/(10.0*100 + 1.0*9) * 9 = 0.9% of attempts.
  171. # (This disregards the bootstrap schedules, where clients start by choosing
  172. # from fallbacks & authoritites, then later choose from only authorities.)
  173. FALLBACK_OUTPUT_WEIGHT = 10.0
  174. ## Parsing Functions
  175. def parse_ts(t):
  176. return datetime.datetime.strptime(t, "%Y-%m-%d %H:%M:%S")
  177. def remove_bad_chars(raw_string, bad_char_list):
  178. # Remove each character in the bad_char_list
  179. cleansed_string = raw_string
  180. for c in bad_char_list:
  181. cleansed_string = cleansed_string.replace(c, '')
  182. return cleansed_string
  183. def cleanse_unprintable(raw_string):
  184. # Remove all unprintable characters
  185. cleansed_string = ''
  186. for c in raw_string:
  187. if c in string.printable:
  188. cleansed_string += c
  189. return cleansed_string
  190. def cleanse_whitespace(raw_string):
  191. # Replace all whitespace characters with a space
  192. cleansed_string = raw_string
  193. for c in string.whitespace:
  194. cleansed_string = cleansed_string.replace(c, ' ')
  195. return cleansed_string
  196. def cleanse_c_multiline_comment(raw_string):
  197. cleansed_string = raw_string
  198. # Embedded newlines should be removed by tor/onionoo, but let's be paranoid
  199. cleansed_string = cleanse_whitespace(cleansed_string)
  200. # ContactInfo and Version can be arbitrary binary data
  201. cleansed_string = cleanse_unprintable(cleansed_string)
  202. # Prevent a malicious / unanticipated string from breaking out
  203. # of a C-style multiline comment
  204. # This removes '/*' and '*/' and '//'
  205. bad_char_list = '*/'
  206. # Prevent a malicious string from using C nulls
  207. bad_char_list += '\0'
  208. # Be safer by removing bad characters entirely
  209. cleansed_string = remove_bad_chars(cleansed_string, bad_char_list)
  210. # Some compilers may further process the content of comments
  211. # There isn't much we can do to cover every possible case
  212. # But comment-based directives are typically only advisory
  213. return cleansed_string
  214. def cleanse_c_string(raw_string):
  215. cleansed_string = raw_string
  216. # Embedded newlines should be removed by tor/onionoo, but let's be paranoid
  217. cleansed_string = cleanse_whitespace(cleansed_string)
  218. # ContactInfo and Version can be arbitrary binary data
  219. cleansed_string = cleanse_unprintable(cleansed_string)
  220. # Prevent a malicious address/fingerprint string from breaking out
  221. # of a C-style string
  222. bad_char_list = '"'
  223. # Prevent a malicious string from using escapes
  224. bad_char_list += '\\'
  225. # Prevent a malicious string from using C nulls
  226. bad_char_list += '\0'
  227. # Be safer by removing bad characters entirely
  228. cleansed_string = remove_bad_chars(cleansed_string, bad_char_list)
  229. # Some compilers may further process the content of strings
  230. # There isn't much we can do to cover every possible case
  231. # But this typically only results in changes to the string data
  232. return cleansed_string
  233. ## OnionOO Source Functions
  234. # a dictionary of source metadata for each onionoo query we've made
  235. fetch_source = {}
  236. # register source metadata for 'what'
  237. # assumes we only retrieve one document for each 'what'
  238. def register_fetch_source(what, url, relays_published, version):
  239. fetch_source[what] = {}
  240. fetch_source[what]['url'] = url
  241. fetch_source[what]['relays_published'] = relays_published
  242. fetch_source[what]['version'] = version
  243. # list each registered source's 'what'
  244. def fetch_source_list():
  245. return sorted(fetch_source.keys())
  246. # given 'what', provide a multiline C comment describing the source
  247. def describe_fetch_source(what):
  248. desc = '/*'
  249. desc += '\n'
  250. desc += 'Onionoo Source: '
  251. desc += cleanse_c_multiline_comment(what)
  252. desc += ' Date: '
  253. desc += cleanse_c_multiline_comment(fetch_source[what]['relays_published'])
  254. desc += ' Version: '
  255. desc += cleanse_c_multiline_comment(fetch_source[what]['version'])
  256. desc += '\n'
  257. desc += 'URL: '
  258. desc += cleanse_c_multiline_comment(fetch_source[what]['url'])
  259. desc += '\n'
  260. desc += '*/'
  261. return desc
  262. ## File Processing Functions
  263. def write_to_file(str, file_name, max_len):
  264. try:
  265. with open(file_name, 'w') as f:
  266. f.write(str[0:max_len])
  267. except EnvironmentError, error:
  268. logging.error('Writing file %s failed: %d: %s'%
  269. (file_name,
  270. error.errno,
  271. error.strerror)
  272. )
  273. def read_from_file(file_name, max_len):
  274. try:
  275. if os.path.isfile(file_name):
  276. with open(file_name, 'r') as f:
  277. return f.read(max_len)
  278. except EnvironmentError, error:
  279. logging.info('Loading file %s failed: %d: %s'%
  280. (file_name,
  281. error.errno,
  282. error.strerror)
  283. )
  284. return None
  285. def load_possibly_compressed_response_json(response):
  286. if response.info().get('Content-Encoding') == 'gzip':
  287. buf = StringIO.StringIO( response.read() )
  288. f = gzip.GzipFile(fileobj=buf)
  289. return json.load(f)
  290. else:
  291. return json.load(response)
  292. def load_json_from_file(json_file_name):
  293. # An exception here may be resolved by deleting the .last_modified
  294. # and .json files, and re-running the script
  295. try:
  296. with open(json_file_name, 'r') as f:
  297. return json.load(f)
  298. except EnvironmentError, error:
  299. raise Exception('Reading not-modified json file %s failed: %d: %s'%
  300. (json_file_name,
  301. error.errno,
  302. error.strerror)
  303. )
  304. ## OnionOO Functions
  305. def datestr_to_datetime(datestr):
  306. # Parse datetimes like: Fri, 02 Oct 2015 13:34:14 GMT
  307. if datestr is not None:
  308. dt = dateutil.parser.parse(datestr)
  309. else:
  310. # Never modified - use start of epoch
  311. dt = datetime.datetime.utcfromtimestamp(0)
  312. # strip any timezone out (in case they're supported in future)
  313. dt = dt.replace(tzinfo=None)
  314. return dt
  315. def onionoo_fetch(what, **kwargs):
  316. params = kwargs
  317. params['type'] = 'relay'
  318. #params['limit'] = 10
  319. params['first_seen_days'] = '%d-'%(ADDRESS_AND_PORT_STABLE_DAYS,)
  320. params['last_seen_days'] = '-7'
  321. params['flag'] = 'V2Dir'
  322. url = ONIONOO + what + '?' + urllib.urlencode(params)
  323. # Unfortunately, the URL is too long for some OS filenames,
  324. # but we still don't want to get files from different URLs mixed up
  325. base_file_name = what + '-' + hashlib.sha1(url).hexdigest()
  326. full_url_file_name = base_file_name + '.full_url'
  327. MAX_FULL_URL_LENGTH = 1024
  328. last_modified_file_name = base_file_name + '.last_modified'
  329. MAX_LAST_MODIFIED_LENGTH = 64
  330. json_file_name = base_file_name + '.json'
  331. if LOCAL_FILES_ONLY:
  332. # Read from the local file, don't write to anything
  333. response_json = load_json_from_file(json_file_name)
  334. else:
  335. # store the full URL to a file for debugging
  336. # no need to compare as long as you trust SHA-1
  337. write_to_file(url, full_url_file_name, MAX_FULL_URL_LENGTH)
  338. request = urllib2.Request(url)
  339. request.add_header('Accept-encoding', 'gzip')
  340. # load the last modified date from the file, if it exists
  341. last_mod_date = read_from_file(last_modified_file_name,
  342. MAX_LAST_MODIFIED_LENGTH)
  343. if last_mod_date is not None:
  344. request.add_header('If-modified-since', last_mod_date)
  345. # Parse last modified date
  346. last_mod = datestr_to_datetime(last_mod_date)
  347. # Not Modified and still recent enough to be useful
  348. # Onionoo / Globe used to use 6 hours, but we can afford a day
  349. required_freshness = datetime.datetime.utcnow()
  350. # strip any timezone out (to match dateutil.parser)
  351. required_freshness = required_freshness.replace(tzinfo=None)
  352. required_freshness -= datetime.timedelta(hours=24)
  353. # Make the OnionOO request
  354. response_code = 0
  355. try:
  356. response = urllib2.urlopen(request)
  357. response_code = response.getcode()
  358. except urllib2.HTTPError, error:
  359. response_code = error.code
  360. if response_code == 304: # not modified
  361. pass
  362. else:
  363. raise Exception("Could not get " + url + ": "
  364. + str(error.code) + ": " + error.reason)
  365. if response_code == 200: # OK
  366. last_mod = datestr_to_datetime(response.info().get('Last-Modified'))
  367. # Check for freshness
  368. if last_mod < required_freshness:
  369. if last_mod_date is not None:
  370. # This check sometimes fails transiently, retry the script if it does
  371. date_message = "Outdated data: last updated " + last_mod_date
  372. else:
  373. date_message = "No data: never downloaded "
  374. raise Exception(date_message + " from " + url)
  375. # Process the data
  376. if response_code == 200: # OK
  377. response_json = load_possibly_compressed_response_json(response)
  378. with open(json_file_name, 'w') as f:
  379. # use the most compact json representation to save space
  380. json.dump(response_json, f, separators=(',',':'))
  381. # store the last modified date in its own file
  382. if response.info().get('Last-modified') is not None:
  383. write_to_file(response.info().get('Last-Modified'),
  384. last_modified_file_name,
  385. MAX_LAST_MODIFIED_LENGTH)
  386. elif response_code == 304: # Not Modified
  387. response_json = load_json_from_file(json_file_name)
  388. else: # Unexpected HTTP response code not covered in the HTTPError above
  389. raise Exception("Unexpected HTTP response code to " + url + ": "
  390. + str(response_code))
  391. register_fetch_source(what,
  392. url,
  393. response_json['relays_published'],
  394. response_json['version'])
  395. return response_json
  396. def fetch(what, **kwargs):
  397. #x = onionoo_fetch(what, **kwargs)
  398. # don't use sort_keys, as the order of or_addresses is significant
  399. #print json.dumps(x, indent=4, separators=(',', ': '))
  400. #sys.exit(0)
  401. return onionoo_fetch(what, **kwargs)
  402. ## Fallback Candidate Class
  403. class Candidate(object):
  404. CUTOFF_ADDRESS_AND_PORT_STABLE = (datetime.datetime.utcnow()
  405. - datetime.timedelta(ADDRESS_AND_PORT_STABLE_DAYS))
  406. def __init__(self, details):
  407. for f in ['fingerprint', 'nickname', 'last_changed_address_or_port',
  408. 'consensus_weight', 'or_addresses', 'dir_address']:
  409. if not f in details: raise Exception("Document has no %s field."%(f,))
  410. if not 'contact' in details:
  411. details['contact'] = None
  412. if not 'flags' in details or details['flags'] is None:
  413. details['flags'] = []
  414. if (not 'advertised_bandwidth' in details
  415. or details['advertised_bandwidth'] is None):
  416. # relays without advertised bandwdith have it calculated from their
  417. # consensus weight
  418. details['advertised_bandwidth'] = 0
  419. if (not 'effective_family' in details
  420. or details['effective_family'] is None):
  421. details['effective_family'] = []
  422. details['last_changed_address_or_port'] = parse_ts(
  423. details['last_changed_address_or_port'])
  424. self._data = details
  425. self._stable_sort_or_addresses()
  426. self._fpr = self._data['fingerprint']
  427. self._running = self._guard = self._v2dir = 0.
  428. self._split_dirport()
  429. self._compute_orport()
  430. if self.orport is None:
  431. raise Exception("Failed to get an orport for %s."%(self._fpr,))
  432. self._compute_ipv6addr()
  433. if not self.has_ipv6():
  434. logging.debug("Failed to get an ipv6 address for %s."%(self._fpr,))
  435. def _stable_sort_or_addresses(self):
  436. # replace self._data['or_addresses'] with a stable ordering,
  437. # sorting the secondary addresses in string order
  438. # leave the received order in self._data['or_addresses_raw']
  439. self._data['or_addresses_raw'] = self._data['or_addresses']
  440. or_address_primary = self._data['or_addresses'][:1]
  441. # subsequent entries in the or_addresses array are in an arbitrary order
  442. # so we stabilise the addresses by sorting them in string order
  443. or_addresses_secondaries_stable = sorted(self._data['or_addresses'][1:])
  444. or_addresses_stable = or_address_primary + or_addresses_secondaries_stable
  445. self._data['or_addresses'] = or_addresses_stable
  446. def get_fingerprint(self):
  447. return self._fpr
  448. # is_valid_ipv[46]_address by gsathya, karsten, 2013
  449. @staticmethod
  450. def is_valid_ipv4_address(address):
  451. if not isinstance(address, (str, unicode)):
  452. return False
  453. # check if there are four period separated values
  454. if address.count(".") != 3:
  455. return False
  456. # checks that each value in the octet are decimal values between 0-255
  457. for entry in address.split("."):
  458. if not entry.isdigit() or int(entry) < 0 or int(entry) > 255:
  459. return False
  460. elif entry[0] == "0" and len(entry) > 1:
  461. return False # leading zeros, for instance in "1.2.3.001"
  462. return True
  463. @staticmethod
  464. def is_valid_ipv6_address(address):
  465. if not isinstance(address, (str, unicode)):
  466. return False
  467. # remove brackets
  468. address = address[1:-1]
  469. # addresses are made up of eight colon separated groups of four hex digits
  470. # with leading zeros being optional
  471. # https://en.wikipedia.org/wiki/IPv6#Address_format
  472. colon_count = address.count(":")
  473. if colon_count > 7:
  474. return False # too many groups
  475. elif colon_count != 7 and not "::" in address:
  476. return False # not enough groups and none are collapsed
  477. elif address.count("::") > 1 or ":::" in address:
  478. return False # multiple groupings of zeros can't be collapsed
  479. found_ipv4_on_previous_entry = False
  480. for entry in address.split(":"):
  481. # If an IPv6 address has an embedded IPv4 address,
  482. # it must be the last entry
  483. if found_ipv4_on_previous_entry:
  484. return False
  485. if not re.match("^[0-9a-fA-f]{0,4}$", entry):
  486. if not Candidate.is_valid_ipv4_address(entry):
  487. return False
  488. else:
  489. found_ipv4_on_previous_entry = True
  490. return True
  491. def _split_dirport(self):
  492. # Split the dir_address into dirip and dirport
  493. (self.dirip, _dirport) = self._data['dir_address'].split(':', 2)
  494. self.dirport = int(_dirport)
  495. def _compute_orport(self):
  496. # Choose the first ORPort that's on the same IPv4 address as the DirPort.
  497. # In rare circumstances, this might not be the primary ORPort address.
  498. # However, _stable_sort_or_addresses() ensures we choose the same one
  499. # every time, even if onionoo changes the order of the secondaries.
  500. self._split_dirport()
  501. self.orport = None
  502. for i in self._data['or_addresses']:
  503. if i != self._data['or_addresses'][0]:
  504. logging.debug('Secondary IPv4 Address Used for %s: %s'%(self._fpr, i))
  505. (ipaddr, port) = i.rsplit(':', 1)
  506. if (ipaddr == self.dirip) and Candidate.is_valid_ipv4_address(ipaddr):
  507. self.orport = int(port)
  508. return
  509. def _compute_ipv6addr(self):
  510. # Choose the first IPv6 address that uses the same port as the ORPort
  511. # Or, choose the first IPv6 address in the list
  512. # _stable_sort_or_addresses() ensures we choose the same IPv6 address
  513. # every time, even if onionoo changes the order of the secondaries.
  514. self.ipv6addr = None
  515. self.ipv6orport = None
  516. # Choose the first IPv6 address that uses the same port as the ORPort
  517. for i in self._data['or_addresses']:
  518. (ipaddr, port) = i.rsplit(':', 1)
  519. if (port == self.orport) and Candidate.is_valid_ipv6_address(ipaddr):
  520. self.ipv6addr = ipaddr
  521. self.ipv6orport = int(port)
  522. return
  523. # Choose the first IPv6 address in the list
  524. for i in self._data['or_addresses']:
  525. (ipaddr, port) = i.rsplit(':', 1)
  526. if Candidate.is_valid_ipv6_address(ipaddr):
  527. self.ipv6addr = ipaddr
  528. self.ipv6orport = int(port)
  529. return
  530. @staticmethod
  531. def _extract_generic_history(history, which='unknown'):
  532. # given a tree like this:
  533. # {
  534. # "1_month": {
  535. # "count": 187,
  536. # "factor": 0.001001001001001001,
  537. # "first": "2015-02-27 06:00:00",
  538. # "interval": 14400,
  539. # "last": "2015-03-30 06:00:00",
  540. # "values": [
  541. # 999,
  542. # 999
  543. # ]
  544. # },
  545. # "1_week": {
  546. # "count": 169,
  547. # "factor": 0.001001001001001001,
  548. # "first": "2015-03-23 07:30:00",
  549. # "interval": 3600,
  550. # "last": "2015-03-30 07:30:00",
  551. # "values": [ ...]
  552. # },
  553. # "1_year": {
  554. # "count": 177,
  555. # "factor": 0.001001001001001001,
  556. # "first": "2014-04-11 00:00:00",
  557. # "interval": 172800,
  558. # "last": "2015-03-29 00:00:00",
  559. # "values": [ ...]
  560. # },
  561. # "3_months": {
  562. # "count": 185,
  563. # "factor": 0.001001001001001001,
  564. # "first": "2014-12-28 06:00:00",
  565. # "interval": 43200,
  566. # "last": "2015-03-30 06:00:00",
  567. # "values": [ ...]
  568. # }
  569. # },
  570. # extract exactly one piece of data per time interval,
  571. # using smaller intervals where available.
  572. #
  573. # returns list of (age, length, value) dictionaries.
  574. generic_history = []
  575. periods = history.keys()
  576. periods.sort(key = lambda x: history[x]['interval'])
  577. now = datetime.datetime.utcnow()
  578. newest = now
  579. for p in periods:
  580. h = history[p]
  581. interval = datetime.timedelta(seconds = h['interval'])
  582. this_ts = parse_ts(h['last'])
  583. if (len(h['values']) != h['count']):
  584. logging.warning('Inconsistent value count in %s document for %s'
  585. %(p, which))
  586. for v in reversed(h['values']):
  587. if (this_ts <= newest):
  588. agt1 = now - this_ts
  589. agt2 = interval
  590. agetmp1 = (agt1.microseconds + (agt1.seconds + agt1.days * 24 * 3600)
  591. * 10**6) / 10**6
  592. agetmp2 = (agt2.microseconds + (agt2.seconds + agt2.days * 24 * 3600)
  593. * 10**6) / 10**6
  594. generic_history.append(
  595. { 'age': agetmp1,
  596. 'length': agetmp2,
  597. 'value': v
  598. })
  599. newest = this_ts
  600. this_ts -= interval
  601. if (this_ts + interval != parse_ts(h['first'])):
  602. logging.warning('Inconsistent time information in %s document for %s'
  603. %(p, which))
  604. #print json.dumps(generic_history, sort_keys=True,
  605. # indent=4, separators=(',', ': '))
  606. return generic_history
  607. @staticmethod
  608. def _avg_generic_history(generic_history):
  609. a = []
  610. for i in generic_history:
  611. if i['age'] > (ADDRESS_AND_PORT_STABLE_DAYS * 24 * 3600):
  612. continue
  613. if (i['length'] is not None
  614. and i['age'] is not None
  615. and i['value'] is not None):
  616. w = i['length'] * math.pow(AGE_ALPHA, i['age']/(3600*24))
  617. a.append( (i['value'] * w, w) )
  618. sv = math.fsum(map(lambda x: x[0], a))
  619. sw = math.fsum(map(lambda x: x[1], a))
  620. if sw == 0.0:
  621. svw = 0.0
  622. else:
  623. svw = sv/sw
  624. return svw
  625. def _add_generic_history(self, history):
  626. periods = r['read_history'].keys()
  627. periods.sort(key = lambda x: r['read_history'][x]['interval'] )
  628. print periods
  629. def add_running_history(self, history):
  630. pass
  631. def add_uptime(self, uptime):
  632. logging.debug('Adding uptime %s.'%(self._fpr,))
  633. # flags we care about: Running, V2Dir, Guard
  634. if not 'flags' in uptime:
  635. logging.debug('No flags in document for %s.'%(self._fpr,))
  636. return
  637. for f in ['Running', 'Guard', 'V2Dir']:
  638. if not f in uptime['flags']:
  639. logging.debug('No %s in flags for %s.'%(f, self._fpr,))
  640. return
  641. running = self._extract_generic_history(uptime['flags']['Running'],
  642. '%s-Running'%(self._fpr))
  643. guard = self._extract_generic_history(uptime['flags']['Guard'],
  644. '%s-Guard'%(self._fpr))
  645. v2dir = self._extract_generic_history(uptime['flags']['V2Dir'],
  646. '%s-V2Dir'%(self._fpr))
  647. if 'BadExit' in uptime['flags']:
  648. badexit = self._extract_generic_history(uptime['flags']['BadExit'],
  649. '%s-BadExit'%(self._fpr))
  650. self._running = self._avg_generic_history(running) / ONIONOO_SCALE_ONE
  651. self._guard = self._avg_generic_history(guard) / ONIONOO_SCALE_ONE
  652. self._v2dir = self._avg_generic_history(v2dir) / ONIONOO_SCALE_ONE
  653. self._badexit = None
  654. if 'BadExit' in uptime['flags']:
  655. self._badexit = self._avg_generic_history(badexit) / ONIONOO_SCALE_ONE
  656. def is_candidate(self):
  657. must_be_running_now = (PERFORM_IPV4_DIRPORT_CHECKS
  658. or PERFORM_IPV6_DIRPORT_CHECKS)
  659. if (must_be_running_now and not self.is_running()):
  660. logging.info('%s not a candidate: not running now, unable to check ' +
  661. 'DirPort consensus download', self._fpr)
  662. return False
  663. if (self._data['last_changed_address_or_port'] >
  664. self.CUTOFF_ADDRESS_AND_PORT_STABLE):
  665. logging.info('%s not a candidate: changed address/port recently (%s)',
  666. self._fpr, self._data['last_changed_address_or_port'])
  667. return False
  668. if self._running < CUTOFF_RUNNING:
  669. logging.info('%s not a candidate: running avg too low (%lf)',
  670. self._fpr, self._running)
  671. return False
  672. if self._v2dir < CUTOFF_V2DIR:
  673. logging.info('%s not a candidate: v2dir avg too low (%lf)',
  674. self._fpr, self._v2dir)
  675. return False
  676. if self._badexit is not None and self._badexit > PERMITTED_BADEXIT:
  677. logging.info('%s not a candidate: badexit avg too high (%lf)',
  678. self._fpr, self._badexit)
  679. return False
  680. # if the relay doesn't report a version, also exclude the relay
  681. if (not self._data.has_key('recommended_version')
  682. or not self._data['recommended_version']):
  683. logging.info('%s not a candidate: version not recommended', self._fpr)
  684. return False
  685. if self._guard < CUTOFF_GUARD:
  686. logging.info('%s not a candidate: guard avg too low (%lf)',
  687. self._fpr, self._guard)
  688. return False
  689. if (not self._data.has_key('consensus_weight')
  690. or self._data['consensus_weight'] < 1):
  691. logging.info('%s not a candidate: consensus weight invalid', self._fpr)
  692. return False
  693. return True
  694. def is_in_whitelist(self, relaylist):
  695. """ A fallback matches if each key in the whitelist line matches:
  696. ipv4
  697. dirport
  698. orport
  699. id
  700. ipv6 address and port (if present)
  701. If the fallback has an ipv6 key, the whitelist line must also have
  702. it, and vice versa, otherwise they don't match. """
  703. ipv6 = None
  704. if self.has_ipv6():
  705. ipv6 = '%s:%d'%(self.ipv6addr, self.ipv6orport)
  706. for entry in relaylist:
  707. if entry['id'] != self._fpr:
  708. # can't log here unless we match an IP and port, because every relay's
  709. # fingerprint is compared to every entry's fingerprint
  710. if entry['ipv4'] == self.dirip and int(entry['orport']) == self.orport:
  711. logging.warning('%s excluded: has OR %s:%d changed fingerprint to ' +
  712. '%s?', entry['id'], self.dirip, self.orport,
  713. self._fpr)
  714. if self.has_ipv6() and entry.has_key('ipv6') and entry['ipv6'] == ipv6:
  715. logging.warning('%s excluded: has OR %s changed fingerprint to ' +
  716. '%s?', entry['id'], ipv6, self._fpr)
  717. continue
  718. if entry['ipv4'] != self.dirip:
  719. logging.warning('%s excluded: has it changed IPv4 from %s to %s?',
  720. self._fpr, entry['ipv4'], self.dirip)
  721. continue
  722. if int(entry['dirport']) != self.dirport:
  723. logging.warning('%s excluded: has it changed DirPort from %s:%d to ' +
  724. '%s:%d?', self._fpr, self.dirip, int(entry['dirport']),
  725. self.dirip, self.dirport)
  726. continue
  727. if int(entry['orport']) != self.orport:
  728. logging.warning('%s excluded: has it changed ORPort from %s:%d to ' +
  729. '%s:%d?', self._fpr, self.dirip, int(entry['orport']),
  730. self.dirip, self.orport)
  731. continue
  732. if entry.has_key('ipv6') and self.has_ipv6():
  733. # if both entry and fallback have an ipv6 address, compare them
  734. if entry['ipv6'] != ipv6:
  735. logging.warning('%s excluded: has it changed IPv6 ORPort from %s ' +
  736. 'to %s?', self._fpr, entry['ipv6'], ipv6)
  737. continue
  738. # if the fallback has an IPv6 address but the whitelist entry
  739. # doesn't, or vice versa, the whitelist entry doesn't match
  740. elif entry.has_key('ipv6') and not self.has_ipv6():
  741. logging.warning('%s excluded: has it lost its former IPv6 address %s?',
  742. self._fpr, entry['ipv6'])
  743. continue
  744. elif not entry.has_key('ipv6') and self.has_ipv6():
  745. logging.warning('%s excluded: has it gained an IPv6 address %s?',
  746. self._fpr, ipv6)
  747. continue
  748. return True
  749. return False
  750. def is_in_blacklist(self, relaylist):
  751. """ A fallback matches a blacklist line if a sufficiently specific group
  752. of attributes matches:
  753. ipv4 & dirport
  754. ipv4 & orport
  755. id
  756. ipv6 & dirport
  757. ipv6 & ipv6 orport
  758. If the fallback and the blacklist line both have an ipv6 key,
  759. their values will be compared, otherwise, they will be ignored.
  760. If there is no dirport and no orport, the entry matches all relays on
  761. that ip. """
  762. for entry in relaylist:
  763. for key in entry:
  764. value = entry[key]
  765. if key == 'id' and value == self._fpr:
  766. logging.info('%s is in the blacklist: fingerprint matches',
  767. self._fpr)
  768. return True
  769. if key == 'ipv4' and value == self.dirip:
  770. # if the dirport is present, check it too
  771. if entry.has_key('dirport'):
  772. if int(entry['dirport']) == self.dirport:
  773. logging.info('%s is in the blacklist: IPv4 (%s) and ' +
  774. 'DirPort (%d) match', self._fpr, self.dirip,
  775. self.dirport)
  776. return True
  777. # if the orport is present, check it too
  778. elif entry.has_key('orport'):
  779. if int(entry['orport']) == self.orport:
  780. logging.info('%s is in the blacklist: IPv4 (%s) and ' +
  781. 'ORPort (%d) match', self._fpr, self.dirip,
  782. self.orport)
  783. return True
  784. else:
  785. logging.info('%s is in the blacklist: IPv4 (%s) matches, and ' +
  786. 'entry has no DirPort or ORPort', self._fpr,
  787. self.dirip)
  788. return True
  789. ipv6 = None
  790. if self.has_ipv6():
  791. ipv6 = '%s:%d'%(self.ipv6addr, self.ipv6orport)
  792. if (key == 'ipv6' and self.has_ipv6()):
  793. # if both entry and fallback have an ipv6 address, compare them,
  794. # otherwise, disregard ipv6 addresses
  795. if value == ipv6:
  796. # if the dirport is present, check it too
  797. if entry.has_key('dirport'):
  798. if int(entry['dirport']) == self.dirport:
  799. logging.info('%s is in the blacklist: IPv6 (%s) and ' +
  800. 'DirPort (%d) match', self._fpr, ipv6,
  801. self.dirport)
  802. return True
  803. # we've already checked the ORPort, it's part of entry['ipv6']
  804. else:
  805. logging.info('%s is in the blacklist: IPv6 (%s) matches, and' +
  806. 'entry has no DirPort', self._fpr, ipv6)
  807. return True
  808. elif (key == 'ipv6' or self.has_ipv6()):
  809. # only log if the fingerprint matches but the IPv6 doesn't
  810. if entry.has_key('id') and entry['id'] == self._fpr:
  811. logging.info('%s skipping IPv6 blacklist comparison: relay ' +
  812. 'has%s IPv6%s, but entry has%s IPv6%s', self._fpr,
  813. '' if self.has_ipv6() else ' no',
  814. (' (' + ipv6 + ')') if self.has_ipv6() else '',
  815. '' if key == 'ipv6' else ' no',
  816. (' (' + value + ')') if key == 'ipv6' else '')
  817. logging.warning('Has %s %s IPv6 address %s?', self._fpr,
  818. 'gained an' if self.has_ipv6() else 'lost its former',
  819. ipv6 if self.has_ipv6() else value)
  820. return False
  821. def cw_to_bw_factor(self):
  822. # any relays with a missing or zero consensus weight are not candidates
  823. # any relays with a missing advertised bandwidth have it set to zero
  824. return self._data['advertised_bandwidth'] / self._data['consensus_weight']
  825. # since advertised_bandwidth is reported by the relay, it can be gamed
  826. # to avoid this, use the median consensus weight to bandwidth factor to
  827. # estimate this relay's measured bandwidth, and make that the upper limit
  828. def measured_bandwidth(self, median_cw_to_bw_factor):
  829. cw_to_bw= median_cw_to_bw_factor
  830. # Reduce exit bandwidth to make sure we're not overloading them
  831. if self.is_exit():
  832. cw_to_bw *= EXIT_BANDWIDTH_FRACTION
  833. measured_bandwidth = self._data['consensus_weight'] * cw_to_bw
  834. if self._data['advertised_bandwidth'] != 0:
  835. # limit advertised bandwidth (if available) to measured bandwidth
  836. return min(measured_bandwidth, self._data['advertised_bandwidth'])
  837. else:
  838. return measured_bandwidth
  839. def set_measured_bandwidth(self, median_cw_to_bw_factor):
  840. self._data['measured_bandwidth'] = self.measured_bandwidth(
  841. median_cw_to_bw_factor)
  842. def is_exit(self):
  843. return 'Exit' in self._data['flags']
  844. def is_guard(self):
  845. return 'Guard' in self._data['flags']
  846. def is_running(self):
  847. return 'Running' in self._data['flags']
  848. # does this fallback have an IPv6 address and orport?
  849. def has_ipv6(self):
  850. return self.ipv6addr is not None and self.ipv6orport is not None
  851. # strip leading and trailing brackets from an IPv6 address
  852. # safe to use on non-bracketed IPv6 and on IPv4 addresses
  853. # also convert to unicode, and make None appear as ''
  854. @staticmethod
  855. def strip_ipv6_brackets(ip):
  856. if ip is None:
  857. return unicode('')
  858. if len(ip) < 2:
  859. return unicode(ip)
  860. if ip[0] == '[' and ip[-1] == ']':
  861. return unicode(ip[1:-1])
  862. return unicode(ip)
  863. # are ip_a and ip_b in the same netblock?
  864. # mask_bits is the size of the netblock
  865. # takes both IPv4 and IPv6 addresses
  866. # the versions of ip_a and ip_b must be the same
  867. # the mask must be valid for the IP version
  868. @staticmethod
  869. def netblocks_equal(ip_a, ip_b, mask_bits):
  870. if ip_a is None or ip_b is None:
  871. return False
  872. ip_a = Candidate.strip_ipv6_brackets(ip_a)
  873. ip_b = Candidate.strip_ipv6_brackets(ip_b)
  874. a = ipaddress.ip_address(ip_a)
  875. b = ipaddress.ip_address(ip_b)
  876. if a.version != b.version:
  877. raise Exception('Mismatching IP versions in %s and %s'%(ip_a, ip_b))
  878. if mask_bits > a.max_prefixlen:
  879. logging.error('Bad IP mask %d for %s and %s'%(mask_bits, ip_a, ip_b))
  880. mask_bits = a.max_prefixlen
  881. if mask_bits < 0:
  882. logging.error('Bad IP mask %d for %s and %s'%(mask_bits, ip_a, ip_b))
  883. mask_bits = 0
  884. a_net = ipaddress.ip_network('%s/%d'%(ip_a, mask_bits), strict=False)
  885. return b in a_net
  886. # is this fallback's IPv4 address (dirip) in the same netblock as other's
  887. # IPv4 address?
  888. # mask_bits is the size of the netblock
  889. def ipv4_netblocks_equal(self, other, mask_bits):
  890. return Candidate.netblocks_equal(self.dirip, other.dirip, mask_bits)
  891. # is this fallback's IPv6 address (ipv6addr) in the same netblock as
  892. # other's IPv6 address?
  893. # Returns False if either fallback has no IPv6 address
  894. # mask_bits is the size of the netblock
  895. def ipv6_netblocks_equal(self, other, mask_bits):
  896. if not self.has_ipv6() or not other.has_ipv6():
  897. return False
  898. return Candidate.netblocks_equal(self.ipv6addr, other.ipv6addr, mask_bits)
  899. # is this fallback's IPv4 DirPort the same as other's IPv4 DirPort?
  900. def dirport_equal(self, other):
  901. return self.dirport == other.dirport
  902. # is this fallback's IPv4 ORPort the same as other's IPv4 ORPort?
  903. def ipv4_orport_equal(self, other):
  904. return self.orport == other.orport
  905. # is this fallback's IPv6 ORPort the same as other's IPv6 ORPort?
  906. # Returns False if either fallback has no IPv6 address
  907. def ipv6_orport_equal(self, other):
  908. if not self.has_ipv6() or not other.has_ipv6():
  909. return False
  910. return self.ipv6orport == other.ipv6orport
  911. # does this fallback have the same DirPort, IPv4 ORPort, or
  912. # IPv6 ORPort as other?
  913. # Ignores IPv6 ORPort if either fallback has no IPv6 address
  914. def port_equal(self, other):
  915. return (self.dirport_equal(other) or self.ipv4_orport_equal(other)
  916. or self.ipv6_orport_equal(other))
  917. # return a list containing IPv4 ORPort, DirPort, and IPv6 ORPort (if present)
  918. def port_list(self):
  919. ports = [self.dirport, self.orport]
  920. if self.has_ipv6() and not self.ipv6orport in ports:
  921. ports.append(self.ipv6orport)
  922. return ports
  923. # does this fallback share a port with other, regardless of whether the
  924. # port types match?
  925. # For example, if self's IPv4 ORPort is 80 and other's DirPort is 80,
  926. # return True
  927. def port_shared(self, other):
  928. for p in self.port_list():
  929. if p in other.port_list():
  930. return True
  931. return False
  932. # report how long it takes to download a consensus from dirip:dirport
  933. @staticmethod
  934. def fallback_consensus_download_speed(dirip, dirport, nickname, max_time):
  935. download_failed = False
  936. downloader = DescriptorDownloader()
  937. start = datetime.datetime.utcnow()
  938. # some directory mirrors respond to requests in ways that hang python
  939. # sockets, which is why we log this line here
  940. logging.info('Initiating consensus download from %s (%s:%d).', nickname,
  941. dirip, dirport)
  942. # there appears to be about 1 second of overhead when comparing stem's
  943. # internal trace time and the elapsed time calculated here
  944. TIMEOUT_SLOP = 1.0
  945. try:
  946. downloader.get_consensus(endpoints = [(dirip, dirport)],
  947. timeout = (max_time + TIMEOUT_SLOP),
  948. validate = True,
  949. retries = 0,
  950. fall_back_to_authority = False).run()
  951. except Exception, stem_error:
  952. logging.info('Unable to retrieve a consensus from %s: %s', nickname,
  953. stem_error)
  954. status = 'error: "%s"' % (stem_error)
  955. level = logging.WARNING
  956. download_failed = True
  957. elapsed = (datetime.datetime.utcnow() - start).total_seconds()
  958. if elapsed > max_time:
  959. status = 'too slow'
  960. level = logging.WARNING
  961. download_failed = True
  962. else:
  963. status = 'ok'
  964. level = logging.DEBUG
  965. logging.log(level, 'Consensus download: %0.1fs %s from %s (%s:%d), ' +
  966. 'max download time %0.1fs.', elapsed, status, nickname,
  967. dirip, dirport, max_time)
  968. return download_failed
  969. # does this fallback download the consensus fast enough?
  970. def check_fallback_download_consensus(self):
  971. # include the relay if we're not doing a check, or we can't check (IPv6)
  972. ipv4_failed = False
  973. ipv6_failed = False
  974. if PERFORM_IPV4_DIRPORT_CHECKS:
  975. ipv4_failed = Candidate.fallback_consensus_download_speed(self.dirip,
  976. self.dirport,
  977. self._data['nickname'],
  978. CONSENSUS_DOWNLOAD_SPEED_MAX)
  979. if self.has_ipv6() and PERFORM_IPV6_DIRPORT_CHECKS:
  980. # Clients assume the IPv6 DirPort is the same as the IPv4 DirPort
  981. ipv6_failed = Candidate.fallback_consensus_download_speed(self.ipv6addr,
  982. self.dirport,
  983. self._data['nickname'],
  984. CONSENSUS_DOWNLOAD_SPEED_MAX)
  985. return ((not ipv4_failed) and (not ipv6_failed))
  986. # if this fallback has not passed a download check, try it again,
  987. # and record the result, available in get_fallback_download_consensus
  988. def try_fallback_download_consensus(self):
  989. if not self.get_fallback_download_consensus():
  990. self._data['download_check'] = self.check_fallback_download_consensus()
  991. # did this fallback pass the download check?
  992. def get_fallback_download_consensus(self):
  993. # if we're not performing checks, return True
  994. if not PERFORM_IPV4_DIRPORT_CHECKS and not PERFORM_IPV6_DIRPORT_CHECKS:
  995. return True
  996. # if we are performing checks, but haven't done one, return False
  997. if not self._data.has_key('download_check'):
  998. return False
  999. return self._data['download_check']
  1000. # output an optional header comment and info for this fallback
  1001. # try_fallback_download_consensus before calling this
  1002. def fallbackdir_line(self, fallbacks, prefilter_fallbacks):
  1003. s = ''
  1004. if OUTPUT_COMMENTS:
  1005. s += self.fallbackdir_comment(fallbacks, prefilter_fallbacks)
  1006. # if the download speed is ok, output a C string
  1007. # if it's not, but we OUTPUT_COMMENTS, output a commented-out C string
  1008. if self.get_fallback_download_consensus() or OUTPUT_COMMENTS:
  1009. s += self.fallbackdir_info(self.get_fallback_download_consensus())
  1010. return s
  1011. # output a header comment for this fallback
  1012. def fallbackdir_comment(self, fallbacks, prefilter_fallbacks):
  1013. # /*
  1014. # nickname
  1015. # flags
  1016. # adjusted bandwidth, consensus weight
  1017. # [contact]
  1018. # [identical contact counts]
  1019. # */
  1020. # Multiline C comment
  1021. s = '/*'
  1022. s += '\n'
  1023. s += cleanse_c_multiline_comment(self._data['nickname'])
  1024. s += '\n'
  1025. s += 'Flags: '
  1026. s += cleanse_c_multiline_comment(' '.join(sorted(self._data['flags'])))
  1027. s += '\n'
  1028. # this is an adjusted bandwidth, see calculate_measured_bandwidth()
  1029. bandwidth = self._data['measured_bandwidth']
  1030. weight = self._data['consensus_weight']
  1031. s += 'Bandwidth: %.1f MByte/s, Consensus Weight: %d'%(
  1032. bandwidth/(1024.0*1024.0),
  1033. weight)
  1034. s += '\n'
  1035. if self._data['contact'] is not None:
  1036. s += cleanse_c_multiline_comment(self._data['contact'])
  1037. if CONTACT_COUNT or CONTACT_BLACKLIST_COUNT:
  1038. fallback_count = len([f for f in fallbacks
  1039. if f._data['contact'] == self._data['contact']])
  1040. if fallback_count > 1:
  1041. s += '\n'
  1042. s += '%d identical contacts listed' % (fallback_count)
  1043. if CONTACT_BLACKLIST_COUNT:
  1044. prefilter_count = len([f for f in prefilter_fallbacks
  1045. if f._data['contact'] == self._data['contact']])
  1046. filter_count = prefilter_count - fallback_count
  1047. if filter_count > 0:
  1048. if fallback_count > 1:
  1049. s += ' '
  1050. else:
  1051. s += '\n'
  1052. s += '%d blacklisted' % (filter_count)
  1053. s += '\n'
  1054. s += '*/'
  1055. s += '\n'
  1056. return s
  1057. # output the fallback info C string for this fallback
  1058. # this is the text that would go after FallbackDir in a torrc
  1059. # if this relay failed the download test and we OUTPUT_COMMENTS,
  1060. # comment-out the returned string
  1061. def fallbackdir_info(self, dl_speed_ok):
  1062. # "address:dirport orport=port id=fingerprint"
  1063. # "[ipv6=addr:orport]"
  1064. # "weight=FALLBACK_OUTPUT_WEIGHT",
  1065. #
  1066. # Do we want a C string, or a commented-out string?
  1067. c_string = dl_speed_ok
  1068. comment_string = not dl_speed_ok and OUTPUT_COMMENTS
  1069. # If we don't want either kind of string, bail
  1070. if not c_string and not comment_string:
  1071. return ''
  1072. s = ''
  1073. # Comment out the fallback directory entry if it's too slow
  1074. # See the debug output for which address and port is failing
  1075. if comment_string:
  1076. s += '/* Consensus download failed or was too slow:\n'
  1077. # Multi-Line C string with trailing comma (part of a string list)
  1078. # This makes it easier to diff the file, and remove IPv6 lines using grep
  1079. # Integers don't need escaping
  1080. s += '"%s orport=%d id=%s"'%(
  1081. cleanse_c_string(self._data['dir_address']),
  1082. self.orport,
  1083. cleanse_c_string(self._fpr))
  1084. s += '\n'
  1085. if self.has_ipv6():
  1086. s += '" ipv6=%s:%d"'%(cleanse_c_string(self.ipv6addr), self.ipv6orport)
  1087. s += '\n'
  1088. s += '" weight=%d",'%(FALLBACK_OUTPUT_WEIGHT)
  1089. if comment_string:
  1090. s += '\n'
  1091. s += '*/'
  1092. return s
  1093. ## Fallback Candidate List Class
  1094. class CandidateList(dict):
  1095. def __init__(self):
  1096. pass
  1097. def _add_relay(self, details):
  1098. if not 'dir_address' in details: return
  1099. c = Candidate(details)
  1100. self[ c.get_fingerprint() ] = c
  1101. def _add_uptime(self, uptime):
  1102. try:
  1103. fpr = uptime['fingerprint']
  1104. except KeyError:
  1105. raise Exception("Document has no fingerprint field.")
  1106. try:
  1107. c = self[fpr]
  1108. except KeyError:
  1109. logging.debug('Got unknown relay %s in uptime document.'%(fpr,))
  1110. return
  1111. c.add_uptime(uptime)
  1112. def _add_details(self):
  1113. logging.debug('Loading details document.')
  1114. d = fetch('details',
  1115. fields=('fingerprint,nickname,contact,last_changed_address_or_port,' +
  1116. 'consensus_weight,advertised_bandwidth,or_addresses,' +
  1117. 'dir_address,recommended_version,flags,effective_family'))
  1118. logging.debug('Loading details document done.')
  1119. if not 'relays' in d: raise Exception("No relays found in document.")
  1120. for r in d['relays']: self._add_relay(r)
  1121. def _add_uptimes(self):
  1122. logging.debug('Loading uptime document.')
  1123. d = fetch('uptime')
  1124. logging.debug('Loading uptime document done.')
  1125. if not 'relays' in d: raise Exception("No relays found in document.")
  1126. for r in d['relays']: self._add_uptime(r)
  1127. def add_relays(self):
  1128. self._add_details()
  1129. self._add_uptimes()
  1130. def count_guards(self):
  1131. guard_count = 0
  1132. for fpr in self.keys():
  1133. if self[fpr].is_guard():
  1134. guard_count += 1
  1135. return guard_count
  1136. # Find fallbacks that fit the uptime, stability, and flags criteria,
  1137. # and make an array of them in self.fallbacks
  1138. def compute_fallbacks(self):
  1139. self.fallbacks = map(lambda x: self[x],
  1140. filter(lambda x: self[x].is_candidate(),
  1141. self.keys()))
  1142. # sort fallbacks by their consensus weight to advertised bandwidth factor,
  1143. # lowest to highest
  1144. # used to find the median cw_to_bw_factor()
  1145. def sort_fallbacks_by_cw_to_bw_factor(self):
  1146. self.fallbacks.sort(key=lambda f: f.cw_to_bw_factor())
  1147. # sort fallbacks by their measured bandwidth, highest to lowest
  1148. # calculate_measured_bandwidth before calling this
  1149. # this is useful for reviewing candidates in priority order
  1150. def sort_fallbacks_by_measured_bandwidth(self):
  1151. self.fallbacks.sort(key=lambda f: f._data['measured_bandwidth'],
  1152. reverse=True)
  1153. # sort fallbacks by the data field data_field, lowest to highest
  1154. def sort_fallbacks_by(self, data_field):
  1155. self.fallbacks.sort(key=lambda f: f._data[data_field])
  1156. @staticmethod
  1157. def load_relaylist(file_name):
  1158. """ Read each line in the file, and parse it like a FallbackDir line:
  1159. an IPv4 address and optional port:
  1160. <IPv4 address>:<port>
  1161. which are parsed into dictionary entries:
  1162. ipv4=<IPv4 address>
  1163. dirport=<port>
  1164. followed by a series of key=value entries:
  1165. orport=<port>
  1166. id=<fingerprint>
  1167. ipv6=<IPv6 address>:<IPv6 orport>
  1168. each line's key/value pairs are placed in a dictonary,
  1169. (of string -> string key/value pairs),
  1170. and these dictionaries are placed in an array.
  1171. comments start with # and are ignored """
  1172. relaylist = []
  1173. file_data = read_from_file(file_name, MAX_LIST_FILE_SIZE)
  1174. if file_data is None:
  1175. return relaylist
  1176. for line in file_data.split('\n'):
  1177. relay_entry = {}
  1178. # ignore comments
  1179. line_comment_split = line.split('#')
  1180. line = line_comment_split[0]
  1181. # cleanup whitespace
  1182. line = cleanse_whitespace(line)
  1183. line = line.strip()
  1184. if len(line) == 0:
  1185. continue
  1186. for item in line.split(' '):
  1187. item = item.strip()
  1188. if len(item) == 0:
  1189. continue
  1190. key_value_split = item.split('=')
  1191. kvl = len(key_value_split)
  1192. if kvl < 1 or kvl > 2:
  1193. print '#error Bad %s item: %s, format is key=value.'%(
  1194. file_name, item)
  1195. if kvl == 1:
  1196. # assume that entries without a key are the ipv4 address,
  1197. # perhaps with a dirport
  1198. ipv4_maybe_dirport = key_value_split[0]
  1199. ipv4_maybe_dirport_split = ipv4_maybe_dirport.split(':')
  1200. dirl = len(ipv4_maybe_dirport_split)
  1201. if dirl < 1 or dirl > 2:
  1202. print '#error Bad %s IPv4 item: %s, format is ipv4:port.'%(
  1203. file_name, item)
  1204. if dirl >= 1:
  1205. relay_entry['ipv4'] = ipv4_maybe_dirport_split[0]
  1206. if dirl == 2:
  1207. relay_entry['dirport'] = ipv4_maybe_dirport_split[1]
  1208. elif kvl == 2:
  1209. relay_entry[key_value_split[0]] = key_value_split[1]
  1210. relaylist.append(relay_entry)
  1211. return relaylist
  1212. # apply the fallback whitelist and blacklist
  1213. def apply_filter_lists(self):
  1214. excluded_count = 0
  1215. logging.debug('Applying whitelist and blacklist.')
  1216. # parse the whitelist and blacklist
  1217. whitelist = self.load_relaylist(WHITELIST_FILE_NAME)
  1218. blacklist = self.load_relaylist(BLACKLIST_FILE_NAME)
  1219. filtered_fallbacks = []
  1220. for f in self.fallbacks:
  1221. in_whitelist = f.is_in_whitelist(whitelist)
  1222. in_blacklist = f.is_in_blacklist(blacklist)
  1223. if in_whitelist and in_blacklist:
  1224. if BLACKLIST_EXCLUDES_WHITELIST_ENTRIES:
  1225. # exclude
  1226. excluded_count += 1
  1227. logging.warning('Excluding %s: in both blacklist and whitelist.',
  1228. f._fpr)
  1229. else:
  1230. # include
  1231. filtered_fallbacks.append(f)
  1232. elif in_whitelist:
  1233. # include
  1234. filtered_fallbacks.append(f)
  1235. elif in_blacklist:
  1236. # exclude
  1237. excluded_count += 1
  1238. logging.info('Excluding %s: in blacklist.', f._fpr)
  1239. else:
  1240. if INCLUDE_UNLISTED_ENTRIES:
  1241. # include
  1242. filtered_fallbacks.append(f)
  1243. else:
  1244. # exclude
  1245. excluded_count += 1
  1246. logging.info('Excluding %s: in neither blacklist nor whitelist.',
  1247. f._fpr)
  1248. self.fallbacks = filtered_fallbacks
  1249. return excluded_count
  1250. @staticmethod
  1251. def summarise_filters(initial_count, excluded_count):
  1252. return '/* Whitelist & blacklist excluded %d of %d candidates. */'%(
  1253. excluded_count, initial_count)
  1254. # calculate each fallback's measured bandwidth based on the median
  1255. # consensus weight to advertised bandwdith ratio
  1256. def calculate_measured_bandwidth(self):
  1257. self.sort_fallbacks_by_cw_to_bw_factor()
  1258. median_fallback = self.fallback_median(True)
  1259. if median_fallback is not None:
  1260. median_cw_to_bw_factor = median_fallback.cw_to_bw_factor()
  1261. else:
  1262. # this will never be used, because there are no fallbacks
  1263. median_cw_to_bw_factor = None
  1264. for f in self.fallbacks:
  1265. f.set_measured_bandwidth(median_cw_to_bw_factor)
  1266. # remove relays with low measured bandwidth from the fallback list
  1267. # calculate_measured_bandwidth for each relay before calling this
  1268. def remove_low_bandwidth_relays(self):
  1269. if MIN_BANDWIDTH is None:
  1270. return
  1271. above_min_bw_fallbacks = []
  1272. for f in self.fallbacks:
  1273. if f._data['measured_bandwidth'] >= MIN_BANDWIDTH:
  1274. above_min_bw_fallbacks.append(f)
  1275. else:
  1276. # the bandwidth we log here is limited by the relay's consensus weight
  1277. # as well as its adverttised bandwidth. See set_measured_bandwidth
  1278. # for details
  1279. logging.info('%s not a candidate: bandwidth %.1fMByte/s too low, ' +
  1280. 'must be at least %.1fMByte/s', f._fpr,
  1281. f._data['measured_bandwidth']/(1024.0*1024.0),
  1282. MIN_BANDWIDTH/(1024.0*1024.0))
  1283. self.fallbacks = above_min_bw_fallbacks
  1284. # the minimum fallback in the list
  1285. # call one of the sort_fallbacks_* functions before calling this
  1286. def fallback_min(self):
  1287. if len(self.fallbacks) > 0:
  1288. return self.fallbacks[-1]
  1289. else:
  1290. return None
  1291. # the median fallback in the list
  1292. # call one of the sort_fallbacks_* functions before calling this
  1293. def fallback_median(self, require_advertised_bandwidth):
  1294. # use the low-median when there are an evan number of fallbacks,
  1295. # for consistency with the bandwidth authorities
  1296. if len(self.fallbacks) > 0:
  1297. median_position = (len(self.fallbacks) - 1) / 2
  1298. if not require_advertised_bandwidth:
  1299. return self.fallbacks[median_position]
  1300. # if we need advertised_bandwidth but this relay doesn't have it,
  1301. # move to a fallback with greater consensus weight until we find one
  1302. while not self.fallbacks[median_position]._data['advertised_bandwidth']:
  1303. median_position += 1
  1304. if median_position >= len(self.fallbacks):
  1305. return None
  1306. return self.fallbacks[median_position]
  1307. else:
  1308. return None
  1309. # the maximum fallback in the list
  1310. # call one of the sort_fallbacks_* functions before calling this
  1311. def fallback_max(self):
  1312. if len(self.fallbacks) > 0:
  1313. return self.fallbacks[0]
  1314. else:
  1315. return None
  1316. # does exclusion_list contain attribute?
  1317. # if so, return False
  1318. # if not, return True
  1319. # if attribute is None or the empty string, always return True
  1320. @staticmethod
  1321. def allow(attribute, exclusion_list):
  1322. if attribute is None or attribute == '':
  1323. return True
  1324. elif attribute in exclusion_list:
  1325. return False
  1326. else:
  1327. return True
  1328. # make sure there is only one fallback per IPv4 address, and per IPv6 address
  1329. # there is only one IPv4 address on each fallback: the IPv4 DirPort address
  1330. # (we choose the IPv4 ORPort which is on the same IPv4 as the DirPort)
  1331. # there is at most one IPv6 address on each fallback: the IPv6 ORPort address
  1332. # we try to match the IPv4 ORPort, but will use any IPv6 address if needed
  1333. # (clients assume the IPv6 DirPort is the same as the IPv4 DirPort, but
  1334. # typically only use the IPv6 ORPort)
  1335. # if there is no IPv6 address, only the IPv4 address is checked
  1336. # return the number of candidates we excluded
  1337. def limit_fallbacks_same_ip(self):
  1338. ip_limit_fallbacks = []
  1339. ip_list = []
  1340. for f in self.fallbacks:
  1341. if (CandidateList.allow(f.dirip, ip_list)
  1342. and CandidateList.allow(f.ipv6addr, ip_list)):
  1343. ip_limit_fallbacks.append(f)
  1344. ip_list.append(f.dirip)
  1345. if f.has_ipv6():
  1346. ip_list.append(f.ipv6addr)
  1347. elif not CandidateList.allow(f.dirip, ip_list):
  1348. logging.info('Eliminated %s: already have fallback on IPv4 %s'%(
  1349. f._fpr, f.dirip))
  1350. elif f.has_ipv6() and not CandidateList.allow(f.ipv6addr, ip_list):
  1351. logging.info('Eliminated %s: already have fallback on IPv6 %s'%(
  1352. f._fpr, f.ipv6addr))
  1353. original_count = len(self.fallbacks)
  1354. self.fallbacks = ip_limit_fallbacks
  1355. return original_count - len(self.fallbacks)
  1356. # make sure there is only one fallback per ContactInfo
  1357. # if there is no ContactInfo, allow the fallback
  1358. # this check can be gamed by providing no ContactInfo, or by setting the
  1359. # ContactInfo to match another fallback
  1360. # However, given the likelihood that relays with the same ContactInfo will
  1361. # go down at similar times, its usefulness outweighs the risk
  1362. def limit_fallbacks_same_contact(self):
  1363. contact_limit_fallbacks = []
  1364. contact_list = []
  1365. for f in self.fallbacks:
  1366. if CandidateList.allow(f._data['contact'], contact_list):
  1367. contact_limit_fallbacks.append(f)
  1368. contact_list.append(f._data['contact'])
  1369. else:
  1370. logging.info(('Eliminated %s: already have fallback on ' +
  1371. 'ContactInfo %s')%(f._fpr, f._data['contact']))
  1372. original_count = len(self.fallbacks)
  1373. self.fallbacks = contact_limit_fallbacks
  1374. return original_count - len(self.fallbacks)
  1375. # make sure there is only one fallback per effective family
  1376. # if there is no family, allow the fallback
  1377. # this check can't be gamed, because we use effective family, which ensures
  1378. # mutual family declarations
  1379. # if any indirect families exist, the result depends on the order in which
  1380. # fallbacks are sorted in the list
  1381. def limit_fallbacks_same_family(self):
  1382. family_limit_fallbacks = []
  1383. fingerprint_list = []
  1384. for f in self.fallbacks:
  1385. if CandidateList.allow(f._fpr, fingerprint_list):
  1386. family_limit_fallbacks.append(f)
  1387. fingerprint_list.append(f._fpr)
  1388. fingerprint_list.extend(f._data['effective_family'])
  1389. else:
  1390. # technically, we already have a fallback with this fallback in its
  1391. # effective family
  1392. logging.info('Eliminated %s: already have fallback in effective ' +
  1393. 'family'%(f._fpr))
  1394. original_count = len(self.fallbacks)
  1395. self.fallbacks = family_limit_fallbacks
  1396. return original_count - len(self.fallbacks)
  1397. # try a download check on each fallback candidate in order
  1398. # stop after max_count successful downloads
  1399. # but don't remove any candidates from the array
  1400. def try_download_consensus_checks(self, max_count):
  1401. dl_ok_count = 0
  1402. for f in self.fallbacks:
  1403. f.try_fallback_download_consensus()
  1404. if f.get_fallback_download_consensus():
  1405. # this fallback downloaded a consensus ok
  1406. dl_ok_count += 1
  1407. if dl_ok_count >= max_count:
  1408. # we have enough fallbacks
  1409. return
  1410. # put max_count successful candidates in the fallbacks array:
  1411. # - perform download checks on each fallback candidate
  1412. # - retry failed candidates if CONSENSUS_DOWNLOAD_RETRY is set
  1413. # - eliminate failed candidates
  1414. # - if there are more than max_count candidates, eliminate lowest bandwidth
  1415. # - if there are fewer than max_count candidates, leave only successful
  1416. # Return the number of fallbacks that failed the consensus check
  1417. def perform_download_consensus_checks(self, max_count):
  1418. self.sort_fallbacks_by_measured_bandwidth()
  1419. self.try_download_consensus_checks(max_count)
  1420. if CONSENSUS_DOWNLOAD_RETRY:
  1421. # try unsuccessful candidates again
  1422. # we could end up with more than max_count successful candidates here
  1423. self.try_download_consensus_checks(max_count)
  1424. # now we have at least max_count successful candidates,
  1425. # or we've tried them all
  1426. original_count = len(self.fallbacks)
  1427. self.fallbacks = filter(lambda x: x.get_fallback_download_consensus(),
  1428. self.fallbacks)
  1429. # some of these failed the check, others skipped the check,
  1430. # if we already had enough successful downloads
  1431. failed_count = original_count - len(self.fallbacks)
  1432. self.fallbacks = self.fallbacks[:max_count]
  1433. return failed_count
  1434. # return a string that describes a/b as a percentage
  1435. @staticmethod
  1436. def describe_percentage(a, b):
  1437. if b != 0:
  1438. return '%d/%d = %.0f%%'%(a, b, (a*100.0)/b)
  1439. else:
  1440. # technically, 0/0 is undefined, but 0.0% is a sensible result
  1441. return '%d/%d = %.0f%%'%(a, b, 0.0)
  1442. # return a dictionary of lists of fallbacks by IPv4 netblock
  1443. # the dictionary is keyed by the fingerprint of an arbitrary fallback
  1444. # in each netblock
  1445. # mask_bits is the size of the netblock
  1446. def fallbacks_by_ipv4_netblock(self, mask_bits):
  1447. netblocks = {}
  1448. for f in self.fallbacks:
  1449. found_netblock = False
  1450. for b in netblocks.keys():
  1451. # we found an existing netblock containing this fallback
  1452. if f.ipv4_netblocks_equal(self[b], mask_bits):
  1453. # add it to the list
  1454. netblocks[b].append(f)
  1455. found_netblock = True
  1456. break
  1457. # make a new netblock based on this fallback's fingerprint
  1458. if not found_netblock:
  1459. netblocks[f._fpr] = [f]
  1460. return netblocks
  1461. # return a dictionary of lists of fallbacks by IPv6 netblock
  1462. # where mask_bits is the size of the netblock
  1463. def fallbacks_by_ipv6_netblock(self, mask_bits):
  1464. netblocks = {}
  1465. for f in self.fallbacks:
  1466. # skip fallbacks without IPv6 addresses
  1467. if not f.has_ipv6():
  1468. continue
  1469. found_netblock = False
  1470. for b in netblocks.keys():
  1471. # we found an existing netblock containing this fallback
  1472. if f.ipv6_netblocks_equal(self[b], mask_bits):
  1473. # add it to the list
  1474. netblocks[b].append(f)
  1475. found_netblock = True
  1476. break
  1477. # make a new netblock based on this fallback's fingerprint
  1478. if not found_netblock:
  1479. netblocks[f._fpr] = [f]
  1480. return netblocks
  1481. # log a message about the proportion of fallbacks in each IPv4 netblock,
  1482. # where mask_bits is the size of the netblock
  1483. def describe_fallback_ipv4_netblock_mask(self, mask_bits):
  1484. fallback_count = len(self.fallbacks)
  1485. shared_netblock_fallback_count = 0
  1486. most_frequent_netblock = None
  1487. netblocks = self.fallbacks_by_ipv4_netblock(mask_bits)
  1488. for b in netblocks.keys():
  1489. if len(netblocks[b]) > 1:
  1490. # how many fallbacks are in a netblock with other fallbacks?
  1491. shared_netblock_fallback_count += len(netblocks[b])
  1492. # what's the netblock with the most fallbacks?
  1493. if (most_frequent_netblock is None
  1494. or len(netblocks[b]) > len(netblocks[most_frequent_netblock])):
  1495. most_frequent_netblock = b
  1496. logging.debug('Fallback IPv4 addresses in the same /%d:'%(mask_bits))
  1497. for f in netblocks[b]:
  1498. logging.debug('%s - %s', f.dirip, f._fpr)
  1499. if most_frequent_netblock is not None:
  1500. logging.warning('There are %s fallbacks in the IPv4 /%d containing %s'%(
  1501. CandidateList.describe_percentage(
  1502. len(netblocks[most_frequent_netblock]),
  1503. fallback_count),
  1504. mask_bits,
  1505. self[most_frequent_netblock].dirip))
  1506. if shared_netblock_fallback_count > 0:
  1507. logging.warning(('%s of fallbacks are in an IPv4 /%d with other ' +
  1508. 'fallbacks')%(CandidateList.describe_percentage(
  1509. shared_netblock_fallback_count,
  1510. fallback_count),
  1511. mask_bits))
  1512. # log a message about the proportion of fallbacks in each IPv6 netblock,
  1513. # where mask_bits is the size of the netblock
  1514. def describe_fallback_ipv6_netblock_mask(self, mask_bits):
  1515. fallback_count = len(self.fallbacks_with_ipv6())
  1516. shared_netblock_fallback_count = 0
  1517. most_frequent_netblock = None
  1518. netblocks = self.fallbacks_by_ipv6_netblock(mask_bits)
  1519. for b in netblocks.keys():
  1520. if len(netblocks[b]) > 1:
  1521. # how many fallbacks are in a netblock with other fallbacks?
  1522. shared_netblock_fallback_count += len(netblocks[b])
  1523. # what's the netblock with the most fallbacks?
  1524. if (most_frequent_netblock is None
  1525. or len(netblocks[b]) > len(netblocks[most_frequent_netblock])):
  1526. most_frequent_netblock = b
  1527. logging.debug('Fallback IPv6 addresses in the same /%d:'%(mask_bits))
  1528. for f in netblocks[b]:
  1529. logging.debug('%s - %s', f.ipv6addr, f._fpr)
  1530. if most_frequent_netblock is not None:
  1531. logging.warning('There are %s fallbacks in the IPv6 /%d containing %s'%(
  1532. CandidateList.describe_percentage(
  1533. len(netblocks[most_frequent_netblock]),
  1534. fallback_count),
  1535. mask_bits,
  1536. self[most_frequent_netblock].ipv6addr))
  1537. if shared_netblock_fallback_count > 0:
  1538. logging.warning(('%s of fallbacks are in an IPv6 /%d with other ' +
  1539. 'fallbacks')%(CandidateList.describe_percentage(
  1540. shared_netblock_fallback_count,
  1541. fallback_count),
  1542. mask_bits))
  1543. # log a message about the proportion of fallbacks in each IPv4 /8, /16,
  1544. # and /24
  1545. def describe_fallback_ipv4_netblocks(self):
  1546. # this doesn't actually tell us anything useful
  1547. #self.describe_fallback_ipv4_netblock_mask(8)
  1548. self.describe_fallback_ipv4_netblock_mask(16)
  1549. self.describe_fallback_ipv4_netblock_mask(24)
  1550. # log a message about the proportion of fallbacks in each IPv6 /12 (RIR),
  1551. # /23 (smaller RIR blocks), /32 (LIR), /48 (Customer), and /64 (Host)
  1552. # https://www.iana.org/assignments/ipv6-unicast-address-assignments/
  1553. def describe_fallback_ipv6_netblocks(self):
  1554. # these don't actually tell us anything useful
  1555. #self.describe_fallback_ipv6_netblock_mask(12)
  1556. #self.describe_fallback_ipv6_netblock_mask(23)
  1557. self.describe_fallback_ipv6_netblock_mask(32)
  1558. self.describe_fallback_ipv6_netblock_mask(48)
  1559. self.describe_fallback_ipv6_netblock_mask(64)
  1560. # log a message about the proportion of fallbacks in each IPv4 and IPv6
  1561. # netblock
  1562. def describe_fallback_netblocks(self):
  1563. self.describe_fallback_ipv4_netblocks()
  1564. self.describe_fallback_ipv6_netblocks()
  1565. # return a list of fallbacks which are on the IPv4 ORPort port
  1566. def fallbacks_on_ipv4_orport(self, port):
  1567. return filter(lambda x: x.orport == port, self.fallbacks)
  1568. # return a list of fallbacks which are on the IPv6 ORPort port
  1569. def fallbacks_on_ipv6_orport(self, port):
  1570. return filter(lambda x: x.ipv6orport == port, self.fallbacks_with_ipv6())
  1571. # return a list of fallbacks which are on the DirPort port
  1572. def fallbacks_on_dirport(self, port):
  1573. return filter(lambda x: x.dirport == port, self.fallbacks)
  1574. # log a message about the proportion of fallbacks on IPv4 ORPort port
  1575. # and return that count
  1576. def describe_fallback_ipv4_orport(self, port):
  1577. port_count = len(self.fallbacks_on_ipv4_orport(port))
  1578. fallback_count = len(self.fallbacks)
  1579. logging.warning('%s of fallbacks are on IPv4 ORPort %d'%(
  1580. CandidateList.describe_percentage(port_count,
  1581. fallback_count),
  1582. port))
  1583. return port_count
  1584. # log a message about the proportion of IPv6 fallbacks on IPv6 ORPort port
  1585. # and return that count
  1586. def describe_fallback_ipv6_orport(self, port):
  1587. port_count = len(self.fallbacks_on_ipv6_orport(port))
  1588. fallback_count = len(self.fallbacks_with_ipv6())
  1589. logging.warning('%s of IPv6 fallbacks are on IPv6 ORPort %d'%(
  1590. CandidateList.describe_percentage(port_count,
  1591. fallback_count),
  1592. port))
  1593. return port_count
  1594. # log a message about the proportion of fallbacks on DirPort port
  1595. # and return that count
  1596. def describe_fallback_dirport(self, port):
  1597. port_count = len(self.fallbacks_on_dirport(port))
  1598. fallback_count = len(self.fallbacks)
  1599. logging.warning('%s of fallbacks are on DirPort %d'%(
  1600. CandidateList.describe_percentage(port_count,
  1601. fallback_count),
  1602. port))
  1603. return port_count
  1604. # log a message about the proportion of fallbacks on each dirport,
  1605. # each IPv4 orport, and each IPv6 orport
  1606. def describe_fallback_ports(self):
  1607. fallback_count = len(self.fallbacks)
  1608. ipv4_or_count = fallback_count
  1609. ipv4_or_count -= self.describe_fallback_ipv4_orport(443)
  1610. ipv4_or_count -= self.describe_fallback_ipv4_orport(9001)
  1611. logging.warning('%s of fallbacks are on other IPv4 ORPorts'%(
  1612. CandidateList.describe_percentage(ipv4_or_count,
  1613. fallback_count)))
  1614. ipv6_fallback_count = len(self.fallbacks_with_ipv6())
  1615. ipv6_or_count = ipv6_fallback_count
  1616. ipv6_or_count -= self.describe_fallback_ipv6_orport(443)
  1617. ipv6_or_count -= self.describe_fallback_ipv6_orport(9001)
  1618. logging.warning('%s of IPv6 fallbacks are on other IPv6 ORPorts'%(
  1619. CandidateList.describe_percentage(ipv6_or_count,
  1620. ipv6_fallback_count)))
  1621. dir_count = fallback_count
  1622. dir_count -= self.describe_fallback_dirport(80)
  1623. dir_count -= self.describe_fallback_dirport(9030)
  1624. logging.warning('%s of fallbacks are on other DirPorts'%(
  1625. CandidateList.describe_percentage(dir_count,
  1626. fallback_count)))
  1627. # return a list of fallbacks which have the Exit flag
  1628. def fallbacks_with_exit(self):
  1629. return filter(lambda x: x.is_exit(), self.fallbacks)
  1630. # log a message about the proportion of fallbacks with an Exit flag
  1631. def describe_fallback_exit_flag(self):
  1632. exit_falback_count = len(self.fallbacks_with_exit())
  1633. fallback_count = len(self.fallbacks)
  1634. logging.warning('%s of fallbacks have the Exit flag'%(
  1635. CandidateList.describe_percentage(exit_falback_count,
  1636. fallback_count)))
  1637. # return a list of fallbacks which have an IPv6 address
  1638. def fallbacks_with_ipv6(self):
  1639. return filter(lambda x: x.has_ipv6(), self.fallbacks)
  1640. # log a message about the proportion of fallbacks on IPv6
  1641. def describe_fallback_ip_family(self):
  1642. ipv6_falback_count = len(self.fallbacks_with_ipv6())
  1643. fallback_count = len(self.fallbacks)
  1644. logging.warning('%s of fallbacks are on IPv6'%(
  1645. CandidateList.describe_percentage(ipv6_falback_count,
  1646. fallback_count)))
  1647. def summarise_fallbacks(self, eligible_count, operator_count, failed_count,
  1648. guard_count, target_count):
  1649. s = ''
  1650. s += '/* To comment-out entries in this file, use C comments, and add *'
  1651. s += ' to the start of each line. (stem finds fallback entries using "'
  1652. s += ' at the start of a line.) */'
  1653. s += '\n'
  1654. # Report:
  1655. # whether we checked consensus download times
  1656. # the number of fallback directories (and limits/exclusions, if relevant)
  1657. # min & max fallback bandwidths
  1658. # #error if below minimum count
  1659. if PERFORM_IPV4_DIRPORT_CHECKS or PERFORM_IPV6_DIRPORT_CHECKS:
  1660. s += '/* Checked %s%s%s DirPorts served a consensus within %.1fs. */'%(
  1661. 'IPv4' if PERFORM_IPV4_DIRPORT_CHECKS else '',
  1662. ' and ' if (PERFORM_IPV4_DIRPORT_CHECKS
  1663. and PERFORM_IPV6_DIRPORT_CHECKS) else '',
  1664. 'IPv6' if PERFORM_IPV6_DIRPORT_CHECKS else '',
  1665. CONSENSUS_DOWNLOAD_SPEED_MAX)
  1666. else:
  1667. s += '/* Did not check IPv4 or IPv6 DirPort consensus downloads. */'
  1668. s += '\n'
  1669. # Multiline C comment with #error if things go bad
  1670. s += '/*'
  1671. s += '\n'
  1672. # Integers don't need escaping in C comments
  1673. fallback_count = len(self.fallbacks)
  1674. if FALLBACK_PROPORTION_OF_GUARDS is None:
  1675. fallback_proportion = ''
  1676. else:
  1677. fallback_proportion = ', Target %d (%d * %.2f)'%(target_count,
  1678. guard_count,
  1679. FALLBACK_PROPORTION_OF_GUARDS)
  1680. s += 'Final Count: %d (Eligible %d%s'%(fallback_count, eligible_count,
  1681. fallback_proportion)
  1682. if MAX_FALLBACK_COUNT is not None:
  1683. s += ', Max %d'%(MAX_FALLBACK_COUNT)
  1684. s += ')\n'
  1685. if eligible_count != fallback_count:
  1686. removed_count = eligible_count - fallback_count
  1687. excess_to_target_or_max = (eligible_count - operator_count - failed_count
  1688. - fallback_count)
  1689. # some 'Failed' failed the check, others 'Skipped' the check,
  1690. # if we already had enough successful downloads
  1691. s += ('Excluded: %d (Same Operator %d, Failed/Skipped Download %d, ' +
  1692. 'Excess %d)')%(removed_count, operator_count, failed_count,
  1693. excess_to_target_or_max)
  1694. s += '\n'
  1695. min_fb = self.fallback_min()
  1696. min_bw = min_fb._data['measured_bandwidth']
  1697. max_fb = self.fallback_max()
  1698. max_bw = max_fb._data['measured_bandwidth']
  1699. s += 'Bandwidth Range: %.1f - %.1f MByte/s'%(min_bw/(1024.0*1024.0),
  1700. max_bw/(1024.0*1024.0))
  1701. s += '\n'
  1702. s += '*/'
  1703. if fallback_count < MIN_FALLBACK_COUNT:
  1704. # We must have a minimum number of fallbacks so they are always
  1705. # reachable, and are in diverse locations
  1706. s += '\n'
  1707. s += '#error Fallback Count %d is too low. '%(fallback_count)
  1708. s += 'Must be at least %d for diversity. '%(MIN_FALLBACK_COUNT)
  1709. s += 'Try adding entries to the whitelist, '
  1710. s += 'or setting INCLUDE_UNLISTED_ENTRIES = True.'
  1711. return s
  1712. ## Main Function
  1713. def list_fallbacks():
  1714. """ Fetches required onionoo documents and evaluates the
  1715. fallback directory criteria for each of the relays """
  1716. logging.warning('Downloading and parsing Onionoo data. ' +
  1717. 'This may take some time.')
  1718. # find relays that could be fallbacks
  1719. candidates = CandidateList()
  1720. candidates.add_relays()
  1721. # work out how many fallbacks we want
  1722. guard_count = candidates.count_guards()
  1723. if FALLBACK_PROPORTION_OF_GUARDS is None:
  1724. target_count = guard_count
  1725. else:
  1726. target_count = int(guard_count * FALLBACK_PROPORTION_OF_GUARDS)
  1727. # the maximum number of fallbacks is the least of:
  1728. # - the target fallback count (FALLBACK_PROPORTION_OF_GUARDS * guard count)
  1729. # - the maximum fallback count (MAX_FALLBACK_COUNT)
  1730. if MAX_FALLBACK_COUNT is None:
  1731. max_count = target_count
  1732. else:
  1733. max_count = min(target_count, MAX_FALLBACK_COUNT)
  1734. candidates.compute_fallbacks()
  1735. prefilter_fallbacks = copy.copy(candidates.fallbacks)
  1736. # filter with the whitelist and blacklist
  1737. # if a relay has changed IPv4 address or ports recently, it will be excluded
  1738. # as ineligible before we call apply_filter_lists, and so there will be no
  1739. # warning that the details have changed from those in the whitelist.
  1740. # instead, there will be an info-level log during the eligibility check.
  1741. initial_count = len(candidates.fallbacks)
  1742. excluded_count = candidates.apply_filter_lists()
  1743. print candidates.summarise_filters(initial_count, excluded_count)
  1744. eligible_count = len(candidates.fallbacks)
  1745. # calculate the measured bandwidth of each relay,
  1746. # then remove low-bandwidth relays
  1747. candidates.calculate_measured_bandwidth()
  1748. candidates.remove_low_bandwidth_relays()
  1749. # print the raw fallback list
  1750. #for x in candidates.fallbacks:
  1751. # print x.fallbackdir_line(True)
  1752. # print json.dumps(candidates[x]._data, sort_keys=True, indent=4,
  1753. # separators=(',', ': '), default=json_util.default)
  1754. # impose mandatory conditions here, like one per contact, family, IP
  1755. # in measured bandwidth order
  1756. candidates.sort_fallbacks_by_measured_bandwidth()
  1757. operator_count = 0
  1758. # only impose these limits on the final list - operators can nominate
  1759. # multiple candidate fallbacks, and then we choose the best set
  1760. if not OUTPUT_CANDIDATES:
  1761. operator_count += candidates.limit_fallbacks_same_ip()
  1762. operator_count += candidates.limit_fallbacks_same_contact()
  1763. operator_count += candidates.limit_fallbacks_same_family()
  1764. # check if each candidate can serve a consensus
  1765. # there's a small risk we've eliminated relays from the same operator that
  1766. # can serve a consensus, in favour of one that can't
  1767. # but given it takes up to 15 seconds to check each consensus download,
  1768. # the risk is worth it
  1769. if PERFORM_IPV4_DIRPORT_CHECKS or PERFORM_IPV6_DIRPORT_CHECKS:
  1770. logging.warning('Checking consensus download speeds. ' +
  1771. 'This may take some time.')
  1772. failed_count = candidates.perform_download_consensus_checks(max_count)
  1773. # analyse and log interesting diversity metrics
  1774. # like netblock, ports, exit, IPv4-only
  1775. # (we can't easily analyse AS, and it's hard to accurately analyse country)
  1776. candidates.describe_fallback_ip_family()
  1777. # if we can't import the ipaddress module, we can't do netblock analysis
  1778. if HAVE_IPADDRESS:
  1779. candidates.describe_fallback_netblocks()
  1780. candidates.describe_fallback_ports()
  1781. candidates.describe_fallback_exit_flag()
  1782. # output C comments summarising the fallback selection process
  1783. if len(candidates.fallbacks) > 0:
  1784. print candidates.summarise_fallbacks(eligible_count, operator_count,
  1785. failed_count, guard_count,
  1786. target_count)
  1787. else:
  1788. print '/* No Fallbacks met criteria */'
  1789. # output C comments specifying the OnionOO data used to create the list
  1790. for s in fetch_source_list():
  1791. print describe_fetch_source(s)
  1792. # sort the list differently depending on why we've created it:
  1793. # if we're outputting the final fallback list, sort by fingerprint
  1794. # this makes diffs much more stable
  1795. # otherwise, if we're trying to find a bandwidth cutoff, or we want to
  1796. # contact operators in priority order, sort by bandwidth (not yet
  1797. # implemented)
  1798. # otherwise, if we're contacting operators, sort by contact
  1799. candidates.sort_fallbacks_by(OUTPUT_SORT_FIELD)
  1800. for x in candidates.fallbacks:
  1801. print x.fallbackdir_line(candidates.fallbacks, prefilter_fallbacks)
  1802. if __name__ == "__main__":
  1803. list_fallbacks()