updateFallbackDirs.py 88 KB

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