updateFallbackDirs.py 86 KB

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