updateFallbackDirs.py 88 KB

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