updateFallbackDirs.py 88 KB

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