TorNet.py 49 KB

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