TorNet.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  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 getPid(self):
  560. """Assuming that this node has its pidfile in ${dir}/pid, return
  561. the pid of the running process, or None if there is no pid in the
  562. file.
  563. """
  564. pidfile = os.path.join(self._env['dir'], 'pid')
  565. if not os.path.exists(pidfile):
  566. return None
  567. with open(pidfile, 'r') as f:
  568. return int(f.read())
  569. def isRunning(self, pid=None):
  570. """Return true iff this node is running. (If 'pid' is provided, we
  571. assume that the pid provided is the one of this node. Otherwise
  572. we call getPid().
  573. """
  574. if pid is None:
  575. pid = self.getPid()
  576. if pid is None:
  577. return False
  578. try:
  579. os.kill(pid, 0) # "kill 0" == "are you there?"
  580. except OSError as e:
  581. if e.errno == errno.ESRCH:
  582. return False
  583. raise
  584. # okay, so the process exists. Say "True" for now.
  585. # XXXX check if this is really tor!
  586. return True
  587. def check(self, listRunning=True, listNonRunning=False):
  588. """See if this node is running, stopped, or crashed. If it's running
  589. and listRunning is set, print a short statement. If it's
  590. stopped and listNonRunning is set, then print a short statement.
  591. If it's crashed, print a statement. Return True if the
  592. node is running, false otherwise.
  593. """
  594. # XXX Split this into "check" and "print" parts.
  595. pid = self.getPid()
  596. nick = self._env['nick']
  597. datadir = self._env['dir']
  598. corefile = "core.%s" % pid
  599. tor_version = get_tor_version(self._env['tor'])
  600. if self.isRunning(pid):
  601. if listRunning:
  602. # PIDs are typically 65535 or less
  603. print("{:12} is running with PID {:5}: {}"
  604. .format(nick, pid, tor_version))
  605. return True
  606. elif os.path.exists(os.path.join(datadir, corefile)):
  607. if listNonRunning:
  608. print("{:12} seems to have crashed, and left core file {}: {}"
  609. .format(nick, corefile, tor_version))
  610. return False
  611. else:
  612. if listNonRunning:
  613. print("{:12} is stopped: {}"
  614. .format(nick, tor_version))
  615. return False
  616. def hup(self):
  617. """Send a SIGHUP to this node, if it's running."""
  618. pid = self.getPid()
  619. nick = self._env['nick']
  620. if self.isRunning(pid):
  621. print("Sending sighup to {}".format(nick))
  622. os.kill(pid, signal.SIGHUP)
  623. return True
  624. else:
  625. print("{:12} is not running".format(nick))
  626. return False
  627. def start(self):
  628. """Try to start this node; return True if we succeeded or it was
  629. already running, False if we failed."""
  630. if self.isRunning():
  631. print("{:12} is already running".format(self._env['nick']))
  632. return True
  633. tor_path = self._env['tor']
  634. torrc = self._getTorrcFname()
  635. cmdline = [
  636. tor_path,
  637. "-f", torrc,
  638. ]
  639. p = launch_process(cmdline)
  640. if self.waitOnLaunch():
  641. # this requires that RunAsDaemon is set
  642. (stdouterr, empty_stderr) = p.communicate()
  643. debug(stdouterr)
  644. assert empty_stderr is None
  645. else:
  646. # this does not require RunAsDaemon to be set, but is slower.
  647. #
  648. # poll() only catches failures before the call itself
  649. # so let's sleep a little first
  650. # this does, of course, slow down process launch
  651. # which can require an adjustment to the voting interval
  652. #
  653. # avoid writing a newline or space when polling
  654. # so output comes out neatly
  655. sys.stdout.write('.')
  656. sys.stdout.flush()
  657. time.sleep(self._env['poll_launch_time'])
  658. p.poll()
  659. if p.returncode is not None and p.returncode != 0:
  660. if self._env['poll_launch_time'] is None:
  661. print(("Couldn't launch {:12} command '{}': " +
  662. "exit {}, output '{}'")
  663. .format(self._env['nick'],
  664. " ".join(cmdline),
  665. p.returncode,
  666. stdouterr))
  667. else:
  668. print(("Couldn't poll {:12} command '{}' " +
  669. "after waiting {} seconds for launch: " +
  670. "exit {}").format(self._env['nick'],
  671. " ".join(cmdline),
  672. self._env['poll_launch_time'],
  673. p.returncode))
  674. return False
  675. return True
  676. def stop(self, sig=signal.SIGINT):
  677. """Try to stop this node by sending it the signal 'sig'."""
  678. pid = self.getPid()
  679. if not self.isRunning(pid):
  680. print("{:12} is not running".format(self._env['nick']))
  681. return
  682. os.kill(pid, sig)
  683. def cleanup_lockfile(self):
  684. lf = self._env['lockfile']
  685. if not self.isRunning() and os.path.exists(lf):
  686. debug("Removing stale lock file for {} ..."
  687. .format(self._env['nick']))
  688. os.remove(lf)
  689. def waitOnLaunch(self):
  690. """Check whether we can wait() for the tor process to launch"""
  691. # TODO: is this the best place for this code?
  692. # RunAsDaemon default is 0
  693. runAsDaemon = False
  694. with open(self._getTorrcFname(), 'r') as f:
  695. for line in f.readlines():
  696. stline = line.strip()
  697. # if the line isn't all whitespace or blank
  698. if len(stline) > 0:
  699. splline = stline.split()
  700. # if the line has at least two tokens on it
  701. if (len(splline) > 0 and
  702. splline[0].lower() == "RunAsDaemon".lower() and
  703. splline[1] == "1"):
  704. # use the RunAsDaemon value from the torrc
  705. # TODO: multiple values?
  706. runAsDaemon = True
  707. if runAsDaemon:
  708. # we must use wait() instead of poll()
  709. self._env['poll_launch_time'] = None
  710. return True
  711. else:
  712. # we must use poll() instead of wait()
  713. if self._env['poll_launch_time'] is None:
  714. self._env['poll_launch_time'] = \
  715. self._env['poll_launch_time_default']
  716. return False
  717. def getLogfile(self, info=False):
  718. """Return the expected path to the logfile for this instance."""
  719. datadir = self._env['dir']
  720. if info:
  721. logname = "info.log"
  722. else:
  723. logname = "notice.log"
  724. return os.path.join(datadir, logname)
  725. def getLastBootstrapStatus(self):
  726. """Look through the logs and return the last bootstrap message
  727. received as a 3-tuple of percentage complete, keyword
  728. (optional), and message.
  729. """
  730. logfname = self.getLogfile()
  731. if not os.path.exists(logfname):
  732. return (-200, "no_logfile", "There is no logfile yet.")
  733. percent,keyword,message=-100,"no_message","No bootstrap messages yet."
  734. with open(logfname, 'r') as f:
  735. for line in f:
  736. m = re.search(r'Bootstrapped (\d+)%( \([^\)]*\))?: (.*)', line)
  737. if m:
  738. percent, keyword, message = m.groups()
  739. percent = int(percent)
  740. return (percent, keyword, message)
  741. def isBootstrapped(self):
  742. """Return true iff the logfile says that this instance is
  743. bootstrapped."""
  744. pct, _, _ = self.getLastBootstrapStatus()
  745. return pct == 100
  746. # XXX: document these options
  747. DEFAULTS = {
  748. 'authority': False,
  749. 'bridgeauthority': False,
  750. 'hasbridgeauth': False,
  751. 'relay': False,
  752. 'bridge': False,
  753. 'hs': False,
  754. 'hs_directory': 'hidden_service',
  755. 'hs-hostname': None,
  756. 'connlimit': 60,
  757. 'net_base_dir': get_absolute_net_path(),
  758. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  759. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  760. 'auth_cert_lifetime': 12,
  761. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  762. # we default to ipv6_addr None to support IPv4-only systems
  763. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  764. 'dirserver_flags': 'no-v2',
  765. 'chutney_dir': get_absolute_chutney_path(),
  766. 'torrc_fname': '${dir}/torrc',
  767. 'orport_base': 5000,
  768. 'dirport_base': 7000,
  769. 'controlport_base': 8000,
  770. 'socksport_base': 9000,
  771. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  772. 'bridges': "Bridge bleargh bad torrc file!",
  773. 'core': True,
  774. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  775. # otherwise, poll after that many seconds (can be fractional/decimal)
  776. 'poll_launch_time': None,
  777. # Used when poll_launch_time is None, but RunAsDaemon is not set
  778. # Set low so that we don't interfere with the voting interval
  779. 'poll_launch_time_default': 0.1,
  780. # the number of bytes of random data we send on each connection
  781. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  782. # the number of times each client will connect
  783. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  784. # Do we want every client to connect to every HS, or one client
  785. # to connect to each HS?
  786. # (Clients choose an exit at random, so this doesn't apply to exits.)
  787. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  788. # How long should verify (and similar commands) wait for a successful
  789. # outcome? (seconds)
  790. # We check BOOTSTRAP_TIME for compatibility with old versions of
  791. # test-network.sh
  792. 'bootstrap_time': int(os.environ.get('CHUTNEY_BOOTSTRAP_TIME',
  793. os.environ.get('BOOTSTRAP_TIME',
  794. 60))),
  795. # the PID of the controlling script (for __OwningControllerProcess)
  796. 'controlling_pid': (int(os.environ.get('CHUTNEY_CONTROLLING_PID', 0))
  797. if 'CHUTNEY_CONTROLLING_PID' in os.environ
  798. else None),
  799. # a DNS config file (for ServerDNSResolvConfFile)
  800. 'dns_conf': (os.environ.get('CHUTNEY_DNS_CONF', '/etc/resolv.conf')
  801. if 'CHUTNEY_DNS_CONF' in os.environ
  802. else None),
  803. }
  804. class TorEnviron(chutney.Templating.Environ):
  805. """Subclass of chutney.Templating.Environ to implement commonly-used
  806. substitutions.
  807. Environment fields provided:
  808. orport, controlport, socksport, dirport: *Port torrc option
  809. dir: DataDirectory torrc option
  810. nick: Nickname torrc option
  811. tor_gencert: name or path of the tor-gencert binary
  812. auth_passphrase: obsoleted by CookieAuthentication
  813. torrc_template_path: path to chutney torrc_templates directory
  814. hs_hostname: the hostname of the key generated by a hidden service
  815. owning_controller_process: the __OwningControllerProcess torrc line,
  816. disabled if tor should continue after the script exits
  817. server_dns_resolv_conf: the ServerDNSResolvConfFile torrc line,
  818. disabled if tor should use the default DNS conf.
  819. If the dns_conf file is missing, this option is also disabled:
  820. otherwise, exits would not work due to tor bug #21900.
  821. Environment fields used:
  822. nodenum: chutney's internal node number for the node
  823. tag: a short text string that represents the type of node
  824. orport_base, controlport_base, socksport_base, dirport_base: the
  825. initial port numbers used by nodenum 0. Each additional node adds
  826. 1 to the port numbers.
  827. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  828. present)
  829. chutney_dir: directory of the chutney source code
  830. tor: name or path of the tor binary
  831. net_base_dir: path to the chutney net directory
  832. hs_directory: name of the hidden service directory
  833. nick: Nickname torrc option (debugging only)
  834. hs-hostname (note hyphen): cached hidden service hostname value
  835. controlling_pid: the PID of the controlling process. After this
  836. process exits, the child tor processes will exit
  837. dns_conf: the path to a DNS config file for Tor Exits. If this file
  838. is empty or unreadable, Tor will try 127.0.0.1:53.
  839. """
  840. def __init__(self, parent=None, **kwargs):
  841. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  842. def _get_orport(self, my):
  843. return my['orport_base'] + my['nodenum']
  844. def _get_controlport(self, my):
  845. return my['controlport_base'] + my['nodenum']
  846. def _get_socksport(self, my):
  847. return my['socksport_base'] + my['nodenum']
  848. def _get_dirport(self, my):
  849. return my['dirport_base'] + my['nodenum']
  850. def _get_dir(self, my):
  851. return os.path.abspath(os.path.join(my['net_base_dir'],
  852. "nodes",
  853. "%03d%s" % (
  854. my['nodenum'], my['tag'])))
  855. def _get_nick(self, my):
  856. return "test%03d%s" % (my['nodenum'], my['tag'])
  857. def _get_tor_gencert(self, my):
  858. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  859. def _get_auth_passphrase(self, my):
  860. return self['nick'] # OMG TEH SECURE!
  861. def _get_torrc_template_path(self, my):
  862. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  863. def _get_lockfile(self, my):
  864. return os.path.join(self['dir'], 'lock')
  865. # A hs generates its key on first run,
  866. # so check for it at the last possible moment,
  867. # but cache it in memory to avoid repeatedly reading the file
  868. # XXXX - this is not like the other functions in this class,
  869. # as it reads from a file created by the hidden service
  870. def _get_hs_hostname(self, my):
  871. if my['hs-hostname'] is None:
  872. datadir = my['dir']
  873. # a file containing a single line with the hs' .onion address
  874. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  875. 'hostname')
  876. try:
  877. with open(hs_hostname_file, 'r') as hostnamefp:
  878. hostname = hostnamefp.read()
  879. # the hostname file ends with a newline
  880. hostname = hostname.strip()
  881. my['hs-hostname'] = hostname
  882. except IOError as e:
  883. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  884. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  885. return my['hs-hostname']
  886. def _get_owning_controller_process(self, my):
  887. cpid = my['controlling_pid']
  888. if cpid is None:
  889. cpid = 0
  890. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  891. # if we want to leave the network running, or controlling_pid is 1
  892. # (or invalid)
  893. if (os.environ.get('CHUTNEY_START_TIME', 0) < 0 or
  894. os.environ.get('CHUTNEY_BOOTSTRAP_TIME', 0) < 0 or
  895. os.environ.get('CHUTNEY_STOP_TIME', 0) < 0 or
  896. cpid <= 1):
  897. return '#' + ocp_line
  898. else:
  899. return ocp_line
  900. # the default resolv.conf path is set at compile time
  901. # there's no easy way to get it out of tor, so we use the typical value
  902. DEFAULT_DNS_RESOLV_CONF = "/etc/resolv.conf"
  903. # if we can't find the specified file, use this one as a substitute
  904. OFFLINE_DNS_RESOLV_CONF = "/dev/null"
  905. def _get_server_dns_resolv_conf(self, my):
  906. if my['dns_conf'] == "":
  907. # if the user asked for tor's default
  908. return "#ServerDNSResolvConfFile using tor's compile-time default"
  909. elif my['dns_conf'] is None:
  910. # if there is no DNS conf file set
  911. debug("CHUTNEY_DNS_CONF not specified, using '{}'."
  912. .format(TorEnviron.DEFAULT_DNS_RESOLV_CONF))
  913. dns_conf = TorEnviron.DEFAULT_DNS_RESOLV_CONF
  914. else:
  915. dns_conf = my['dns_conf']
  916. dns_conf = os.path.abspath(dns_conf)
  917. # work around Tor bug #21900, where exits fail when the DNS conf
  918. # file does not exist, or is a broken symlink
  919. # (os.path.exists returns False for broken symbolic links)
  920. if not os.path.exists(dns_conf):
  921. # Issue a warning so the user notices
  922. print("CHUTNEY_DNS_CONF '{}' does not exist, using '{}'."
  923. .format(dns_conf, TorEnviron.OFFLINE_DNS_RESOLV_CONF))
  924. dns_conf = TorEnviron.OFFLINE_DNS_RESOLV_CONF
  925. return "ServerDNSResolvConfFile %s" % (dns_conf)
  926. class Network(object):
  927. """A network of Tor nodes, plus functions to manipulate them
  928. """
  929. def __init__(self, defaultEnviron):
  930. self._nodes = []
  931. self._dfltEnv = defaultEnviron
  932. self._nextnodenum = 0
  933. def _addNode(self, n):
  934. n.setNodenum(self._nextnodenum)
  935. self._nextnodenum += 1
  936. self._nodes.append(n)
  937. def move_aside_nodes_dir(self):
  938. """Move aside the nodes directory, if it exists and is not a link.
  939. Used for backwards-compatibility only: nodes is created as a link to
  940. a new directory with a unique name in the current implementation.
  941. """
  942. nodesdir = get_absolute_nodes_path()
  943. # only move the directory if it exists
  944. if not os.path.exists(nodesdir):
  945. return
  946. # and if it's not a link
  947. if os.path.islink(nodesdir):
  948. return
  949. # subtract 1 second to avoid collisions and get the correct ordering
  950. newdir = get_new_absolute_nodes_path(time.time() - 1)
  951. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  952. os.rename(nodesdir, newdir)
  953. def create_new_nodes_dir(self):
  954. """Create a new directory with a unique name, and symlink it to nodes
  955. """
  956. # for backwards compatibility, move aside the old nodes directory
  957. # (if it's not a link)
  958. self.move_aside_nodes_dir()
  959. # the unique directory we'll create
  960. newnodesdir = get_new_absolute_nodes_path()
  961. # the canonical name we'll link it to
  962. nodeslink = get_absolute_nodes_path()
  963. # this path should be unique and should not exist
  964. if os.path.exists(newnodesdir):
  965. raise RuntimeError(
  966. 'get_new_absolute_nodes_path returned a path that exists')
  967. # if this path exists, it must be a link
  968. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  969. raise RuntimeError(
  970. 'get_absolute_nodes_path returned a path that exists and is not a link')
  971. # create the new, uniquely named directory, and link it to nodes
  972. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  973. # this gets created with mode 0700, that's probably ok
  974. mkdir_p(newnodesdir)
  975. try:
  976. os.unlink(nodeslink)
  977. except OSError as e:
  978. # it's ok if the link doesn't exist, we're just about to make it
  979. if e.errno == errno.ENOENT:
  980. pass
  981. else:
  982. raise
  983. os.symlink(newnodesdir, nodeslink)
  984. def _checkConfig(self):
  985. for n in self._nodes:
  986. n.getBuilder().checkConfig(self)
  987. def configure(self):
  988. self.create_new_nodes_dir()
  989. network = self
  990. altauthlines = []
  991. bridgelines = []
  992. builders = [n.getBuilder() for n in self._nodes]
  993. self._checkConfig()
  994. # XXX don't change node names or types or count if anything is
  995. # XXX running!
  996. for b in builders:
  997. b.preConfig(network)
  998. altauthlines.append(b._getAltAuthLines(
  999. self._dfltEnv['hasbridgeauth']))
  1000. bridgelines.append(b._getBridgeLines())
  1001. self._dfltEnv['authorities'] = "".join(altauthlines)
  1002. self._dfltEnv['bridges'] = "".join(bridgelines)
  1003. for b in builders:
  1004. b.config(network)
  1005. for b in builders:
  1006. b.postConfig(network)
  1007. def status(self):
  1008. statuses = [n.getController().check(listNonRunning=True)
  1009. for n in self._nodes]
  1010. n_ok = len([x for x in statuses if x])
  1011. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  1012. return n_ok == len(self._nodes)
  1013. def restart(self):
  1014. self.stop()
  1015. self.start()
  1016. def start(self):
  1017. # format polling correctly - avoid printing a newline
  1018. sys.stdout.write("Starting nodes")
  1019. sys.stdout.flush()
  1020. rv = all([n.getController().start() for n in self._nodes])
  1021. # now print a newline unconditionally - this stops poll()ing
  1022. # output from being squashed together, at the cost of a blank
  1023. # line in wait()ing output
  1024. print("")
  1025. return rv
  1026. def hup(self):
  1027. print("Sending SIGHUP to nodes")
  1028. return all([n.getController().hup() for n in self._nodes])
  1029. def wait_for_bootstrap(self):
  1030. print("Waiting for nodes to bootstrap...")
  1031. limit = getenv_int("CHUTNEY_START_TIME", 20)
  1032. delay = 0.5
  1033. controllers = [n.getController() for n in self._nodes]
  1034. elapsed = 0.0
  1035. while elapsed < limit:
  1036. all_bootstrapped = True
  1037. for c in controllers:
  1038. if not c.isBootstrapped():
  1039. all_bootstrapped = False
  1040. break
  1041. if all_bootstrapped:
  1042. print("Everything bootstrapped after %s sec"%elapsed)
  1043. return True
  1044. time.sleep(delay)
  1045. elapsed += delay
  1046. print("Bootstrap failed. Node status:")
  1047. for c in controllers:
  1048. c.check(listRunning=False, listNonRunning=True)
  1049. print(c.getLastBootstrapStatus())
  1050. return False
  1051. def stop(self):
  1052. controllers = [n.getController() for n in self._nodes]
  1053. for sig, desc in [(signal.SIGINT, "SIGINT"),
  1054. (signal.SIGINT, "another SIGINT"),
  1055. (signal.SIGKILL, "SIGKILL")]:
  1056. print("Sending %s to nodes" % desc)
  1057. for c in controllers:
  1058. if c.isRunning():
  1059. c.stop(sig=sig)
  1060. print("Waiting for nodes to finish.")
  1061. wrote_dot = False
  1062. for n in range(15):
  1063. time.sleep(1)
  1064. if all(not c.isRunning() for c in controllers):
  1065. # make the output clearer by adding a newline
  1066. if wrote_dot:
  1067. sys.stdout.write("\n")
  1068. sys.stdout.flush()
  1069. # check for stale lock file when Tor crashes
  1070. for c in controllers:
  1071. c.cleanup_lockfile()
  1072. return
  1073. sys.stdout.write(".")
  1074. wrote_dot = True
  1075. sys.stdout.flush()
  1076. for c in controllers:
  1077. c.check(listNonRunning=False)
  1078. # make the output clearer by adding a newline
  1079. if wrote_dot:
  1080. sys.stdout.write("\n")
  1081. sys.stdout.flush()
  1082. def ConfigureNodes(nodelist):
  1083. network = _THE_NETWORK
  1084. for n in nodelist:
  1085. network._addNode(n)
  1086. if n._env['bridgeauthority']:
  1087. network._dfltEnv['hasbridgeauth'] = True
  1088. def getTests():
  1089. tests = []
  1090. chutney_path = get_absolute_chutney_path()
  1091. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  1092. chutney_path += "/"
  1093. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  1094. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  1095. tests.append(os.path.splitext(x)[0])
  1096. return tests
  1097. def usage(network):
  1098. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  1099. "Known commands are: %s" % (
  1100. " ".join(x for x in dir(network)
  1101. if not x.startswith("_"))),
  1102. "Known tests are: %s" % (
  1103. " ".join(getTests()))
  1104. ])
  1105. def exit_on_error(err_msg):
  1106. print("Error: {0}\n".format(err_msg))
  1107. print(usage(_THE_NETWORK))
  1108. sys.exit(1)
  1109. def runConfigFile(verb, data):
  1110. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  1111. Node=Node,
  1112. ConfigureNodes=ConfigureNodes,
  1113. _THE_NETWORK=_THE_NETWORK,
  1114. torrc_option_warn_count=0,
  1115. TORRC_OPTION_WARN_LIMIT=10)
  1116. exec(data, _GLOBALS)
  1117. network = _GLOBALS['_THE_NETWORK']
  1118. # let's check if the verb is a valid test and run it
  1119. if verb in getTests():
  1120. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  1121. try:
  1122. return test_module.run_test(network)
  1123. except AttributeError as e:
  1124. print("Error running test {!r}: {}".format(verb, e))
  1125. return False
  1126. # tell the user we don't know what their verb meant
  1127. if not hasattr(network, verb):
  1128. print(usage(network))
  1129. print("Error: I don't know how to %s." % verb)
  1130. return
  1131. return getattr(network, verb)()
  1132. def parseArgs():
  1133. if len(sys.argv) < 3:
  1134. exit_on_error("Not enough arguments given.")
  1135. if not os.path.isfile(sys.argv[2]):
  1136. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  1137. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  1138. def main():
  1139. global _BASE_ENVIRON
  1140. global _TOR_VERSIONS
  1141. global _TORRC_OPTIONS
  1142. global _THE_NETWORK
  1143. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  1144. # _TOR_VERSIONS gets initialised on demand as a map of
  1145. # "/path/to/tor" => "Tor version ..."
  1146. _TOR_VERSIONS = dict()
  1147. # _TORRC_OPTIONS gets initialised on demand as a map of
  1148. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  1149. # Or it can be pre-populated as a static whitelist of options
  1150. _TORRC_OPTIONS = dict()
  1151. _THE_NETWORK = Network(_BASE_ENVIRON)
  1152. args = parseArgs()
  1153. f = open(args['network_cfg'])
  1154. result = runConfigFile(args['action'], f.read())
  1155. if result is False:
  1156. return -1
  1157. return 0
  1158. if __name__ == '__main__':
  1159. sys.exit(main())