updateFallbackDirs.py 93 KB

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