TorNet.py 51 KB

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