updateFallbackDirs.py 94 KB

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