updateFallbackDirs.py 86 KB

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