TorNet.py 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. # Copyright 2013 The Tor Project
  5. #
  6. # You may do anything with this work that copyright law would normally
  7. # restrict, so long as you retain the above notice(s) and this license
  8. # in all redistributed copies and derived works. There is no warranty.
  9. from __future__ import print_function
  10. from __future__ import with_statement
  11. import cgitb
  12. import errno
  13. import importlib
  14. import os
  15. import platform
  16. import re
  17. import signal
  18. import shutil
  19. import subprocess
  20. import sys
  21. import time
  22. from chutney.Debug import debug_flag, debug
  23. import chutney.Host
  24. import chutney.Templating
  25. import chutney.Traffic
  26. import chutney.Util
  27. _BASE_ENVIRON = None
  28. _TOR_VERSIONS = None
  29. _TORRC_OPTIONS = None
  30. _THE_NETWORK = None
  31. TORRC_OPTION_WARN_LIMIT = 10
  32. torrc_option_warn_count = 0
  33. # Get verbose tracebacks, so we can diagnose better.
  34. cgitb.enable(format="plain")
  35. class MissingBinaryException(Exception):
  36. pass
  37. def getenv_type(env_var, default, type_, type_name=None):
  38. """
  39. Return the value of the environment variable 'envar' as type_,
  40. or 'default' if no such variable exists.
  41. Raise ValueError using type_name if the environment variable is set,
  42. but type_() raises a ValueError on its value. (If type_name is None
  43. or empty, the ValueError uses type_'s string representation instead.)
  44. """
  45. strval = os.environ.get(env_var)
  46. if strval is None:
  47. return default
  48. try:
  49. return type_(strval)
  50. except ValueError:
  51. if not type_name:
  52. type_name = str(type_)
  53. raise ValueError(("Invalid value for environment variable '{}': "
  54. "expected {}, but got '{}'")
  55. .format(env_var, typename, strval))
  56. def getenv_int(env_var, default):
  57. """
  58. Return the value of the environment variable 'envar' as an int,
  59. or 'default' if no such variable exists.
  60. Raise ValueError if the environment variable is set, but is not an int.
  61. """
  62. return getenv_type(env_var, default, int, type_name='an int')
  63. def getenv_bool(env_var, default):
  64. """
  65. Return the value of the environment variable 'envar' as a bool,
  66. or 'default' if no such variable exists.
  67. Unlike bool(), converts 0, "False", and "No" to False.
  68. Raise ValueError if the environment variable is set, but is not a bool.
  69. """
  70. try:
  71. # Handle integer values
  72. return bool(getenv_int(env_var, default))
  73. except ValueError:
  74. # Handle values that the user probably expects to be False
  75. strval = os.environ.get(env_var)
  76. if strval.lower() in ['false', 'no']:
  77. return False
  78. else:
  79. return getenv_type(env_var, default, bool, type_name='a bool')
  80. def mkdir_p(d, mode=448):
  81. """Create directory 'd' and all of its parents as needed. Unlike
  82. os.makedirs, does not give an error if d already exists.
  83. 448 is the decimal representation of the octal number 0700. Since
  84. python2 only supports 0700 and python3 only supports 0o700, we can use
  85. neither.
  86. Note that python2 and python3 differ in how they create the
  87. permissions for the intermediate directories. In python3, 'mode'
  88. only sets the mode for the last directory created.
  89. """
  90. try:
  91. os.makedirs(d, mode=mode)
  92. except OSError as e:
  93. if e.errno == errno.EEXIST:
  94. return
  95. raise
  96. def make_datadir_subdirectory(datadir, subdir):
  97. """
  98. Create a datadirectory (if necessary) and a subdirectory of
  99. that datadirectory. Ensure that both are mode 700.
  100. """
  101. mkdir_p(datadir)
  102. mkdir_p(os.path.join(datadir, subdir))
  103. def get_absolute_chutney_path():
  104. # use the current directory as the default
  105. # (./chutney already sets CHUTNEY_PATH using the path to the script)
  106. # use tools/test-network.sh if you want chutney to try really hard to find
  107. # itself
  108. relative_chutney_path = os.environ.get('CHUTNEY_PATH', os.getcwd())
  109. return os.path.abspath(relative_chutney_path)
  110. def get_absolute_net_path():
  111. # use the chutney path as the default
  112. absolute_chutney_path = get_absolute_chutney_path()
  113. relative_net_path = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  114. # but what is it relative to?
  115. # let's check if it's in CHUTNEY_PATH first, to preserve
  116. # backwards-compatible behaviour
  117. chutney_net_path = os.path.join(absolute_chutney_path, relative_net_path)
  118. if os.path.isdir(chutney_net_path):
  119. return chutney_net_path
  120. # ok, it's relative to the current directory, whatever that is
  121. return os.path.abspath(relative_net_path)
  122. def get_absolute_nodes_path():
  123. # there's no way to customise this: we really don't need more options
  124. return os.path.join(get_absolute_net_path(), 'nodes')
  125. def get_new_absolute_nodes_path(now=time.time()):
  126. # automatically chosen to prevent path collisions, and result in an ordered
  127. # series of directory path names
  128. # should only be called by 'chutney configure', all other chutney commands
  129. # should use get_absolute_nodes_path()
  130. nodesdir = get_absolute_nodes_path()
  131. newdir = newdirbase = "%s.%d" % (nodesdir, now)
  132. # if the time is the same, fall back to a simple integer count
  133. # (this is very unlikely to happen unless the clock changes: it's not
  134. # possible to run multiple chutney networks at the same time)
  135. i = 0
  136. while os.path.exists(newdir):
  137. i += 1
  138. newdir = "%s.%d" % (newdirbase, i)
  139. return newdir
  140. def _warnMissingTor(tor_path, cmdline, tor_name="tor"):
  141. """Log a warning that the binary tor_name can't be found at tor_path
  142. while running cmdline.
  143. """
  144. print(("Cannot find the {} binary at '{}' for the command line '{}'. " +
  145. "Set the TOR_DIR environment variable to the directory " +
  146. "containing {}.")
  147. .format(tor_name, tor_path, " ".join(cmdline), tor_name))
  148. def run_tor(cmdline, exit_on_missing=True):
  149. """Run the tor command line cmdline, which must start with the path or
  150. name of a tor binary.
  151. Returns the combined stdout and stderr of the process.
  152. If exit_on_missing is true, warn and exit if the tor binary is missing.
  153. Otherwise, raise a MissingBinaryException.
  154. """
  155. if not debug_flag:
  156. cmdline.append("--quiet")
  157. try:
  158. stdouterr = subprocess.check_output(cmdline,
  159. stderr=subprocess.STDOUT,
  160. universal_newlines=True,
  161. bufsize=-1)
  162. debug(stdouterr)
  163. except OSError as e:
  164. # only catch file not found error
  165. if e.errno == errno.ENOENT:
  166. if exit_on_missing:
  167. _warnMissingTor(cmdline[0], cmdline)
  168. sys.exit(1)
  169. else:
  170. raise MissingBinaryException()
  171. else:
  172. raise
  173. except subprocess.CalledProcessError as e:
  174. # only catch file not found error
  175. if e.returncode == 127:
  176. if exit_on_missing:
  177. _warnMissingTor(cmdline[0], cmdline)
  178. sys.exit(1)
  179. else:
  180. raise MissingBinaryException()
  181. else:
  182. raise
  183. return stdouterr
  184. def launch_process(cmdline, tor_name="tor", stdin=None, exit_on_missing=True):
  185. """Launch the command line cmdline, which must start with the path or
  186. name of a binary. Use tor_name as the canonical name of the binary.
  187. Pass stdin to the Popen constructor.
  188. Returns the Popen object for the launched process.
  189. """
  190. if tor_name == "tor" and not debug_flag:
  191. cmdline.append("--quiet")
  192. elif tor_name == "tor-gencert" and debug_flag:
  193. cmdline.append("-v")
  194. try:
  195. p = subprocess.Popen(cmdline,
  196. stdin=stdin,
  197. stdout=subprocess.PIPE,
  198. stderr=subprocess.STDOUT,
  199. universal_newlines=True,
  200. bufsize=-1)
  201. except OSError as e:
  202. # only catch file not found error
  203. if e.errno == errno.ENOENT:
  204. if exit_on_missing:
  205. _warnMissingTor(cmdline[0], cmdline, tor_name=tor_name)
  206. sys.exit(1)
  207. else:
  208. raise MissingBinaryException()
  209. else:
  210. raise
  211. return p
  212. def run_tor_gencert(cmdline, passphrase):
  213. """Run the tor-gencert command line cmdline, which must start with the
  214. path or name of a tor-gencert binary.
  215. Then send passphrase to the stdin of the process.
  216. Returns the combined stdout and stderr of the process.
  217. """
  218. p = launch_process(cmdline,
  219. tor_name="tor-gencert",
  220. stdin=subprocess.PIPE)
  221. (stdouterr, empty_stderr) = p.communicate(passphrase + "\n")
  222. debug(stdouterr)
  223. assert p.returncode == 0 # XXXX BAD!
  224. assert empty_stderr is None
  225. return stdouterr
  226. @chutney.Util.memoized
  227. def tor_exists(tor):
  228. """Return true iff this tor binary exists."""
  229. try:
  230. run_tor([tor, "--quiet", "--version"], exit_on_missing=False)
  231. return True
  232. except MissingBinaryException:
  233. return False
  234. @chutney.Util.memoized
  235. def tor_gencert_exists(gencert):
  236. """Return true iff this tor-gencert binary exists."""
  237. try:
  238. p = launch_process([gencert, "--help"], exit_on_missing=False)
  239. p.wait()
  240. return True
  241. except MissingBinaryException:
  242. return False
  243. @chutney.Util.memoized
  244. def get_tor_version(tor):
  245. """Return the version of the tor binary.
  246. Versions are cached for each unique tor path.
  247. """
  248. cmdline = [
  249. tor,
  250. "--version",
  251. ]
  252. tor_version = run_tor(cmdline)
  253. # clean it up a bit
  254. tor_version = tor_version.strip()
  255. tor_version = tor_version.replace("version ", "")
  256. tor_version = tor_version.replace(").", ")")
  257. # check we received a tor version, and nothing else
  258. assert re.match(r'^[-+.() A-Za-z0-9]+$', tor_version)
  259. return tor_version
  260. @chutney.Util.memoized
  261. def get_torrc_options(tor):
  262. """Return the torrc options supported by the tor binary.
  263. Options are cached for each unique tor path.
  264. """
  265. cmdline = [
  266. tor,
  267. "--list-torrc-options",
  268. ]
  269. opts = run_tor(cmdline)
  270. # check we received a list of options, and nothing else
  271. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  272. torrc_opts = opts.split()
  273. return torrc_opts
  274. @chutney.Util.memoized
  275. def get_tor_modules(tor):
  276. """Check the list of compile-time modules advertised by the given
  277. 'tor' binary, and return a map from module name to a boolean
  278. describing whether it is supported.
  279. Unlisted modules are ones that Tor did not treat as compile-time
  280. optional modules.
  281. """
  282. cmdline = [
  283. tor,
  284. "--list-modules",
  285. "--quiet"
  286. ]
  287. try:
  288. mods = run_tor(cmdline)
  289. except subprocess.CalledProcessError as e:
  290. # Tor doesn't support --list-modules; act as if it said nothing.
  291. mods = ""
  292. supported = {}
  293. for line in mods.split("\n"):
  294. m = re.match(r'^(\S+): (yes|no)', line)
  295. if not m:
  296. continue
  297. supported[m.group(1)] = (m.group(2) == "yes")
  298. return supported
  299. def tor_has_module(tor, modname, default=True):
  300. """Return true iff the given tor binary supports a given compile-time
  301. module. If the module is not listed, return 'default'.
  302. """
  303. return get_tor_modules(tor).get(modname, default)
  304. class Node(object):
  305. """A Node represents a Tor node or a set of Tor nodes. It's created
  306. in a network configuration file.
  307. This class is responsible for holding the user's selected node
  308. configuration, and figuring out how the node needs to be
  309. configured and launched.
  310. """
  311. # Fields:
  312. # _parent
  313. # _env
  314. # _builder
  315. # _controller
  316. ########
  317. # Users are expected to call these:
  318. def __init__(self, parent=None, **kwargs):
  319. self._parent = parent
  320. self._env = self._createEnviron(parent, kwargs)
  321. self._builder = None
  322. self._controller = None
  323. def getN(self, N):
  324. return [Node(self) for _ in range(N)]
  325. def specialize(self, **kwargs):
  326. return Node(parent=self, **kwargs)
  327. def set_runtime(self, key, fn):
  328. """Specify a runtime function that gets invoked to find the
  329. runtime value of a key. It should take a single argument, which
  330. will be an environment.
  331. """
  332. setattr(self._env, "_get_"+key, fn)
  333. ######
  334. # Chutney uses these:
  335. def getBuilder(self):
  336. """Return a NodeBuilder instance to set up this node (that is, to
  337. write all the files that need to be in place so that this
  338. node can be run by a NodeController).
  339. """
  340. if self._builder is None:
  341. self._builder = LocalNodeBuilder(self._env)
  342. return self._builder
  343. def getController(self):
  344. """Return a NodeController instance to control this node (that is,
  345. to start it, stop it, see if it's running, etc.)
  346. """
  347. if self._controller is None:
  348. self._controller = LocalNodeController(self._env)
  349. return self._controller
  350. def setNodenum(self, num):
  351. """Assign a value to the 'nodenum' element of this node. Each node
  352. in a network gets its own nodenum.
  353. """
  354. self._env['nodenum'] = num
  355. #####
  356. # These are internal:
  357. def _createEnviron(self, parent, argdict):
  358. """Return an Environ that delegates to the parent node's Environ (if
  359. there is a parent node), or to the default environment.
  360. """
  361. if parent:
  362. parentenv = parent._env
  363. else:
  364. parentenv = self._getDefaultEnviron()
  365. return TorEnviron(parentenv, **argdict)
  366. def _getDefaultEnviron(self):
  367. """Return the default environment. Any variables that we can't find
  368. set for any particular node, we look for here.
  369. """
  370. return _BASE_ENVIRON
  371. class _NodeCommon(object):
  372. """Internal helper class for functionality shared by some NodeBuilders
  373. and some NodeControllers."""
  374. # XXXX maybe this should turn into a mixin.
  375. def __init__(self, env):
  376. self._env = env
  377. def expand(self, pat, includePath=(".",)):
  378. return chutney.Templating.Template(pat, includePath).format(self._env)
  379. def _getTorrcFname(self):
  380. """Return the name of the file where we'll be writing torrc"""
  381. return self.expand("${torrc_fname}")
  382. class NodeBuilder(_NodeCommon):
  383. """Abstract base class. A NodeBuilder is responsible for doing all the
  384. one-time prep needed to set up a node in a network.
  385. """
  386. def __init__(self, env):
  387. _NodeCommon.__init__(self, env)
  388. def checkConfig(self, net):
  389. """Try to format our torrc; raise an exception if we can't.
  390. """
  391. def preConfig(self, net):
  392. """Called on all nodes before any nodes configure: generates keys as
  393. needed.
  394. """
  395. def config(self, net):
  396. """Called to configure a node: creates a torrc file for it."""
  397. def postConfig(self, net):
  398. """Called on each nodes after all nodes configure."""
  399. def isSupported(self, net):
  400. """Return true if this node appears to have everything it needs;
  401. false otherwise."""
  402. class NodeController(_NodeCommon):
  403. """Abstract base class. A NodeController is responsible for running a
  404. node on the network.
  405. """
  406. def __init__(self, env):
  407. _NodeCommon.__init__(self, env)
  408. def check(self, listRunning=True, listNonRunning=False):
  409. """See if this node is running, stopped, or crashed. If it's running
  410. and listRunning is set, print a short statement. If it's
  411. stopped and listNonRunning is set, then print a short statement.
  412. If it's crashed, print a statement. Return True if the
  413. node is running, false otherwise.
  414. """
  415. def start(self):
  416. """Try to start this node; return True if we succeeded or it was
  417. already running, False if we failed."""
  418. def stop(self, sig=signal.SIGINT):
  419. """Try to stop this node by sending it the signal 'sig'."""
  420. class LocalNodeBuilder(NodeBuilder):
  421. # Environment members used:
  422. # torrc -- which torrc file to use
  423. # torrc_template_path -- path to search for torrc files and include files
  424. # authority -- bool -- are we an authority?
  425. # bridgeauthority -- bool -- are we a bridge authority?
  426. # relay -- bool -- are we a relay?
  427. # bridge -- bool -- are we a bridge?
  428. # hs -- bool -- are we a hidden service?
  429. # nodenum -- int -- set by chutney -- which unique node index is this?
  430. # dir -- path -- set by chutney -- data directory for this tor
  431. # tor_gencert -- path to tor_gencert binary
  432. # tor -- path to tor binary
  433. # auth_cert_lifetime -- lifetime of authority certs, in months.
  434. # ip -- primary IP address (usually IPv4) to listen on
  435. # ipv6_addr -- secondary IP address (usually IPv6) to listen on
  436. # orport, dirport -- used on authorities, relays, and bridges. The orport
  437. # is used for both IPv4 and IPv6, if present
  438. # fingerprint -- used only if authority
  439. # dirserver_flags -- used only if authority
  440. # nick -- nickname of this router
  441. # Environment members set
  442. # fingerprint -- hex router key fingerprint
  443. # nodenum -- int -- set by chutney -- which unique node index is this?
  444. def __init__(self, env):
  445. NodeBuilder.__init__(self, env)
  446. self._env = env
  447. def _createTorrcFile(self, checkOnly=False):
  448. """Write the torrc file for this node, disabling any options
  449. that are not supported by env's tor binary using comments.
  450. If checkOnly, just make sure that the formatting is indeed
  451. possible.
  452. """
  453. global torrc_option_warn_count
  454. fn_out = self._getTorrcFname()
  455. torrc_template = self._getTorrcTemplate()
  456. output = torrc_template.format(self._env)
  457. if checkOnly:
  458. # XXXX Is it time-consuming to format? If so, cache here.
  459. return
  460. # now filter the options we're about to write, commenting out
  461. # the options that the current tor binary doesn't support
  462. tor = self._env['tor']
  463. tor_version = get_tor_version(tor)
  464. torrc_opts = get_torrc_options(tor)
  465. # check if each option is supported before writing it
  466. # Unsupported option values may need special handling.
  467. with open(fn_out, 'w') as f:
  468. # we need to do case-insensitive option comparison
  469. lower_opts = [opt.lower() for opt in torrc_opts]
  470. # keep ends when splitting lines, so we can write them out
  471. # using writelines() without messing around with "\n"s
  472. for line in output.splitlines(True):
  473. # check if the first word on the line is a supported option,
  474. # preserving empty lines and comment lines
  475. sline = line.strip()
  476. if (len(sline) == 0 or
  477. sline[0] == '#' or
  478. sline.split()[0].lower() in lower_opts):
  479. pass
  480. else:
  481. warn_msg = (("The tor binary at {} does not support " +
  482. "the option in the torrc line:\n{}")
  483. .format(tor, line.strip()))
  484. if torrc_option_warn_count < TORRC_OPTION_WARN_LIMIT:
  485. print(warn_msg)
  486. torrc_option_warn_count += 1
  487. else:
  488. debug(warn_msg)
  489. # always dump the full output to the torrc file
  490. line = ("# {} version {} does not support: {}"
  491. .format(tor, tor_version, line))
  492. f.writelines([line])
  493. def _getTorrcTemplate(self):
  494. """Return the template used to write the torrc for this node."""
  495. template_path = self._env['torrc_template_path']
  496. return chutney.Templating.Template("$${include:$torrc}",
  497. includePath=template_path)
  498. def _getFreeVars(self):
  499. """Return a set of the free variables in the torrc template for this
  500. node.
  501. """
  502. template = self._getTorrcTemplate()
  503. return template.freevars(self._env)
  504. def checkConfig(self, net):
  505. """Try to format our torrc; raise an exception if we can't.
  506. """
  507. self._createTorrcFile(checkOnly=True)
  508. def preConfig(self, net):
  509. """Called on all nodes before any nodes configure: generates keys and
  510. hidden service directories as needed.
  511. """
  512. self._makeDataDir()
  513. if self._env['authority']:
  514. self._genAuthorityKey()
  515. if self._env['relay']:
  516. self._genRouterKey()
  517. if self._env['hs']:
  518. self._makeHiddenServiceDir()
  519. def config(self, net):
  520. """Called to configure a node: creates a torrc file for it."""
  521. self._createTorrcFile()
  522. # self._createScripts()
  523. def postConfig(self, net):
  524. """Called on each nodes after all nodes configure."""
  525. # self.net.addNode(self)
  526. pass
  527. def isSupported(self, net):
  528. """Return true if this node appears to have everything it needs;
  529. false otherwise."""
  530. if not tor_exists(self._env['tor']):
  531. print("No binary found for %r"%self._env['tor'])
  532. return False
  533. if self._env['authority']:
  534. if not tor_has_module(self._env['tor'], "dirauth"):
  535. print("No dirauth support in %r"%self._env['tor'])
  536. return False
  537. if not tor_gencert_exists(self._env['tor-gencert']):
  538. print("No binary found for tor-gencert %r"%self._env['tor-gencrrt'])
  539. def _makeDataDir(self):
  540. """Create the data directory (with keys subdirectory) for this node.
  541. """
  542. datadir = self._env['dir']
  543. make_datadir_subdirectory(datadir, "keys")
  544. def _makeHiddenServiceDir(self):
  545. """Create the hidden service subdirectory for this node.
  546. The directory name is stored under the 'hs_directory' environment
  547. key. It is combined with the 'dir' data directory key to yield the
  548. path to the hidden service directory.
  549. """
  550. datadir = self._env['dir']
  551. make_datadir_subdirectory(datadir, self._env['hs_directory'])
  552. def _genAuthorityKey(self):
  553. """Generate an authority identity and signing key for this authority,
  554. if they do not already exist."""
  555. datadir = self._env['dir']
  556. tor_gencert = self._env['tor_gencert']
  557. lifetime = self._env['auth_cert_lifetime']
  558. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  559. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  560. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  561. addr = self.expand("${ip}:${dirport}")
  562. passphrase = self._env['auth_passphrase']
  563. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  564. return
  565. cmdline = [
  566. tor_gencert,
  567. '--create-identity-key',
  568. '--passphrase-fd', '0',
  569. '-i', idfile,
  570. '-s', skfile,
  571. '-c', certfile,
  572. '-m', str(lifetime),
  573. '-a', addr,
  574. ]
  575. # nicknames are testNNNaa[OLD], but we want them to look tidy
  576. print("Creating identity key for {:12} with {}"
  577. .format(self._env['nick'], cmdline[0]))
  578. debug("Identity key path '{}', command '{}'"
  579. .format(idfile, " ".join(cmdline)))
  580. run_tor_gencert(cmdline, passphrase)
  581. def _genRouterKey(self):
  582. """Generate an identity key for this router, unless we already have,
  583. and set up the 'fingerprint' entry in the Environ.
  584. """
  585. datadir = self._env['dir']
  586. tor = self._env['tor']
  587. torrc = self._getTorrcFname()
  588. cmdline = [
  589. tor,
  590. "--ignore-missing-torrc",
  591. "-f", torrc,
  592. "--list-fingerprint",
  593. "--orport", "1",
  594. "--datadirectory", datadir,
  595. ]
  596. stdouterr = run_tor(cmdline)
  597. fingerprint = "".join((stdouterr.rstrip().split('\n')[-1]).split()[1:])
  598. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  599. print("Error when getting fingerprint using '%r'. It output '%r'."
  600. .format(" ".join(cmdline), stdouterr))
  601. sys.exit(1)
  602. self._env['fingerprint'] = fingerprint
  603. def _getAltAuthLines(self, hasbridgeauth=False):
  604. """Return a combination of AlternateDirAuthority,
  605. and AlternateBridgeAuthority lines for
  606. this Node, appropriately. Non-authorities return ""."""
  607. if not self._env['authority']:
  608. return ""
  609. datadir = self._env['dir']
  610. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  611. v3id = None
  612. with open(certfile, 'r') as f:
  613. for line in f:
  614. if line.startswith("fingerprint"):
  615. v3id = line.split()[1].strip()
  616. break
  617. assert v3id is not None
  618. if self._env['bridgeauthority']:
  619. # Bridge authorities return AlternateBridgeAuthority with
  620. # the 'bridge' flag set.
  621. options = ("AlternateBridgeAuthority",)
  622. self._env['dirserver_flags'] += " bridge"
  623. else:
  624. # Directory authorities return AlternateDirAuthority with
  625. # the 'v3ident' flag set.
  626. # XXXX This next line is needed for 'bridges' but breaks
  627. # 'basic'
  628. if hasbridgeauth:
  629. options = ("AlternateDirAuthority",)
  630. else:
  631. options = ("DirAuthority",)
  632. self._env['dirserver_flags'] += " v3ident=%s" % v3id
  633. authlines = ""
  634. for authopt in options:
  635. authlines += "%s %s orport=%s" % (
  636. authopt, self._env['nick'], self._env['orport'])
  637. # It's ok to give an authority's IPv6 address to an IPv4-only
  638. # client or relay: it will and must ignore it
  639. # and yes, the orport is the same on IPv4 and IPv6
  640. if self._env['ipv6_addr'] is not None:
  641. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  642. self._env['orport'])
  643. authlines += " %s %s:%s %s\n" % (
  644. self._env['dirserver_flags'], self._env['ip'],
  645. self._env['dirport'], self._env['fingerprint'])
  646. return authlines
  647. def _getBridgeLines(self):
  648. """Return potential Bridge line for this Node. Non-bridge
  649. relays return "".
  650. """
  651. if not self._env['bridge']:
  652. return ""
  653. if self._env['pt_bridge']:
  654. port = self._env['ptport']
  655. transport = self._env['pt_transport']
  656. extra = self._env['pt_extra']
  657. else:
  658. # the orport is the same on IPv4 and IPv6
  659. port = self._env['orport']
  660. transport = ""
  661. extra = ""
  662. BRIDGE_LINE_TEMPLATE = "Bridge %s %s:%s %s %s\n"
  663. bridgelines = BRIDGE_LINE_TEMPLATE % (transport,
  664. self._env['ip'],
  665. port,
  666. self._env['fingerprint'],
  667. extra)
  668. if self._env['ipv6_addr'] is not None:
  669. bridgelines += BRIDGE_LINE_TEMPLATE % (transport,
  670. self._env['ipv6_addr'],
  671. port,
  672. self._env['fingerprint'],
  673. extra)
  674. return bridgelines
  675. class LocalNodeController(NodeController):
  676. def __init__(self, env):
  677. NodeController.__init__(self, env)
  678. self._env = env
  679. def getNick(self):
  680. """Return the nickname for this node."""
  681. return self._env['nick']
  682. def getPid(self):
  683. """Assuming that this node has its pidfile in ${dir}/pid, return
  684. the pid of the running process, or None if there is no pid in the
  685. file.
  686. """
  687. pidfile = os.path.join(self._env['dir'], 'pid')
  688. if not os.path.exists(pidfile):
  689. return None
  690. with open(pidfile, 'r') as f:
  691. return int(f.read())
  692. def isRunning(self, pid=None):
  693. """Return true iff this node is running. (If 'pid' is provided, we
  694. assume that the pid provided is the one of this node. Otherwise
  695. we call getPid().
  696. """
  697. if pid is None:
  698. pid = self.getPid()
  699. if pid is None:
  700. return False
  701. try:
  702. os.kill(pid, 0) # "kill 0" == "are you there?"
  703. except OSError as e:
  704. if e.errno == errno.ESRCH:
  705. return False
  706. raise
  707. # okay, so the process exists. Say "True" for now.
  708. # XXXX check if this is really tor!
  709. return True
  710. def check(self, listRunning=True, listNonRunning=False):
  711. """See if this node is running, stopped, or crashed. If it's running
  712. and listRunning is set, print a short statement. If it's
  713. stopped and listNonRunning is set, then print a short statement.
  714. If it's crashed, print a statement. Return True if the
  715. node is running, false otherwise.
  716. """
  717. # XXX Split this into "check" and "print" parts.
  718. pid = self.getPid()
  719. nick = self._env['nick']
  720. datadir = self._env['dir']
  721. corefile = "core.%s" % pid
  722. tor_version = get_tor_version(self._env['tor'])
  723. if self.isRunning(pid):
  724. if listRunning:
  725. # PIDs are typically 65535 or less
  726. print("{:12} is running with PID {:5}: {}"
  727. .format(nick, pid, tor_version))
  728. return True
  729. elif os.path.exists(os.path.join(datadir, corefile)):
  730. if listNonRunning:
  731. print("{:12} seems to have crashed, and left core file {}: {}"
  732. .format(nick, corefile, tor_version))
  733. return False
  734. else:
  735. if listNonRunning:
  736. print("{:12} is stopped: {}"
  737. .format(nick, tor_version))
  738. return False
  739. def hup(self):
  740. """Send a SIGHUP to this node, if it's running."""
  741. pid = self.getPid()
  742. nick = self._env['nick']
  743. if self.isRunning(pid):
  744. print("Sending sighup to {}".format(nick))
  745. os.kill(pid, signal.SIGHUP)
  746. return True
  747. else:
  748. print("{:12} is not running".format(nick))
  749. return False
  750. def start(self):
  751. """Try to start this node; return True if we succeeded or it was
  752. already running, False if we failed."""
  753. if self.isRunning():
  754. print("{:12} is already running".format(self._env['nick']))
  755. return True
  756. tor_path = self._env['tor']
  757. torrc = self._getTorrcFname()
  758. cmdline = [
  759. tor_path,
  760. "-f", torrc,
  761. ]
  762. p = launch_process(cmdline)
  763. if self.waitOnLaunch():
  764. # this requires that RunAsDaemon is set
  765. (stdouterr, empty_stderr) = p.communicate()
  766. debug(stdouterr)
  767. assert empty_stderr is None
  768. else:
  769. # this does not require RunAsDaemon to be set, but is slower.
  770. #
  771. # poll() only catches failures before the call itself
  772. # so let's sleep a little first
  773. # this does, of course, slow down process launch
  774. # which can require an adjustment to the voting interval
  775. #
  776. # avoid writing a newline or space when polling
  777. # so output comes out neatly
  778. sys.stdout.write('.')
  779. sys.stdout.flush()
  780. time.sleep(self._env['poll_launch_time'])
  781. p.poll()
  782. if p.returncode is not None and p.returncode != 0:
  783. if self._env['poll_launch_time'] is None:
  784. print(("Couldn't launch {:12} command '{}': " +
  785. "exit {}, output '{}'")
  786. .format(self._env['nick'],
  787. " ".join(cmdline),
  788. p.returncode,
  789. stdouterr))
  790. else:
  791. print(("Couldn't poll {:12} command '{}' " +
  792. "after waiting {} seconds for launch: " +
  793. "exit {}").format(self._env['nick'],
  794. " ".join(cmdline),
  795. self._env['poll_launch_time'],
  796. p.returncode))
  797. return False
  798. return True
  799. def stop(self, sig=signal.SIGINT):
  800. """Try to stop this node by sending it the signal 'sig'."""
  801. pid = self.getPid()
  802. if not self.isRunning(pid):
  803. print("{:12} is not running".format(self._env['nick']))
  804. return
  805. os.kill(pid, sig)
  806. def cleanup_lockfile(self):
  807. lf = self._env['lockfile']
  808. if not self.isRunning() and os.path.exists(lf):
  809. debug("Removing stale lock file for {} ..."
  810. .format(self._env['nick']))
  811. os.remove(lf)
  812. def waitOnLaunch(self):
  813. """Check whether we can wait() for the tor process to launch"""
  814. # TODO: is this the best place for this code?
  815. # RunAsDaemon default is 0
  816. runAsDaemon = False
  817. with open(self._getTorrcFname(), 'r') as f:
  818. for line in f.readlines():
  819. stline = line.strip()
  820. # if the line isn't all whitespace or blank
  821. if len(stline) > 0:
  822. splline = stline.split()
  823. # if the line has at least two tokens on it
  824. if (len(splline) > 0 and
  825. splline[0].lower() == "RunAsDaemon".lower() and
  826. splline[1] == "1"):
  827. # use the RunAsDaemon value from the torrc
  828. # TODO: multiple values?
  829. runAsDaemon = True
  830. if runAsDaemon:
  831. # we must use wait() instead of poll()
  832. self._env['poll_launch_time'] = None
  833. return True
  834. else:
  835. # we must use poll() instead of wait()
  836. if self._env['poll_launch_time'] is None:
  837. self._env['poll_launch_time'] = \
  838. self._env['poll_launch_time_default']
  839. return False
  840. def getLogfile(self, info=False):
  841. """Return the expected path to the logfile for this instance."""
  842. datadir = self._env['dir']
  843. if info:
  844. logname = "info.log"
  845. else:
  846. logname = "notice.log"
  847. return os.path.join(datadir, logname)
  848. def getLastBootstrapStatus(self):
  849. """Look through the logs and return the last bootstrap message
  850. received as a 3-tuple of percentage complete, keyword
  851. (optional), and message.
  852. """
  853. logfname = self.getLogfile()
  854. if not os.path.exists(logfname):
  855. return (-200, "no_logfile", "There is no logfile yet.")
  856. percent,keyword,message=-100,"no_message","No bootstrap messages yet."
  857. with open(logfname, 'r') as f:
  858. for line in f:
  859. m = re.search(r'Bootstrapped (\d+)%(?: \(([^\)]*)\))?: (.*)',
  860. line)
  861. if m:
  862. percent, keyword, message = m.groups()
  863. percent = int(percent)
  864. return (percent, keyword, message)
  865. def isBootstrapped(self):
  866. """Return true iff the logfile says that this instance is
  867. bootstrapped."""
  868. pct, _, _ = self.getLastBootstrapStatus()
  869. return pct == 100
  870. # XXX: document these options
  871. DEFAULTS = {
  872. 'authority': False,
  873. 'bridgeauthority': False,
  874. 'hasbridgeauth': False,
  875. 'relay': False,
  876. 'bridge': False,
  877. 'pt_bridge': False,
  878. 'pt_transport' : "",
  879. 'pt_extra' : "",
  880. 'hs': False,
  881. 'hs_directory': 'hidden_service',
  882. 'hs-hostname': None,
  883. 'connlimit': 60,
  884. 'net_base_dir': get_absolute_net_path(),
  885. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  886. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  887. 'auth_cert_lifetime': 12,
  888. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  889. # we default to ipv6_addr None to support IPv4-only systems
  890. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  891. 'dirserver_flags': 'no-v2',
  892. 'chutney_dir': get_absolute_chutney_path(),
  893. 'torrc_fname': '${dir}/torrc',
  894. 'orport_base': 5000,
  895. 'dirport_base': 7000,
  896. 'controlport_base': 8000,
  897. 'socksport_base': 9000,
  898. 'extorport_base' : 9500,
  899. 'ptport_base' : 9900,
  900. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  901. 'bridges': "Bridge bleargh bad torrc file!",
  902. 'core': True,
  903. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  904. # otherwise, poll after that many seconds (can be fractional/decimal)
  905. 'poll_launch_time': None,
  906. # Used when poll_launch_time is None, but RunAsDaemon is not set
  907. # Set low so that we don't interfere with the voting interval
  908. 'poll_launch_time_default': 0.1,
  909. # the number of bytes of random data we send on each connection
  910. 'data_bytes': getenv_int('CHUTNEY_DATA_BYTES', 10 * 1024),
  911. # the number of times each client will connect
  912. 'connection_count': getenv_int('CHUTNEY_CONNECTIONS', 1),
  913. # Do we want every client to connect to every HS, or one client
  914. # to connect to each HS?
  915. # (Clients choose an exit at random, so this doesn't apply to exits.)
  916. 'hs_multi_client': getenv_int('CHUTNEY_HS_MULTI_CLIENT', 0),
  917. # How long should verify (and similar commands) wait for a successful
  918. # outcome? (seconds)
  919. # We check BOOTSTRAP_TIME for compatibility with old versions of
  920. # test-network.sh
  921. 'bootstrap_time': getenv_int('CHUTNEY_BOOTSTRAP_TIME',
  922. getenv_int('BOOTSTRAP_TIME',
  923. 60)),
  924. # the PID of the controlling script (for __OwningControllerProcess)
  925. 'controlling_pid': getenv_int('CHUTNEY_CONTROLLING_PID', 0),
  926. # a DNS config file (for ServerDNSResolvConfFile)
  927. 'dns_conf': (os.environ.get('CHUTNEY_DNS_CONF', '/etc/resolv.conf')
  928. if 'CHUTNEY_DNS_CONF' in os.environ
  929. else None),
  930. # The phase at which this instance needs to be
  931. # configured/launched, if we're doing multiphase
  932. # configuration/launch.
  933. 'config_phase' : 1,
  934. 'launch_phase' : 1,
  935. 'CUR_CONFIG_PHASE': getenv_int('CHUTNEY_CONFIG_PHASE', 1),
  936. 'CUR_LAUNCH_PHASE': getenv_int('CHUTNEY_LAUNCH_PHASE', 1),
  937. # the Sandbox torrc option value
  938. # defaults to 1 on Linux, and 0 otherwise
  939. 'sandbox': int(getenv_bool('CHUTNEY_TOR_SANDBOX',
  940. platform.system() == 'Linux')),
  941. }
  942. class TorEnviron(chutney.Templating.Environ):
  943. """Subclass of chutney.Templating.Environ to implement commonly-used
  944. substitutions.
  945. Environment fields provided:
  946. orport, controlport, socksport, dirport: *Port torrc option
  947. dir: DataDirectory torrc option
  948. nick: Nickname torrc option
  949. tor_gencert: name or path of the tor-gencert binary
  950. auth_passphrase: obsoleted by CookieAuthentication
  951. torrc_template_path: path to chutney torrc_templates directory
  952. hs_hostname: the hostname of the key generated by a hidden service
  953. owning_controller_process: the __OwningControllerProcess torrc line,
  954. disabled if tor should continue after the script exits
  955. server_dns_resolv_conf: the ServerDNSResolvConfFile torrc line,
  956. disabled if tor should use the default DNS conf.
  957. If the dns_conf file is missing, this option is also disabled:
  958. otherwise, exits would not work due to tor bug #21900.
  959. sandbox: Sets Sandbox to the value of CHUTNEY_TOR_SANDBOX.
  960. The default is 1 on Linux, and 0 on other platforms.
  961. Chutney users can disable the sandbox using:
  962. export CHUTNEY_TOR_SANDBOX=0
  963. if it doesn't work on their version of glibc.
  964. Environment fields used:
  965. nodenum: chutney's internal node number for the node
  966. tag: a short text string that represents the type of node
  967. orport_base, controlport_base, socksport_base, dirport_base: the
  968. initial port numbers used by nodenum 0. Each additional node adds
  969. 1 to the port numbers.
  970. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  971. present)
  972. chutney_dir: directory of the chutney source code
  973. tor: name or path of the tor binary
  974. net_base_dir: path to the chutney net directory
  975. hs_directory: name of the hidden service directory
  976. nick: Nickname torrc option (debugging only)
  977. hs-hostname (note hyphen): cached hidden service hostname value
  978. controlling_pid: the PID of the controlling process. After this
  979. process exits, the child tor processes will exit
  980. dns_conf: the path to a DNS config file for Tor Exits. If this file
  981. is empty or unreadable, Tor will try 127.0.0.1:53.
  982. """
  983. def __init__(self, parent=None, **kwargs):
  984. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  985. def _get_orport(self, my):
  986. return my['orport_base'] + my['nodenum']
  987. def _get_controlport(self, my):
  988. return my['controlport_base'] + my['nodenum']
  989. def _get_socksport(self, my):
  990. return my['socksport_base'] + my['nodenum']
  991. def _get_dirport(self, my):
  992. return my['dirport_base'] + my['nodenum']
  993. def _get_extorport(self, my):
  994. return my['extorport_base'] + my['nodenum']
  995. def _get_ptport(self, my):
  996. return my['ptport_base'] + my['nodenum']
  997. def _get_dir(self, my):
  998. return os.path.abspath(os.path.join(my['net_base_dir'],
  999. "nodes",
  1000. "%03d%s" % (
  1001. my['nodenum'], my['tag'])))
  1002. def _get_nick(self, my):
  1003. return "test%03d%s" % (my['nodenum'], my['tag'])
  1004. def _get_tor_gencert(self, my):
  1005. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  1006. def _get_auth_passphrase(self, my):
  1007. return self['nick'] # OMG TEH SECURE!
  1008. def _get_torrc_template_path(self, my):
  1009. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  1010. def _get_lockfile(self, my):
  1011. return os.path.join(self['dir'], 'lock')
  1012. # A hs generates its key on first run,
  1013. # so check for it at the last possible moment,
  1014. # but cache it in memory to avoid repeatedly reading the file
  1015. # XXXX - this is not like the other functions in this class,
  1016. # as it reads from a file created by the hidden service
  1017. def _get_hs_hostname(self, my):
  1018. if my['hs-hostname'] is None:
  1019. datadir = my['dir']
  1020. # a file containing a single line with the hs' .onion address
  1021. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  1022. 'hostname')
  1023. try:
  1024. with open(hs_hostname_file, 'r') as hostnamefp:
  1025. hostname = hostnamefp.read()
  1026. # the hostname file ends with a newline
  1027. hostname = hostname.strip()
  1028. my['hs-hostname'] = hostname
  1029. except IOError as e:
  1030. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  1031. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  1032. return my['hs-hostname']
  1033. def _get_owning_controller_process(self, my):
  1034. cpid = my['controlling_pid']
  1035. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  1036. # if we want to leave the network running, or controlling_pid is 1
  1037. # (or invalid)
  1038. if (getenv_int('CHUTNEY_START_TIME', 0) < 0 or
  1039. getenv_int('CHUTNEY_BOOTSTRAP_TIME', 0) < 0 or
  1040. getenv_int('CHUTNEY_STOP_TIME', 0) < 0 or
  1041. cpid <= 1):
  1042. return '#' + ocp_line
  1043. else:
  1044. return ocp_line
  1045. # the default resolv.conf path is set at compile time
  1046. # there's no easy way to get it out of tor, so we use the typical value
  1047. DEFAULT_DNS_RESOLV_CONF = "/etc/resolv.conf"
  1048. # if we can't find the specified file, use this one as a substitute
  1049. OFFLINE_DNS_RESOLV_CONF = "/dev/null"
  1050. def _get_server_dns_resolv_conf(self, my):
  1051. if my['dns_conf'] == "":
  1052. # if the user asked for tor's default
  1053. return "#ServerDNSResolvConfFile using tor's compile-time default"
  1054. elif my['dns_conf'] is None:
  1055. # if there is no DNS conf file set
  1056. debug("CHUTNEY_DNS_CONF not specified, using '{}'."
  1057. .format(TorEnviron.DEFAULT_DNS_RESOLV_CONF))
  1058. dns_conf = TorEnviron.DEFAULT_DNS_RESOLV_CONF
  1059. else:
  1060. dns_conf = my['dns_conf']
  1061. dns_conf = os.path.abspath(dns_conf)
  1062. # work around Tor bug #21900, where exits fail when the DNS conf
  1063. # file does not exist, or is a broken symlink
  1064. # (os.path.exists returns False for broken symbolic links)
  1065. if not os.path.exists(dns_conf):
  1066. # Issue a warning so the user notices
  1067. print("CHUTNEY_DNS_CONF '{}' does not exist, using '{}'."
  1068. .format(dns_conf, TorEnviron.OFFLINE_DNS_RESOLV_CONF))
  1069. dns_conf = TorEnviron.OFFLINE_DNS_RESOLV_CONF
  1070. return "ServerDNSResolvConfFile %s" % (dns_conf)
  1071. KNOWN_REQUIREMENTS = {
  1072. "IPV6": chutney.Host.is_ipv6_supported
  1073. }
  1074. class Network(object):
  1075. """A network of Tor nodes, plus functions to manipulate them
  1076. """
  1077. def __init__(self, defaultEnviron):
  1078. self._nodes = []
  1079. self._requirements = []
  1080. self._dfltEnv = defaultEnviron
  1081. self._nextnodenum = 0
  1082. def _addNode(self, n):
  1083. n.setNodenum(self._nextnodenum)
  1084. self._nextnodenum += 1
  1085. self._nodes.append(n)
  1086. def _addRequirement(self, requirement):
  1087. requirement = requirement.upper()
  1088. if requirement not in KNOWN_REQUIREMENTS:
  1089. raise RuntimemeError(("Unrecognized requirement %r"%requirement))
  1090. self._requirements.append(requirement)
  1091. def move_aside_nodes_dir(self):
  1092. """Move aside the nodes directory, if it exists and is not a link.
  1093. Used for backwards-compatibility only: nodes is created as a link to
  1094. a new directory with a unique name in the current implementation.
  1095. """
  1096. nodesdir = get_absolute_nodes_path()
  1097. # only move the directory if it exists
  1098. if not os.path.exists(nodesdir):
  1099. return
  1100. # and if it's not a link
  1101. if os.path.islink(nodesdir):
  1102. return
  1103. # subtract 1 second to avoid collisions and get the correct ordering
  1104. newdir = get_new_absolute_nodes_path(time.time() - 1)
  1105. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  1106. os.rename(nodesdir, newdir)
  1107. def create_new_nodes_dir(self):
  1108. """Create a new directory with a unique name, and symlink it to nodes
  1109. """
  1110. # for backwards compatibility, move aside the old nodes directory
  1111. # (if it's not a link)
  1112. self.move_aside_nodes_dir()
  1113. # the unique directory we'll create
  1114. newnodesdir = get_new_absolute_nodes_path()
  1115. # the canonical name we'll link it to
  1116. nodeslink = get_absolute_nodes_path()
  1117. # this path should be unique and should not exist
  1118. if os.path.exists(newnodesdir):
  1119. raise RuntimeError(
  1120. 'get_new_absolute_nodes_path returned a path that exists')
  1121. # if this path exists, it must be a link
  1122. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  1123. raise RuntimeError(
  1124. 'get_absolute_nodes_path returned a path that exists and is not a link')
  1125. # create the new, uniquely named directory, and link it to nodes
  1126. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  1127. # this gets created with mode 0700, that's probably ok
  1128. mkdir_p(newnodesdir)
  1129. try:
  1130. os.unlink(nodeslink)
  1131. except OSError as e:
  1132. # it's ok if the link doesn't exist, we're just about to make it
  1133. if e.errno == errno.ENOENT:
  1134. pass
  1135. else:
  1136. raise
  1137. os.symlink(newnodesdir, nodeslink)
  1138. def _checkConfig(self):
  1139. for n in self._nodes:
  1140. n.getBuilder().checkConfig(self)
  1141. def supported(self):
  1142. """Check whether this network is supported by the set of binaries
  1143. and host information we have.
  1144. """
  1145. missing_any = False
  1146. for r in self._requirements:
  1147. if not KNOWN_REQUIREMENTS[r]():
  1148. print(("Can't run this network: %s is missing."))
  1149. missing_any = True
  1150. for n in self._nodes:
  1151. if not n.getBuilder().isSupported(self):
  1152. missing_any = False
  1153. if missing_any:
  1154. sys.exit(1)
  1155. def configure(self):
  1156. phase = self._dfltEnv['CUR_CONFIG_PHASE']
  1157. if phase == 1:
  1158. self.create_new_nodes_dir()
  1159. network = self
  1160. altauthlines = []
  1161. bridgelines = []
  1162. all_builders = [ n.getBuilder() for n in self._nodes ]
  1163. builders = [ b for b in all_builders
  1164. if b._env['config_phase'] == phase ]
  1165. self._checkConfig()
  1166. # XXX don't change node names or types or count if anything is
  1167. # XXX running!
  1168. for b in all_builders:
  1169. b.preConfig(network)
  1170. altauthlines.append(b._getAltAuthLines(
  1171. self._dfltEnv['hasbridgeauth']))
  1172. bridgelines.append(b._getBridgeLines())
  1173. self._dfltEnv['authorities'] = "".join(altauthlines)
  1174. self._dfltEnv['bridges'] = "".join(bridgelines)
  1175. for b in builders:
  1176. b.config(network)
  1177. for b in builders:
  1178. b.postConfig(network)
  1179. def status(self):
  1180. statuses = [n.getController().check(listNonRunning=True)
  1181. for n in self._nodes]
  1182. n_ok = len([x for x in statuses if x])
  1183. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  1184. return n_ok == len(self._nodes)
  1185. def restart(self):
  1186. self.stop()
  1187. self.start()
  1188. def start(self):
  1189. # format polling correctly - avoid printing a newline
  1190. sys.stdout.write("Starting nodes")
  1191. sys.stdout.flush()
  1192. rv = all([n.getController().start() for n in self._nodes
  1193. if n._env['launch_phase'] ==
  1194. self._dfltEnv['CUR_LAUNCH_PHASE']])
  1195. # now print a newline unconditionally - this stops poll()ing
  1196. # output from being squashed together, at the cost of a blank
  1197. # line in wait()ing output
  1198. print("")
  1199. return rv
  1200. def hup(self):
  1201. print("Sending SIGHUP to nodes")
  1202. return all([n.getController().hup() for n in self._nodes])
  1203. def wait_for_bootstrap(self):
  1204. print("Waiting for nodes to bootstrap...")
  1205. limit = getenv_int("CHUTNEY_START_TIME", 60)
  1206. delay = 0.5
  1207. controllers = [n.getController() for n in self._nodes]
  1208. elapsed = 0.0
  1209. most_recent_status = [ None ] * len(controllers)
  1210. while True:
  1211. all_bootstrapped = True
  1212. most_recent_status = [ ]
  1213. for c in controllers:
  1214. pct, kwd, msg = c.getLastBootstrapStatus()
  1215. most_recent_status.append((pct, kwd, msg))
  1216. if pct != 100:
  1217. all_bootstrapped = False
  1218. if all_bootstrapped:
  1219. print("Everything bootstrapped after %s sec"%elapsed)
  1220. return True
  1221. if elapsed >= limit:
  1222. break
  1223. time.sleep(delay)
  1224. elapsed += delay
  1225. print("Bootstrap failed. Node status:")
  1226. for c, status in zip(controllers,most_recent_status):
  1227. c.check(listRunning=False, listNonRunning=True)
  1228. print("{}: {}".format(c.getNick(), status))
  1229. return False
  1230. def stop(self):
  1231. controllers = [n.getController() for n in self._nodes]
  1232. for sig, desc in [(signal.SIGINT, "SIGINT"),
  1233. (signal.SIGINT, "another SIGINT"),
  1234. (signal.SIGKILL, "SIGKILL")]:
  1235. print("Sending %s to nodes" % desc)
  1236. for c in controllers:
  1237. if c.isRunning():
  1238. c.stop(sig=sig)
  1239. print("Waiting for nodes to finish.")
  1240. wrote_dot = False
  1241. for n in range(15):
  1242. time.sleep(1)
  1243. if all(not c.isRunning() for c in controllers):
  1244. # make the output clearer by adding a newline
  1245. if wrote_dot:
  1246. sys.stdout.write("\n")
  1247. sys.stdout.flush()
  1248. # check for stale lock file when Tor crashes
  1249. for c in controllers:
  1250. c.cleanup_lockfile()
  1251. return
  1252. sys.stdout.write(".")
  1253. wrote_dot = True
  1254. sys.stdout.flush()
  1255. for c in controllers:
  1256. c.check(listNonRunning=False)
  1257. # make the output clearer by adding a newline
  1258. if wrote_dot:
  1259. sys.stdout.write("\n")
  1260. sys.stdout.flush()
  1261. def Require(feature):
  1262. network = _THE_NETWORK
  1263. network._addRequirement(feature)
  1264. def ConfigureNodes(nodelist):
  1265. network = _THE_NETWORK
  1266. for n in nodelist:
  1267. network._addNode(n)
  1268. if n._env['bridgeauthority']:
  1269. network._dfltEnv['hasbridgeauth'] = True
  1270. def getTests():
  1271. tests = []
  1272. chutney_path = get_absolute_chutney_path()
  1273. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  1274. chutney_path += "/"
  1275. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  1276. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  1277. tests.append(os.path.splitext(x)[0])
  1278. return tests
  1279. def usage(network):
  1280. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  1281. "Known commands are: %s" % (
  1282. " ".join(x for x in dir(network)
  1283. if not x.startswith("_"))),
  1284. "Known tests are: %s" % (
  1285. " ".join(getTests()))
  1286. ])
  1287. def exit_on_error(err_msg):
  1288. print("Error: {0}\n".format(err_msg))
  1289. print(usage(_THE_NETWORK))
  1290. sys.exit(1)
  1291. def runConfigFile(verb, data):
  1292. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  1293. Node=Node,
  1294. Require=Require,
  1295. ConfigureNodes=ConfigureNodes,
  1296. _THE_NETWORK=_THE_NETWORK,
  1297. torrc_option_warn_count=0,
  1298. TORRC_OPTION_WARN_LIMIT=10)
  1299. exec(data, _GLOBALS)
  1300. network = _GLOBALS['_THE_NETWORK']
  1301. # let's check if the verb is a valid test and run it
  1302. if verb in getTests():
  1303. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  1304. try:
  1305. run_test = test_module.run_test
  1306. except AttributeError as e:
  1307. print("Error running test {!r}: {}".format(verb, e))
  1308. return False
  1309. return run_test(network)
  1310. # tell the user we don't know what their verb meant
  1311. if not hasattr(network, verb):
  1312. print(usage(network))
  1313. print("Error: I don't know how to %s." % verb)
  1314. return
  1315. return getattr(network, verb)()
  1316. def parseArgs():
  1317. if len(sys.argv) < 3:
  1318. exit_on_error("Not enough arguments given.")
  1319. if not os.path.isfile(sys.argv[2]):
  1320. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  1321. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  1322. def main():
  1323. global _BASE_ENVIRON
  1324. global _THE_NETWORK
  1325. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  1326. _THE_NETWORK = Network(_BASE_ENVIRON)
  1327. args = parseArgs()
  1328. f = open(args['network_cfg'])
  1329. result = runConfigFile(args['action'], f.read())
  1330. if result is False:
  1331. return -1
  1332. return 0
  1333. if __name__ == '__main__':
  1334. sys.exit(main())