updateFallbackDirs.py 83 KB

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