TorNet.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. # Copyright 2013 The Tor Project
  5. #
  6. # You may do anything with this work that copyright law would normally
  7. # restrict, so long as you retain the above notice(s) and this license
  8. # in all redistributed copies and derived works. There is no warranty.
  9. from __future__ import 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. def mkdir_p(d, mode=0777):
  23. """Create directory 'd' and all of its parents as needed. Unlike
  24. os.makedirs, does not give an error if d already exists.
  25. """
  26. try:
  27. os.makedirs(d,mode=mode)
  28. except OSError, e:
  29. if e.errno == errno.EEXIST:
  30. return
  31. raise
  32. class Node(object):
  33. """A Node represents a Tor node or a set of Tor nodes. It's created
  34. in a network configuration file.
  35. This class is responsible for holding the user's selected node
  36. configuration, and figuring out how the node needs to be
  37. configured and launched.
  38. """
  39. ## Fields:
  40. # _parent
  41. # _env
  42. # _builder
  43. # _controller
  44. ########
  45. # Users are expected to call these:
  46. def __init__(self, parent=None, **kwargs):
  47. self._parent = parent
  48. self._env = self._createEnviron(parent, kwargs)
  49. self._builder = None
  50. self._controller = None
  51. def getN(self, N):
  52. return [ Node(self) for _ in xrange(N) ]
  53. def specialize(self, **kwargs):
  54. return Node(parent=self, **kwargs)
  55. ######
  56. # Chutney uses these:
  57. def getBuilder(self):
  58. """Return a NodeBuilder instance to set up this node (that is, to
  59. write all the files that need to be in place so that this
  60. node can be run by a NodeController).
  61. """
  62. if self._builder is None:
  63. self._builder = LocalNodeBuilder(self._env)
  64. return self._builder
  65. def getController(self):
  66. """Return a NodeController instance to control this node (that is,
  67. to start it, stop it, see if it's running, etc.)
  68. """
  69. if self._controller is None:
  70. self._controller = LocalNodeController(self._env)
  71. return self._controller
  72. def setNodenum(self, num):
  73. """Assign a value to the 'nodenum' element of this node. Each node
  74. in a network gets its own nodenum.
  75. """
  76. self._env['nodenum'] = num
  77. #####
  78. # These are internal:
  79. def _createEnviron(self, parent, argdict):
  80. """Return an Environ that delegates to the parent node's Environ (if
  81. there is a parent node), or to the default environment.
  82. """
  83. if parent:
  84. parentenv = parent._env
  85. else:
  86. parentenv = self._getDefaultEnviron()
  87. return TorEnviron(parentenv, **argdict)
  88. def _getDefaultEnviron(self):
  89. """Return the default environment. Any variables that we can't find
  90. set for any particular node, we look for here.
  91. """
  92. return _BASE_ENVIRON
  93. class _NodeCommon(object):
  94. """Internal helper class for functionality shared by some NodeBuilders
  95. and some NodeControllers."""
  96. # XXXX maybe this should turn into a mixin.
  97. def __init__(self, env):
  98. self._env = env
  99. def expand(self, pat, includePath=(".",)):
  100. return chutney.Templating.Template(pat, includePath).format(self._env)
  101. def _getTorrcFname(self):
  102. """Return the name of the file where we'll be writing torrc"""
  103. return self.expand("${torrc_fname}")
  104. class NodeBuilder(_NodeCommon):
  105. """Abstract base class. A NodeBuilder is responsible for doing all the
  106. one-time prep needed to set up a node in a network.
  107. """
  108. def __init__(self, env):
  109. _NodeCommon.__init__(self, env)
  110. def checkConfig(self, net):
  111. """Try to format our torrc; raise an exception if we can't.
  112. """
  113. def preConfig(self, net):
  114. """Called on all nodes before any nodes configure: generates keys as
  115. needed.
  116. """
  117. def config(self, net):
  118. """Called to configure a node: creates a torrc file for it."""
  119. def postConfig(self, net):
  120. """Called on each nodes after all nodes configure."""
  121. class NodeController(_NodeCommon):
  122. """Abstract base class. A NodeController is responsible for running a
  123. node on the network.
  124. """
  125. def __init__(self, env):
  126. _NodeCommon.__init__(self, env)
  127. def check(self, listRunning=True, listNonRunning=False):
  128. """See if this node is running, stopped, or crashed. If it's running
  129. and listRunning is set, print a short statement. If it's
  130. stopped and listNonRunning is set, then print a short statement.
  131. If it's crashed, print a statement. Return True if the
  132. node is running, false otherwise.
  133. """
  134. def start(self):
  135. """Try to start this node; return True if we succeeded or it was
  136. already running, False if we failed."""
  137. def stop(self, sig=signal.SIGINT):
  138. """Try to stop this node by sending it the signal 'sig'."""
  139. class LocalNodeBuilder(NodeBuilder):
  140. ## Environment members used:
  141. # torrc -- which torrc file to use
  142. # torrc_template_path -- path to search for torrc files and include files
  143. # authority -- bool -- are we an authority?
  144. # bridgeauthority -- bool -- are we a bridge authority?
  145. # relay -- bool -- are we a relay?
  146. # bridge -- bool -- are we a bridge?
  147. # nodenum -- int -- set by chutney -- which unique node index is this?
  148. # dir -- path -- set by chutney -- data directory for this tor
  149. # tor_gencert -- path to tor_gencert binary
  150. # tor -- path to tor binary
  151. # auth_cert_lifetime -- lifetime of authority certs, in months.
  152. # ip -- IP to listen on (used only if authority or bridge)
  153. # ipv6_addr -- IPv6 address to listen on (used only if ipv6 bridge)
  154. # orport, dirport -- (used only if authority)
  155. # fingerprint -- used only if authority
  156. # dirserver_flags -- used only if authority
  157. # nick -- nickname of this router
  158. ## Environment members set
  159. # fingerprint -- hex router key fingerprint
  160. # nodenum -- int -- set by chutney -- which unique node index is this?
  161. def __init__(self, env):
  162. NodeBuilder.__init__(self, env)
  163. self._env = env
  164. def _createTorrcFile(self, checkOnly=False):
  165. """Write the torrc file for this node. If checkOnly, just make sure
  166. that the formatting is indeed possible.
  167. """
  168. fn_out = self._getTorrcFname()
  169. torrc_template = self._getTorrcTemplate()
  170. output = torrc_template.format(self._env)
  171. if checkOnly:
  172. # XXXX Is it time-cosuming to format? If so, cache here.
  173. return
  174. with open(fn_out, 'w') as f:
  175. f.write(output)
  176. def _getTorrcTemplate(self):
  177. """Return the template used to write the torrc for this node."""
  178. template_path = self._env['torrc_template_path']
  179. return chutney.Templating.Template("$${include:$torrc}",
  180. includePath=template_path)
  181. def _getFreeVars(self):
  182. """Return a set of the free variables in the torrc template for this
  183. node.
  184. """
  185. template = self._getTorrcTemplate()
  186. return template.freevars(self._env)
  187. def checkConfig(self, net):
  188. """Try to format our torrc; raise an exception if we can't.
  189. """
  190. self._createTorrcFile(checkOnly=True)
  191. def preConfig(self, net):
  192. """Called on all nodes before any nodes configure: generates keys as
  193. needed.
  194. """
  195. self._makeDataDir()
  196. if self._env['authority']:
  197. self._genAuthorityKey()
  198. if self._env['relay']:
  199. self._genRouterKey()
  200. def config(self, net):
  201. """Called to configure a node: creates a torrc file for it."""
  202. self._createTorrcFile()
  203. #self._createScripts()
  204. def postConfig(self, net):
  205. """Called on each nodes after all nodes configure."""
  206. #self.net.addNode(self)
  207. pass
  208. def _makeDataDir(self):
  209. """Create the data directory (with keys subdirectory) for this node.
  210. """
  211. datadir = self._env['dir']
  212. mkdir_p(os.path.join(datadir, 'keys'))
  213. def _genAuthorityKey(self):
  214. """Generate an authority identity and signing key for this authority,
  215. if they do not already exist."""
  216. datadir = self._env['dir']
  217. tor_gencert = self._env['tor_gencert']
  218. lifetime = self._env['auth_cert_lifetime']
  219. idfile = os.path.join(datadir,'keys',"authority_identity_key")
  220. skfile = os.path.join(datadir,'keys',"authority_signing_key")
  221. certfile = os.path.join(datadir,'keys',"authority_certificate")
  222. addr = self.expand("${ip}:${dirport}")
  223. passphrase = self._env['auth_passphrase']
  224. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  225. return
  226. cmdline = [
  227. tor_gencert,
  228. '--create-identity-key',
  229. '--passphrase-fd', '0',
  230. '-i', idfile,
  231. '-s', skfile,
  232. '-c', certfile,
  233. '-m', str(lifetime),
  234. '-a', addr]
  235. print "Creating identity key %s for %s with %s"%(
  236. idfile,self._env['nick']," ".join(cmdline))
  237. try:
  238. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  239. except OSError as e:
  240. # only catch file not found error
  241. if e.errno == errno.ENOENT:
  242. print ("Cannot find tor-gencert binary %r. Use "
  243. "CHUTNEY_TOR_GENCERT environment variable to set the "
  244. "path, or put the binary into $PATH.")%tor_gencert
  245. sys.exit(0)
  246. else:
  247. raise
  248. p.communicate(passphrase+"\n")
  249. assert p.returncode == 0 #XXXX BAD!
  250. def _genRouterKey(self):
  251. """Generate an identity key for this router, unless we already have,
  252. and set up the 'fingerprint' entry in the Environ.
  253. """
  254. datadir = self._env['dir']
  255. tor = self._env['tor']
  256. cmdline = [
  257. tor,
  258. "--quiet",
  259. "--list-fingerprint",
  260. "--orport", "1",
  261. "--dirserver",
  262. "xyzzy 127.0.0.1:1 ffffffffffffffffffffffffffffffffffffffff",
  263. "--datadirectory", datadir ]
  264. try:
  265. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  266. except OSError as e:
  267. # only catch file not found error
  268. if e.errno == errno.ENOENT:
  269. print ("Cannot find tor binary %r. Use "
  270. "CHUTNEY_TOR environment variable to set the "
  271. "path, or put the binary into $PATH.")%tor
  272. sys.exit(0)
  273. else:
  274. raise
  275. stdout, stderr = p.communicate()
  276. fingerprint = "".join(stdout.split()[1:])
  277. assert re.match(r'^[A-F0-9]{40}$', fingerprint)
  278. self._env['fingerprint'] = fingerprint
  279. def _getAltAuthLines(self, hasbridgeauth=False):
  280. """Return a combination of AlternateDirAuthority,
  281. AlternateHSAuthority and AlternateBridgeAuthority lines for
  282. this Node, appropriately. Non-authorities return ""."""
  283. if not self._env['authority']:
  284. return ""
  285. datadir = self._env['dir']
  286. certfile = os.path.join(datadir,'keys',"authority_certificate")
  287. v3id = None
  288. with open(certfile, 'r') as f:
  289. for line in f:
  290. if line.startswith("fingerprint"):
  291. v3id = line.split()[1].strip()
  292. break
  293. assert v3id is not None
  294. if self._env['bridgeauthority']:
  295. # Bridge authorities return AlternateBridgeAuthority with
  296. # the 'bridge' flag set.
  297. options = ("AlternateBridgeAuthority",)
  298. self._env['dirserver_flags'] += " bridge"
  299. else:
  300. # Directory authorities return AlternateDirAuthority with
  301. # the 'hs' and 'v3ident' flags set.
  302. # XXXX This next line is needed for 'bridges' but breaks
  303. # 'basic'
  304. if hasbridgeauth:
  305. options = ("AlternateDirAuthority",)
  306. else:
  307. options = ("DirAuthority",)
  308. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  309. authlines = ""
  310. for authopt in options:
  311. authlines += "%s %s orport=%s %s %s:%s %s\n" %(
  312. authopt, self._env['nick'], self._env['orport'],
  313. self._env['dirserver_flags'], self._env['ip'],
  314. self._env['dirport'], self._env['fingerprint'])
  315. return authlines
  316. def _getBridgeLines(self):
  317. """Return potential Bridge line for this Node. Non-bridge
  318. relays return "".
  319. """
  320. if not self._env['bridge']:
  321. return ""
  322. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  323. self._env['orport'])
  324. if self._env['ipv6_addr'] is not None:
  325. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  326. self._env['orport'])
  327. return bridgelines
  328. class LocalNodeController(NodeController):
  329. def __init__(self, env):
  330. NodeController.__init__(self, env)
  331. self._env = env
  332. def getPid(self):
  333. """Assuming that this node has its pidfile in ${dir}/pid, return
  334. the pid of the running process, or None if there is no pid in the
  335. file.
  336. """
  337. pidfile = os.path.join(self._env['dir'], 'pid')
  338. if not os.path.exists(pidfile):
  339. return None
  340. with open(pidfile, 'r') as f:
  341. return int(f.read())
  342. def isRunning(self, pid=None):
  343. """Return true iff this node is running. (If 'pid' is provided, we
  344. assume that the pid provided is the one of this node. Otherwise
  345. we call getPid().
  346. """
  347. if pid is None:
  348. pid = self.getPid()
  349. if pid is None:
  350. return False
  351. try:
  352. os.kill(pid, 0) # "kill 0" == "are you there?"
  353. except OSError, e:
  354. if e.errno == errno.ESRCH:
  355. return False
  356. raise
  357. # okay, so the process exists. Say "True" for now.
  358. # XXXX check if this is really tor!
  359. return True
  360. def check(self, listRunning=True, listNonRunning=False):
  361. """See if this node is running, stopped, or crashed. If it's running
  362. and listRunning is set, print a short statement. If it's
  363. stopped and listNonRunning is set, then print a short statement.
  364. If it's crashed, print a statement. Return True if the
  365. node is running, false otherwise.
  366. """
  367. # XXX Split this into "check" and "print" parts.
  368. pid = self.getPid()
  369. running = self.isRunning(pid)
  370. nick = self._env['nick']
  371. dir = self._env['dir']
  372. if running:
  373. if listRunning:
  374. print "%s is running with PID %s"%(nick,pid)
  375. return True
  376. elif os.path.exists(os.path.join(dir, "core.%s"%pid)):
  377. if listNonRunning:
  378. print "%s seems to have crashed, and left core file core.%s"%(
  379. nick,pid)
  380. return False
  381. else:
  382. if listNonRunning:
  383. print "%s is stopped"%nick
  384. return False
  385. def hup(self):
  386. """Send a SIGHUP to this node, if it's running."""
  387. pid = self.getPid()
  388. running = self.isRunning(pid)
  389. nick = self._env['nick']
  390. if running:
  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())