updateFallbackDirs.py 80 KB

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