updateFallbackDirs.py 88 KB

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