TorNet.py 54 KB

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