updateFallbackDirs.py 87 KB

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