TorNet.py 48 KB

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