updateFallbackDirs.py 88 KB

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