updateFallbackDirs.py 83 KB

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