TorNet.py 33 KB

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