updateFallbackDirs.py 78 KB

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