TorNet.py 32 KB

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