TorNet.py 48 KB

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