TorNet.py 32 KB

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