updateFallbackDirs.py 93 KB

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