TorNet.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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 with_statement
  10. # Get verbose tracebacks, so we can diagnose better.
  11. import cgitb
  12. cgitb.enable(format="plain")
  13. import os
  14. import signal
  15. import subprocess
  16. import sys
  17. import re
  18. import errno
  19. import time
  20. import chutney.Templating
  21. import chutney.Traffic
  22. _BASE_ENVIRON = None
  23. _THE_NETWORK = None
  24. def mkdir_p(d, mode=0777):
  25. """Create directory 'd' and all of its parents as needed. Unlike
  26. os.makedirs, does not give an error if d already exists.
  27. """
  28. try:
  29. os.makedirs(d, mode=mode)
  30. except OSError, e:
  31. if e.errno == errno.EEXIST:
  32. return
  33. raise
  34. class Node(object):
  35. """A Node represents a Tor node or a set of Tor nodes. It's created
  36. in a network configuration file.
  37. This class is responsible for holding the user's selected node
  38. configuration, and figuring out how the node needs to be
  39. configured and launched.
  40. """
  41. # Fields:
  42. # _parent
  43. # _env
  44. # _builder
  45. # _controller
  46. ########
  47. # Users are expected to call these:
  48. def __init__(self, parent=None, **kwargs):
  49. self._parent = parent
  50. self._env = self._createEnviron(parent, kwargs)
  51. self._builder = None
  52. self._controller = None
  53. def getN(self, N):
  54. return [Node(self) for _ in xrange(N)]
  55. def specialize(self, **kwargs):
  56. return Node(parent=self, **kwargs)
  57. ######
  58. # Chutney uses these:
  59. def getBuilder(self):
  60. """Return a NodeBuilder instance to set up this node (that is, to
  61. write all the files that need to be in place so that this
  62. node can be run by a NodeController).
  63. """
  64. if self._builder is None:
  65. self._builder = LocalNodeBuilder(self._env)
  66. return self._builder
  67. def getController(self):
  68. """Return a NodeController instance to control this node (that is,
  69. to start it, stop it, see if it's running, etc.)
  70. """
  71. if self._controller is None:
  72. self._controller = LocalNodeController(self._env)
  73. return self._controller
  74. def setNodenum(self, num):
  75. """Assign a value to the 'nodenum' element of this node. Each node
  76. in a network gets its own nodenum.
  77. """
  78. self._env['nodenum'] = num
  79. #####
  80. # These are internal:
  81. def _createEnviron(self, parent, argdict):
  82. """Return an Environ that delegates to the parent node's Environ (if
  83. there is a parent node), or to the default environment.
  84. """
  85. if parent:
  86. parentenv = parent._env
  87. else:
  88. parentenv = self._getDefaultEnviron()
  89. return TorEnviron(parentenv, **argdict)
  90. def _getDefaultEnviron(self):
  91. """Return the default environment. Any variables that we can't find
  92. set for any particular node, we look for here.
  93. """
  94. return _BASE_ENVIRON
  95. class _NodeCommon(object):
  96. """Internal helper class for functionality shared by some NodeBuilders
  97. and some NodeControllers."""
  98. # XXXX maybe this should turn into a mixin.
  99. def __init__(self, env):
  100. self._env = env
  101. def expand(self, pat, includePath=(".",)):
  102. return chutney.Templating.Template(pat, includePath).format(self._env)
  103. def _getTorrcFname(self):
  104. """Return the name of the file where we'll be writing torrc"""
  105. return self.expand("${torrc_fname}")
  106. class NodeBuilder(_NodeCommon):
  107. """Abstract base class. A NodeBuilder is responsible for doing all the
  108. one-time prep needed to set up a node in a network.
  109. """
  110. def __init__(self, env):
  111. _NodeCommon.__init__(self, env)
  112. def checkConfig(self, net):
  113. """Try to format our torrc; raise an exception if we can't.
  114. """
  115. def preConfig(self, net):
  116. """Called on all nodes before any nodes configure: generates keys as
  117. needed.
  118. """
  119. def config(self, net):
  120. """Called to configure a node: creates a torrc file for it."""
  121. def postConfig(self, net):
  122. """Called on each nodes after all nodes configure."""
  123. class NodeController(_NodeCommon):
  124. """Abstract base class. A NodeController is responsible for running a
  125. node on the network.
  126. """
  127. def __init__(self, env):
  128. _NodeCommon.__init__(self, env)
  129. def check(self, listRunning=True, listNonRunning=False):
  130. """See if this node is running, stopped, or crashed. If it's running
  131. and listRunning is set, print a short statement. If it's
  132. stopped and listNonRunning is set, then print a short statement.
  133. If it's crashed, print a statement. Return True if the
  134. node is running, false otherwise.
  135. """
  136. def start(self):
  137. """Try to start this node; return True if we succeeded or it was
  138. already running, False if we failed."""
  139. def stop(self, sig=signal.SIGINT):
  140. """Try to stop this node by sending it the signal 'sig'."""
  141. class LocalNodeBuilder(NodeBuilder):
  142. # Environment members used:
  143. # torrc -- which torrc file to use
  144. # torrc_template_path -- path to search for torrc files and include files
  145. # authority -- bool -- are we an authority?
  146. # bridgeauthority -- bool -- are we a bridge authority?
  147. # relay -- bool -- are we a relay?
  148. # bridge -- bool -- are we a bridge?
  149. # nodenum -- int -- set by chutney -- which unique node index is this?
  150. # dir -- path -- set by chutney -- data directory for this tor
  151. # tor_gencert -- path to tor_gencert binary
  152. # tor -- path to tor binary
  153. # auth_cert_lifetime -- lifetime of authority certs, in months.
  154. # ip -- IP to listen on (used only if authority or bridge)
  155. # ipv6_addr -- IPv6 address to listen on (used only if ipv6 bridge)
  156. # orport, dirport -- (used only if authority)
  157. # fingerprint -- used only if authority
  158. # dirserver_flags -- used only if authority
  159. # nick -- nickname of this router
  160. # Environment members set
  161. # fingerprint -- hex router key fingerprint
  162. # nodenum -- int -- set by chutney -- which unique node index is this?
  163. def __init__(self, env):
  164. NodeBuilder.__init__(self, env)
  165. self._env = env
  166. def _createTorrcFile(self, checkOnly=False):
  167. """Write the torrc file for this node. If checkOnly, just make sure
  168. that the formatting is indeed possible.
  169. """
  170. fn_out = self._getTorrcFname()
  171. torrc_template = self._getTorrcTemplate()
  172. output = torrc_template.format(self._env)
  173. if checkOnly:
  174. # XXXX Is it time-cosuming to format? If so, cache here.
  175. return
  176. with open(fn_out, 'w') as f:
  177. f.write(output)
  178. def _getTorrcTemplate(self):
  179. """Return the template used to write the torrc for this node."""
  180. template_path = self._env['torrc_template_path']
  181. return chutney.Templating.Template("$${include:$torrc}",
  182. includePath=template_path)
  183. def _getFreeVars(self):
  184. """Return a set of the free variables in the torrc template for this
  185. node.
  186. """
  187. template = self._getTorrcTemplate()
  188. return template.freevars(self._env)
  189. def checkConfig(self, net):
  190. """Try to format our torrc; raise an exception if we can't.
  191. """
  192. self._createTorrcFile(checkOnly=True)
  193. def preConfig(self, net):
  194. """Called on all nodes before any nodes configure: generates keys as
  195. needed.
  196. """
  197. self._makeDataDir()
  198. if self._env['authority']:
  199. self._genAuthorityKey()
  200. if self._env['relay']:
  201. self._genRouterKey()
  202. def config(self, net):
  203. """Called to configure a node: creates a torrc file for it."""
  204. self._createTorrcFile()
  205. # self._createScripts()
  206. def postConfig(self, net):
  207. """Called on each nodes after all nodes configure."""
  208. # self.net.addNode(self)
  209. pass
  210. def _makeDataDir(self):
  211. """Create the data directory (with keys subdirectory) for this node.
  212. """
  213. datadir = self._env['dir']
  214. mkdir_p(os.path.join(datadir, 'keys'))
  215. def _genAuthorityKey(self):
  216. """Generate an authority identity and signing key for this authority,
  217. if they do not already exist."""
  218. datadir = self._env['dir']
  219. tor_gencert = self._env['tor_gencert']
  220. lifetime = self._env['auth_cert_lifetime']
  221. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  222. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  223. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  224. addr = self.expand("${ip}:${dirport}")
  225. passphrase = self._env['auth_passphrase']
  226. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  227. return
  228. cmdline = [
  229. tor_gencert,
  230. '--create-identity-key',
  231. '--passphrase-fd', '0',
  232. '-i', idfile,
  233. '-s', skfile,
  234. '-c', certfile,
  235. '-m', str(lifetime),
  236. '-a', addr]
  237. print "Creating identity key %s for %s with %s" % (
  238. idfile, self._env['nick'], " ".join(cmdline))
  239. try:
  240. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  241. except OSError as e:
  242. # only catch file not found error
  243. if e.errno == errno.ENOENT:
  244. print ("Cannot find tor-gencert binary %r. Use "
  245. "CHUTNEY_TOR_GENCERT environment variable to set the "
  246. "path, or put the binary into $PATH.") % tor_gencert
  247. sys.exit(0)
  248. else:
  249. raise
  250. p.communicate(passphrase + "\n")
  251. assert p.returncode == 0 # XXXX BAD!
  252. def _genRouterKey(self):
  253. """Generate an identity key for this router, unless we already have,
  254. and set up the 'fingerprint' entry in the Environ.
  255. """
  256. datadir = self._env['dir']
  257. tor = self._env['tor']
  258. cmdline = [
  259. tor,
  260. "--quiet",
  261. "--list-fingerprint",
  262. "--orport", "1",
  263. "--dirserver",
  264. "xyzzy 127.0.0.1:1 ffffffffffffffffffffffffffffffffffffffff",
  265. "--datadirectory", datadir]
  266. try:
  267. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  268. except OSError as e:
  269. # only catch file not found error
  270. if e.errno == errno.ENOENT:
  271. print ("Cannot find tor binary %r. Use "
  272. "CHUTNEY_TOR environment variable to set the "
  273. "path, or put the binary into $PATH.") % tor
  274. sys.exit(0)
  275. else:
  276. raise
  277. stdout, stderr = p.communicate()
  278. fingerprint = "".join(stdout.split()[1:])
  279. assert re.match(r'^[A-F0-9]{40}$', fingerprint)
  280. self._env['fingerprint'] = fingerprint
  281. def _getAltAuthLines(self, hasbridgeauth=False):
  282. """Return a combination of AlternateDirAuthority,
  283. AlternateHSAuthority and AlternateBridgeAuthority lines for
  284. this Node, appropriately. Non-authorities return ""."""
  285. if not self._env['authority']:
  286. return ""
  287. datadir = self._env['dir']
  288. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  289. v3id = None
  290. with open(certfile, 'r') as f:
  291. for line in f:
  292. if line.startswith("fingerprint"):
  293. v3id = line.split()[1].strip()
  294. break
  295. assert v3id is not None
  296. if self._env['bridgeauthority']:
  297. # Bridge authorities return AlternateBridgeAuthority with
  298. # the 'bridge' flag set.
  299. options = ("AlternateBridgeAuthority",)
  300. self._env['dirserver_flags'] += " bridge"
  301. else:
  302. # Directory authorities return AlternateDirAuthority with
  303. # the 'hs' and 'v3ident' flags set.
  304. # XXXX This next line is needed for 'bridges' but breaks
  305. # 'basic'
  306. if hasbridgeauth:
  307. options = ("AlternateDirAuthority",)
  308. else:
  309. options = ("DirAuthority",)
  310. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  311. authlines = ""
  312. for authopt in options:
  313. authlines += "%s %s orport=%s %s %s:%s %s\n" % (
  314. authopt, self._env['nick'], self._env['orport'],
  315. self._env['dirserver_flags'], self._env['ip'],
  316. self._env['dirport'], self._env['fingerprint'])
  317. return authlines
  318. def _getBridgeLines(self):
  319. """Return potential Bridge line for this Node. Non-bridge
  320. relays return "".
  321. """
  322. if not self._env['bridge']:
  323. return ""
  324. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  325. self._env['orport'])
  326. if self._env['ipv6_addr'] is not None:
  327. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  328. self._env['orport'])
  329. return bridgelines
  330. class LocalNodeController(NodeController):
  331. def __init__(self, env):
  332. NodeController.__init__(self, env)
  333. self._env = env
  334. def getPid(self):
  335. """Assuming that this node has its pidfile in ${dir}/pid, return
  336. the pid of the running process, or None if there is no pid in the
  337. file.
  338. """
  339. pidfile = os.path.join(self._env['dir'], 'pid')
  340. if not os.path.exists(pidfile):
  341. return None
  342. with open(pidfile, 'r') as f:
  343. return int(f.read())
  344. def isRunning(self, pid=None):
  345. """Return true iff this node is running. (If 'pid' is provided, we
  346. assume that the pid provided is the one of this node. Otherwise
  347. we call getPid().
  348. """
  349. if pid is None:
  350. pid = self.getPid()
  351. if pid is None:
  352. return False
  353. try:
  354. os.kill(pid, 0) # "kill 0" == "are you there?"
  355. except OSError, e:
  356. if e.errno == errno.ESRCH:
  357. return False
  358. raise
  359. # okay, so the process exists. Say "True" for now.
  360. # XXXX check if this is really tor!
  361. return True
  362. def check(self, listRunning=True, listNonRunning=False):
  363. """See if this node is running, stopped, or crashed. If it's running
  364. and listRunning is set, print a short statement. If it's
  365. stopped and listNonRunning is set, then print a short statement.
  366. If it's crashed, print a statement. Return True if the
  367. node is running, false otherwise.
  368. """
  369. # XXX Split this into "check" and "print" parts.
  370. pid = self.getPid()
  371. nick = self._env['nick']
  372. datadir = self._env['dir']
  373. if self.isRunning(pid):
  374. if listRunning:
  375. print "%s is running with PID %s" % (nick, pid)
  376. return True
  377. elif os.path.exists(os.path.join(datadir, "core.%s" % pid)):
  378. if listNonRunning:
  379. print "%s seems to have crashed, and left core file core.%s" % (
  380. nick, pid)
  381. return False
  382. else:
  383. if listNonRunning:
  384. print "%s is stopped" % nick
  385. return False
  386. def hup(self):
  387. """Send a SIGHUP to this node, if it's running."""
  388. pid = self.getPid()
  389. nick = self._env['nick']
  390. if self.isRunning(pid):
  391. print "Sending sighup to %s" % nick
  392. os.kill(pid, signal.SIGHUP)
  393. return True
  394. else:
  395. print "%s is not running" % nick
  396. return False
  397. def start(self):
  398. """Try to start this node; return True if we succeeded or it was
  399. already running, False if we failed."""
  400. if self.isRunning():
  401. print "%s is already running" % self._env['nick']
  402. return True
  403. tor_path = self._env['tor']
  404. torrc = self._getTorrcFname()
  405. cmdline = [
  406. tor_path,
  407. "--quiet",
  408. "-f", torrc,
  409. ]
  410. try:
  411. p = subprocess.Popen(cmdline)
  412. except OSError as e:
  413. # only catch file not found error
  414. if e.errno == errno.ENOENT:
  415. print ("Cannot find tor binary %r. Use CHUTNEY_TOR "
  416. "environment variable to set the path, or put the binary "
  417. "into $PATH.") % tor_path
  418. sys.exit(0)
  419. else:
  420. raise
  421. # XXXX this requires that RunAsDaemon is set.
  422. p.wait()
  423. if p.returncode != 0:
  424. print "Couldn't launch %s (%s): %s" % (self._env['nick'],
  425. " ".join(cmdline),
  426. p.returncode)
  427. return False
  428. return True
  429. def stop(self, sig=signal.SIGINT):
  430. """Try to stop this node by sending it the signal 'sig'."""
  431. pid = self.getPid()
  432. if not self.isRunning(pid):
  433. print "%s is not running" % self._env['nick']
  434. return
  435. os.kill(pid, sig)
  436. def cleanup_lockfile(self):
  437. lf = self._env['lockfile']
  438. if self.isRunning() or (not os.path.exists(lf)):
  439. return
  440. print 'Removing stale lock file for {0} ...'.format(
  441. self._env['nick'])
  442. os.remove(lf)
  443. DEFAULTS = {
  444. 'authority': False,
  445. 'bridgeauthority': False,
  446. 'hasbridgeauth': False,
  447. 'relay': False,
  448. 'bridge': False,
  449. 'connlimit': 60,
  450. 'net_base_dir': 'net',
  451. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  452. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  453. 'auth_cert_lifetime': 12,
  454. 'ip': '127.0.0.1',
  455. 'ipv6_addr': None,
  456. 'dirserver_flags': 'no-v2',
  457. 'chutney_dir': '.',
  458. 'torrc_fname': '${dir}/torrc',
  459. 'orport_base': 5000,
  460. 'dirport_base': 7000,
  461. 'controlport_base': 8000,
  462. 'socksport_base': 9000,
  463. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  464. 'bridges': "Bridge bleargh bad torrc file!",
  465. 'core': True,
  466. }
  467. class TorEnviron(chutney.Templating.Environ):
  468. """Subclass of chutney.Templating.Environ to implement commonly-used
  469. substitutions.
  470. Environment fields provided:
  471. orport, controlport, socksport, dirport:
  472. dir:
  473. nick:
  474. tor_gencert:
  475. auth_passphrase:
  476. torrc_template_path:
  477. Environment fields used:
  478. nodenum
  479. tag
  480. orport_base, controlport_base, socksport_base, dirport_base
  481. chutney_dir
  482. tor
  483. XXXX document the above. Or document all fields in one place?
  484. """
  485. def __init__(self, parent=None, **kwargs):
  486. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  487. def _get_orport(self, my):
  488. return my['orport_base'] + my['nodenum']
  489. def _get_controlport(self, my):
  490. return my['controlport_base'] + my['nodenum']
  491. def _get_socksport(self, my):
  492. return my['socksport_base'] + my['nodenum']
  493. def _get_dirport(self, my):
  494. return my['dirport_base'] + my['nodenum']
  495. def _get_dir(self, my):
  496. return os.path.abspath(os.path.join(my['net_base_dir'],
  497. "nodes",
  498. "%03d%s" % (my['nodenum'], my['tag'])))
  499. def _get_nick(self, my):
  500. return "test%03d%s" % (my['nodenum'], my['tag'])
  501. def _get_tor_gencert(self, my):
  502. if my['tor-gencert']:
  503. return my['tor-gencert']
  504. else:
  505. return '{0}-gencert'.format(my['tor'])
  506. def _get_auth_passphrase(self, my):
  507. return self['nick'] # OMG TEH SECURE!
  508. def _get_torrc_template_path(self, my):
  509. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  510. def _get_lockfile(self, my):
  511. return os.path.join(self['dir'], 'lock')
  512. class Network(object):
  513. """A network of Tor nodes, plus functions to manipulate them
  514. """
  515. def __init__(self, defaultEnviron):
  516. self._nodes = []
  517. self._dfltEnv = defaultEnviron
  518. self._nextnodenum = 0
  519. def _addNode(self, n):
  520. n.setNodenum(self._nextnodenum)
  521. self._nextnodenum += 1
  522. self._nodes.append(n)
  523. def _checkConfig(self):
  524. for n in self._nodes:
  525. n.getBuilder().checkConfig(self)
  526. def configure(self):
  527. network = self
  528. altauthlines = []
  529. bridgelines = []
  530. builders = [n.getBuilder() for n in self._nodes]
  531. self._checkConfig()
  532. # XXX don't change node names or types or count if anything is
  533. # XXX running!
  534. for b in builders:
  535. b.preConfig(network)
  536. altauthlines.append(b._getAltAuthLines(
  537. self._dfltEnv['hasbridgeauth']))
  538. bridgelines.append(b._getBridgeLines())
  539. self._dfltEnv['authorities'] = "".join(altauthlines)
  540. self._dfltEnv['bridges'] = "".join(bridgelines)
  541. for b in builders:
  542. b.config(network)
  543. for b in builders:
  544. b.postConfig(network)
  545. def status(self):
  546. statuses = [n.getController().check() for n in self._nodes]
  547. n_ok = len([x for x in statuses if x])
  548. print "%d/%d nodes are running" % (n_ok, len(self._nodes))
  549. if n_ok != len(self._nodes):
  550. return False
  551. return True
  552. def restart(self):
  553. self.stop()
  554. self.start()
  555. def start(self):
  556. print "Starting nodes"
  557. return all([n.getController().start() for n in self._nodes])
  558. def hup(self):
  559. print "Sending SIGHUP to nodes"
  560. return all([n.getController().hup() for n in self._nodes])
  561. def stop(self):
  562. controllers = [n.getController() for n in self._nodes]
  563. for sig, desc in [(signal.SIGINT, "SIGINT"),
  564. (signal.SIGINT, "another SIGINT"),
  565. (signal.SIGKILL, "SIGKILL")]:
  566. print "Sending %s to nodes" % desc
  567. for c in controllers:
  568. if c.isRunning():
  569. c.stop(sig=sig)
  570. print "Waiting for nodes to finish."
  571. for n in xrange(15):
  572. time.sleep(1)
  573. if all(not c.isRunning() for c in controllers):
  574. # check for stale lock file when Tor crashes
  575. for c in controllers:
  576. c.cleanup_lockfile()
  577. return
  578. sys.stdout.write(".")
  579. sys.stdout.flush()
  580. for c in controllers:
  581. c.check(listNonRunning=False)
  582. def verify(self):
  583. sys.stdout.write("Verifying data transmission: ")
  584. sys.stdout.flush()
  585. status = self._verify_traffic()
  586. if status:
  587. print("Success")
  588. else:
  589. print("Failure")
  590. return status
  591. def _verify_traffic(self):
  592. """Verify (parts of) the network by sending traffic through it
  593. and verify what is received."""
  594. LISTEN_PORT = 4747 # FIXME: Do better! Note the default exit policy.
  595. DATALEN = 10 * 1024 # Octets.
  596. TIMEOUT = 3 # Seconds.
  597. with open('/dev/urandom', 'r') as randfp:
  598. tmpdata = randfp.read(DATALEN)
  599. bind_to = ('127.0.0.1', LISTEN_PORT)
  600. tt = chutney.Traffic.TrafficTester(bind_to, tmpdata, TIMEOUT)
  601. for op in filter(lambda n: n._env['tag'] == 'c', self._nodes):
  602. tt.add(chutney.Traffic.Source(tt, bind_to, tmpdata,
  603. ('localhost', int(op._env['socksport']))))
  604. return tt.run()
  605. def ConfigureNodes(nodelist):
  606. network = _THE_NETWORK
  607. for n in nodelist:
  608. network._addNode(n)
  609. if n._env['bridgeauthority']:
  610. network._dfltEnv['hasbridgeauth'] = True
  611. def usage(network):
  612. return "\n".join(["Usage: chutney {command} {networkfile}",
  613. "Known commands are: %s" % (
  614. " ".join(x for x in dir(network) if not x.startswith("_")))])
  615. def runConfigFile(verb, f):
  616. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  617. Node=Node,
  618. ConfigureNodes=ConfigureNodes,
  619. _THE_NETWORK=_THE_NETWORK)
  620. exec f in _GLOBALS
  621. network = _GLOBALS['_THE_NETWORK']
  622. if not hasattr(network, verb):
  623. print usage(network)
  624. print "Error: I don't know how to %s." % verb
  625. return
  626. return getattr(network, verb)()
  627. def main():
  628. global _BASE_ENVIRON
  629. global _THE_NETWORK
  630. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  631. _THE_NETWORK = Network(_BASE_ENVIRON)
  632. if len(sys.argv) < 3:
  633. print usage(_THE_NETWORK)
  634. print "Error: Not enough arguments given."
  635. sys.exit(1)
  636. f = open(sys.argv[2])
  637. result = runConfigFile(sys.argv[1], f)
  638. if result is False:
  639. return -1
  640. return 0
  641. if __name__ == '__main__':
  642. sys.exit(main())