updateFallbackDirs.py 93 KB

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