updateFallbackDirs.py 89 KB

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