updateFallbackDirs.py 82 KB

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