updateFallbackDirs.py 89 KB

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