TorNet.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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. import cgitb
  12. import os
  13. import signal
  14. import subprocess
  15. import sys
  16. import re
  17. import errno
  18. import time
  19. import shutil
  20. import importlib
  21. import chutney.Templating
  22. import chutney.Traffic
  23. _BASE_ENVIRON = None
  24. _TORRC_OPTIONS = None
  25. _THE_NETWORK = None
  26. # Get verbose tracebacks, so we can diagnose better.
  27. cgitb.enable(format="plain")
  28. def mkdir_p(d, mode=511):
  29. """Create directory 'd' and all of its parents as needed. Unlike
  30. os.makedirs, does not give an error if d already exists.
  31. 511 is the decimal representation of the octal number 0777. Since
  32. python2 only supports 0777 and python3 only supports 0o777, we can use
  33. neither.
  34. """
  35. try:
  36. os.makedirs(d, mode=mode)
  37. except OSError as e:
  38. if e.errno == errno.EEXIST:
  39. return
  40. raise
  41. class Node(object):
  42. """A Node represents a Tor node or a set of Tor nodes. It's created
  43. in a network configuration file.
  44. This class is responsible for holding the user's selected node
  45. configuration, and figuring out how the node needs to be
  46. configured and launched.
  47. """
  48. # Fields:
  49. # _parent
  50. # _env
  51. # _builder
  52. # _controller
  53. ########
  54. # Users are expected to call these:
  55. def __init__(self, parent=None, **kwargs):
  56. self._parent = parent
  57. self._env = self._createEnviron(parent, kwargs)
  58. self._builder = None
  59. self._controller = None
  60. def getN(self, N):
  61. return [Node(self) for _ in range(N)]
  62. def specialize(self, **kwargs):
  63. return Node(parent=self, **kwargs)
  64. ######
  65. # Chutney uses these:
  66. def getBuilder(self):
  67. """Return a NodeBuilder instance to set up this node (that is, to
  68. write all the files that need to be in place so that this
  69. node can be run by a NodeController).
  70. """
  71. if self._builder is None:
  72. self._builder = LocalNodeBuilder(self._env)
  73. return self._builder
  74. def getController(self):
  75. """Return a NodeController instance to control this node (that is,
  76. to start it, stop it, see if it's running, etc.)
  77. """
  78. if self._controller is None:
  79. self._controller = LocalNodeController(self._env)
  80. return self._controller
  81. def setNodenum(self, num):
  82. """Assign a value to the 'nodenum' element of this node. Each node
  83. in a network gets its own nodenum.
  84. """
  85. self._env['nodenum'] = num
  86. #####
  87. # These are internal:
  88. def _createEnviron(self, parent, argdict):
  89. """Return an Environ that delegates to the parent node's Environ (if
  90. there is a parent node), or to the default environment.
  91. """
  92. if parent:
  93. parentenv = parent._env
  94. else:
  95. parentenv = self._getDefaultEnviron()
  96. return TorEnviron(parentenv, **argdict)
  97. def _getDefaultEnviron(self):
  98. """Return the default environment. Any variables that we can't find
  99. set for any particular node, we look for here.
  100. """
  101. return _BASE_ENVIRON
  102. class _NodeCommon(object):
  103. """Internal helper class for functionality shared by some NodeBuilders
  104. and some NodeControllers."""
  105. # XXXX maybe this should turn into a mixin.
  106. def __init__(self, env):
  107. self._env = env
  108. def expand(self, pat, includePath=(".",)):
  109. return chutney.Templating.Template(pat, includePath).format(self._env)
  110. def _getTorrcFname(self):
  111. """Return the name of the file where we'll be writing torrc"""
  112. return self.expand("${torrc_fname}")
  113. class NodeBuilder(_NodeCommon):
  114. """Abstract base class. A NodeBuilder is responsible for doing all the
  115. one-time prep needed to set up a node in a network.
  116. """
  117. def __init__(self, env):
  118. _NodeCommon.__init__(self, env)
  119. def checkConfig(self, net):
  120. """Try to format our torrc; raise an exception if we can't.
  121. """
  122. def preConfig(self, net):
  123. """Called on all nodes before any nodes configure: generates keys as
  124. needed.
  125. """
  126. def config(self, net):
  127. """Called to configure a node: creates a torrc file for it."""
  128. def postConfig(self, net):
  129. """Called on each nodes after all nodes configure."""
  130. class NodeController(_NodeCommon):
  131. """Abstract base class. A NodeController is responsible for running a
  132. node on the network.
  133. """
  134. def __init__(self, env):
  135. _NodeCommon.__init__(self, env)
  136. def check(self, listRunning=True, listNonRunning=False):
  137. """See if this node is running, stopped, or crashed. If it's running
  138. and listRunning is set, print a short statement. If it's
  139. stopped and listNonRunning is set, then print a short statement.
  140. If it's crashed, print a statement. Return True if the
  141. node is running, false otherwise.
  142. """
  143. def start(self):
  144. """Try to start this node; return True if we succeeded or it was
  145. already running, False if we failed."""
  146. def stop(self, sig=signal.SIGINT):
  147. """Try to stop this node by sending it the signal 'sig'."""
  148. class LocalNodeBuilder(NodeBuilder):
  149. # Environment members used:
  150. # torrc -- which torrc file to use
  151. # torrc_template_path -- path to search for torrc files and include files
  152. # authority -- bool -- are we an authority?
  153. # bridgeauthority -- bool -- are we a bridge authority?
  154. # relay -- bool -- are we a relay?
  155. # bridge -- bool -- are we a bridge?
  156. # hs -- bool -- are we a hidden service?
  157. # nodenum -- int -- set by chutney -- which unique node index is this?
  158. # dir -- path -- set by chutney -- data directory for this tor
  159. # tor_gencert -- path to tor_gencert binary
  160. # tor -- path to tor binary
  161. # auth_cert_lifetime -- lifetime of authority certs, in months.
  162. # ip -- IP to listen on (used only if authority or bridge)
  163. # ipv6_addr -- IPv6 address to listen on (used only if ipv6 bridge)
  164. # orport, dirport -- (used only if authority)
  165. # fingerprint -- used only if authority
  166. # dirserver_flags -- used only if authority
  167. # nick -- nickname of this router
  168. # Environment members set
  169. # fingerprint -- hex router key fingerprint
  170. # nodenum -- int -- set by chutney -- which unique node index is this?
  171. def __init__(self, env):
  172. NodeBuilder.__init__(self, env)
  173. self._env = env
  174. def _createTorrcFile(self, checkOnly=False):
  175. """Write the torrc file for this node, disabling any options
  176. that are not supported by env's tor binary using comments.
  177. If checkOnly, just make sure that the formatting is indeed
  178. possible.
  179. """
  180. fn_out = self._getTorrcFname()
  181. torrc_template = self._getTorrcTemplate()
  182. output = torrc_template.format(self._env)
  183. if checkOnly:
  184. # XXXX Is it time-consuming to format? If so, cache here.
  185. return
  186. # now filter the options we're about to write, commenting out
  187. # the options that the current tor binary doesn't support
  188. tor = self._env['tor']
  189. # find the options the current tor binary supports, and cache them
  190. if tor not in _TORRC_OPTIONS:
  191. # Note: some versions of tor (e.g. 0.2.4.23) require
  192. # --list-torrc-options to be the first argument
  193. cmdline = [
  194. tor,
  195. "--list-torrc-options",
  196. "--hush"]
  197. try:
  198. opts = subprocess.check_output(cmdline, 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 or
  232. sline[0] == '#' or
  233. 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 and
  262. hidden service directories as 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. torrc = self._getTorrcFname()
  339. cmdline = [
  340. tor,
  341. "--quiet",
  342. "--ignore-missing-torrc",
  343. "-f", torrc,
  344. "--list-fingerprint",
  345. "--orport", "1",
  346. "--datadirectory", datadir]
  347. try:
  348. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  349. except OSError as e:
  350. # only catch file not found error
  351. if e.errno == errno.ENOENT:
  352. print("Cannot find tor binary %r. Use "
  353. "CHUTNEY_TOR environment variable to set the "
  354. "path, or put the binary into $PATH." % tor)
  355. sys.exit(0)
  356. else:
  357. raise
  358. stdout, stderr = p.communicate()
  359. fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
  360. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  361. print(("Error when calling %r. It gave %r as a fingerprint "
  362. " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
  363. sys.exit(1)
  364. self._env['fingerprint'] = fingerprint
  365. def _getAltAuthLines(self, hasbridgeauth=False):
  366. """Return a combination of AlternateDirAuthority,
  367. AlternateHSAuthority and AlternateBridgeAuthority lines for
  368. this Node, appropriately. Non-authorities return ""."""
  369. if not self._env['authority']:
  370. return ""
  371. datadir = self._env['dir']
  372. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  373. v3id = None
  374. with open(certfile, 'r') as f:
  375. for line in f:
  376. if line.startswith("fingerprint"):
  377. v3id = line.split()[1].strip()
  378. break
  379. assert v3id is not None
  380. if self._env['bridgeauthority']:
  381. # Bridge authorities return AlternateBridgeAuthority with
  382. # the 'bridge' flag set.
  383. options = ("AlternateBridgeAuthority",)
  384. self._env['dirserver_flags'] += " bridge"
  385. else:
  386. # Directory authorities return AlternateDirAuthority with
  387. # the 'hs' and 'v3ident' flags set.
  388. # XXXX This next line is needed for 'bridges' but breaks
  389. # 'basic'
  390. if hasbridgeauth:
  391. options = ("AlternateDirAuthority",)
  392. else:
  393. options = ("DirAuthority",)
  394. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  395. authlines = ""
  396. for authopt in options:
  397. authlines += "%s %s orport=%s %s %s:%s %s\n" % (
  398. authopt, self._env['nick'], self._env['orport'],
  399. self._env['dirserver_flags'], self._env['ip'],
  400. self._env['dirport'], self._env['fingerprint'])
  401. return authlines
  402. def _getBridgeLines(self):
  403. """Return potential Bridge line for this Node. Non-bridge
  404. relays return "".
  405. """
  406. if not self._env['bridge']:
  407. return ""
  408. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  409. self._env['orport'])
  410. if self._env['ipv6_addr'] is not None:
  411. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  412. self._env['orport'])
  413. return bridgelines
  414. class LocalNodeController(NodeController):
  415. def __init__(self, env):
  416. NodeController.__init__(self, env)
  417. self._env = env
  418. def getPid(self):
  419. """Assuming that this node has its pidfile in ${dir}/pid, return
  420. the pid of the running process, or None if there is no pid in the
  421. file.
  422. """
  423. pidfile = os.path.join(self._env['dir'], 'pid')
  424. if not os.path.exists(pidfile):
  425. return None
  426. with open(pidfile, 'r') as f:
  427. return int(f.read())
  428. def isRunning(self, pid=None):
  429. """Return true iff this node is running. (If 'pid' is provided, we
  430. assume that the pid provided is the one of this node. Otherwise
  431. we call getPid().
  432. """
  433. if pid is None:
  434. pid = self.getPid()
  435. if pid is None:
  436. return False
  437. try:
  438. os.kill(pid, 0) # "kill 0" == "are you there?"
  439. except OSError as e:
  440. if e.errno == errno.ESRCH:
  441. return False
  442. raise
  443. # okay, so the process exists. Say "True" for now.
  444. # XXXX check if this is really tor!
  445. return True
  446. def check(self, listRunning=True, listNonRunning=False):
  447. """See if this node is running, stopped, or crashed. If it's running
  448. and listRunning is set, print a short statement. If it's
  449. stopped and listNonRunning is set, then print a short statement.
  450. If it's crashed, print a statement. Return True if the
  451. node is running, false otherwise.
  452. """
  453. # XXX Split this into "check" and "print" parts.
  454. pid = self.getPid()
  455. nick = self._env['nick']
  456. datadir = self._env['dir']
  457. corefile = "core.%s" % pid
  458. if self.isRunning(pid):
  459. if listRunning:
  460. print("%s is running with PID %s" % (nick, pid))
  461. return True
  462. elif os.path.exists(os.path.join(datadir, corefile)):
  463. if listNonRunning:
  464. print("%s seems to have crashed, and left core file %s" % (
  465. nick, corefile))
  466. return False
  467. else:
  468. if listNonRunning:
  469. print("%s is stopped" % nick)
  470. return False
  471. def hup(self):
  472. """Send a SIGHUP to this node, if it's running."""
  473. pid = self.getPid()
  474. nick = self._env['nick']
  475. if self.isRunning(pid):
  476. print("Sending sighup to %s" % nick)
  477. os.kill(pid, signal.SIGHUP)
  478. return True
  479. else:
  480. print("%s is not running" % nick)
  481. return False
  482. def start(self):
  483. """Try to start this node; return True if we succeeded or it was
  484. already running, False if we failed."""
  485. if self.isRunning():
  486. print("%s is already running" % self._env['nick'])
  487. return True
  488. tor_path = self._env['tor']
  489. torrc = self._getTorrcFname()
  490. cmdline = [
  491. tor_path,
  492. "--quiet",
  493. "-f", torrc,
  494. ]
  495. try:
  496. p = subprocess.Popen(cmdline)
  497. except OSError as e:
  498. # only catch file not found error
  499. if e.errno == errno.ENOENT:
  500. print("Cannot find tor binary %r. Use CHUTNEY_TOR "
  501. "environment variable to set the path, or put the "
  502. "binary into $PATH." % tor_path)
  503. sys.exit(0)
  504. else:
  505. raise
  506. if self.waitOnLaunch():
  507. # this requires that RunAsDaemon is set
  508. p.wait()
  509. else:
  510. # this does not require RunAsDaemon to be set, but is slower.
  511. #
  512. # poll() only catches failures before the call itself
  513. # so let's sleep a little first
  514. # this does, of course, slow down process launch
  515. # which can require an adjustment to the voting interval
  516. #
  517. # avoid writing a newline or space when polling
  518. # so output comes out neatly
  519. sys.stdout.write('.')
  520. sys.stdout.flush()
  521. time.sleep(self._env['poll_launch_time'])
  522. p.poll()
  523. if p.returncode is not None and p.returncode != 0:
  524. if self._env['poll_launch_time'] is None:
  525. print("Couldn't launch %s (%s): %s" % (self._env['nick'],
  526. " ".join(cmdline),
  527. p.returncode))
  528. else:
  529. print("Couldn't poll %s (%s) "
  530. "after waiting %s seconds for launch"
  531. ": %s" % (self._env['nick'],
  532. " ".join(cmdline),
  533. self._env['poll_launch_time'],
  534. p.returncode))
  535. return False
  536. return True
  537. def stop(self, sig=signal.SIGINT):
  538. """Try to stop this node by sending it the signal 'sig'."""
  539. pid = self.getPid()
  540. if not self.isRunning(pid):
  541. print("%s is not running" % self._env['nick'])
  542. return
  543. os.kill(pid, sig)
  544. def cleanup_lockfile(self):
  545. lf = self._env['lockfile']
  546. if not self.isRunning() and os.path.exists(lf):
  547. print('Removing stale lock file for {0} ...'.format(
  548. self._env['nick']))
  549. os.remove(lf)
  550. def waitOnLaunch(self):
  551. """Check whether we can wait() for the tor process to launch"""
  552. # TODO: is this the best place for this code?
  553. # RunAsDaemon default is 0
  554. runAsDaemon = False
  555. with open(self._getTorrcFname(), 'r') as f:
  556. for line in f.readlines():
  557. stline = line.strip()
  558. # if the line isn't all whitespace or blank
  559. if len(stline) > 0:
  560. splline = stline.split()
  561. # if the line has at least two tokens on it
  562. if (len(splline) > 0 and
  563. splline[0].lower() == "RunAsDaemon".lower() and
  564. splline[1] == "1"):
  565. # use the RunAsDaemon value from the torrc
  566. # TODO: multiple values?
  567. runAsDaemon = True
  568. if runAsDaemon:
  569. # we must use wait() instead of poll()
  570. self._env['poll_launch_time'] = None
  571. return True
  572. else:
  573. # we must use poll() instead of wait()
  574. if self._env['poll_launch_time'] is None:
  575. self._env['poll_launch_time'] = \
  576. self._env['poll_launch_time_default']
  577. return False
  578. DEFAULTS = {
  579. 'authority': False,
  580. 'bridgeauthority': False,
  581. 'hasbridgeauth': False,
  582. 'relay': False,
  583. 'bridge': False,
  584. 'hs': False,
  585. 'hs_directory': 'hidden_service',
  586. 'hs-hostname': None,
  587. 'connlimit': 60,
  588. 'net_base_dir': os.environ.get('CHUTNEY_DATA_DIR', 'net'),
  589. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  590. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  591. 'auth_cert_lifetime': 12,
  592. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  593. 'ipv6_addr': None,
  594. 'dirserver_flags': 'no-v2',
  595. 'chutney_dir': '.',
  596. 'torrc_fname': '${dir}/torrc',
  597. 'orport_base': 5000,
  598. 'dirport_base': 7000,
  599. 'controlport_base': 8000,
  600. 'socksport_base': 9000,
  601. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  602. 'bridges': "Bridge bleargh bad torrc file!",
  603. 'core': True,
  604. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  605. # otherwise, poll after that many seconds (can be fractional/decimal)
  606. 'poll_launch_time': None,
  607. # Used when poll_launch_time is None, but RunAsDaemon is not set
  608. # Set low so that we don't interfere with the voting interval
  609. 'poll_launch_time_default': 0.1,
  610. # the number of bytes of random data we send on each connection
  611. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  612. # the number of times each client will connect
  613. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  614. # Do we want every client to connect to every HS, or one client
  615. # to connect to each HS?
  616. # (Clients choose an exit at random, so this doesn't apply to exits.)
  617. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  618. }
  619. class TorEnviron(chutney.Templating.Environ):
  620. """Subclass of chutney.Templating.Environ to implement commonly-used
  621. substitutions.
  622. Environment fields provided:
  623. orport, controlport, socksport, dirport:
  624. dir:
  625. nick:
  626. tor_gencert:
  627. auth_passphrase:
  628. torrc_template_path:
  629. hs_hostname:
  630. Environment fields used:
  631. nodenum
  632. tag
  633. orport_base, controlport_base, socksport_base, dirport_base
  634. tor-gencert (note hyphen)
  635. chutney_dir
  636. tor
  637. dir
  638. hs_directory
  639. nick (debugging only)
  640. hs-hostname (note hyphen)
  641. XXXX document the above. Or document all fields in one place?
  642. """
  643. def __init__(self, parent=None, **kwargs):
  644. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  645. def _get_orport(self, my):
  646. return my['orport_base'] + my['nodenum']
  647. def _get_controlport(self, my):
  648. return my['controlport_base'] + my['nodenum']
  649. def _get_socksport(self, my):
  650. return my['socksport_base'] + my['nodenum']
  651. def _get_dirport(self, my):
  652. return my['dirport_base'] + my['nodenum']
  653. def _get_dir(self, my):
  654. return os.path.abspath(os.path.join(my['net_base_dir'],
  655. "nodes",
  656. "%03d%s" % (
  657. my['nodenum'], my['tag'])))
  658. def _get_nick(self, my):
  659. return "test%03d%s" % (my['nodenum'], my['tag'])
  660. def _get_tor_gencert(self, my):
  661. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  662. def _get_auth_passphrase(self, my):
  663. return self['nick'] # OMG TEH SECURE!
  664. def _get_torrc_template_path(self, my):
  665. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  666. def _get_lockfile(self, my):
  667. return os.path.join(self['dir'], 'lock')
  668. # A hs generates its key on first run,
  669. # so check for it at the last possible moment,
  670. # but cache it in memory to avoid repeatedly reading the file
  671. # XXXX - this is not like the other functions in this class,
  672. # as it reads from a file created by the hidden service
  673. def _get_hs_hostname(self, my):
  674. if my['hs-hostname'] is None:
  675. datadir = my['dir']
  676. # a file containing a single line with the hs' .onion address
  677. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  678. 'hostname')
  679. try:
  680. with open(hs_hostname_file, 'r') as hostnamefp:
  681. hostname = hostnamefp.read()
  682. # the hostname file ends with a newline
  683. hostname = hostname.strip()
  684. my['hs-hostname'] = hostname
  685. except IOError as e:
  686. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  687. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  688. return my['hs-hostname']
  689. class Network(object):
  690. """A network of Tor nodes, plus functions to manipulate them
  691. """
  692. def __init__(self, defaultEnviron):
  693. self._nodes = []
  694. self._dfltEnv = defaultEnviron
  695. self._nextnodenum = 0
  696. def _addNode(self, n):
  697. n.setNodenum(self._nextnodenum)
  698. self._nextnodenum += 1
  699. self._nodes.append(n)
  700. def move_aside_nodes(self):
  701. net_base_dir = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  702. nodesdir = os.path.join(net_base_dir, 'nodes')
  703. if not os.path.exists(nodesdir):
  704. return
  705. newdir = newdirbase = "%s.%d" % (nodesdir, time.time())
  706. i = 0
  707. while os.path.exists(newdir):
  708. i += 1
  709. newdir = "%s.%d" % (newdirbase, i)
  710. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  711. os.rename(nodesdir, newdir)
  712. def _checkConfig(self):
  713. for n in self._nodes:
  714. n.getBuilder().checkConfig(self)
  715. def configure(self):
  716. # shutil.rmtree(os.path.join(os.getcwd(),'net','nodes'),ignore_errors=True)
  717. self.move_aside_nodes()
  718. network = self
  719. altauthlines = []
  720. bridgelines = []
  721. builders = [n.getBuilder() for n in self._nodes]
  722. self._checkConfig()
  723. # XXX don't change node names or types or count if anything is
  724. # XXX running!
  725. for b in builders:
  726. b.preConfig(network)
  727. altauthlines.append(b._getAltAuthLines(
  728. self._dfltEnv['hasbridgeauth']))
  729. bridgelines.append(b._getBridgeLines())
  730. self._dfltEnv['authorities'] = "".join(altauthlines)
  731. self._dfltEnv['bridges'] = "".join(bridgelines)
  732. for b in builders:
  733. b.config(network)
  734. for b in builders:
  735. b.postConfig(network)
  736. def status(self):
  737. statuses = [n.getController().check() for n in self._nodes]
  738. n_ok = len([x for x in statuses if x])
  739. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  740. return n_ok == len(self._nodes)
  741. def restart(self):
  742. self.stop()
  743. self.start()
  744. def start(self):
  745. if self._dfltEnv['poll_launch_time'] is not None:
  746. # format polling correctly - avoid printing a newline
  747. sys.stdout.write("Starting nodes")
  748. sys.stdout.flush()
  749. else:
  750. print("Starting nodes")
  751. rv = all([n.getController().start() for n in self._nodes])
  752. # now print a newline unconditionally - this stops poll()ing
  753. # output from being squashed together, at the cost of a blank
  754. # line in wait()ing output
  755. print("")
  756. return rv
  757. def hup(self):
  758. print("Sending SIGHUP to nodes")
  759. return all([n.getController().hup() for n in self._nodes])
  760. def stop(self):
  761. controllers = [n.getController() for n in self._nodes]
  762. for sig, desc in [(signal.SIGINT, "SIGINT"),
  763. (signal.SIGINT, "another SIGINT"),
  764. (signal.SIGKILL, "SIGKILL")]:
  765. print("Sending %s to nodes" % desc)
  766. for c in controllers:
  767. if c.isRunning():
  768. c.stop(sig=sig)
  769. print("Waiting for nodes to finish.")
  770. for n in range(15):
  771. time.sleep(1)
  772. if all(not c.isRunning() for c in controllers):
  773. # check for stale lock file when Tor crashes
  774. for c in controllers:
  775. c.cleanup_lockfile()
  776. return
  777. sys.stdout.write(".")
  778. sys.stdout.flush()
  779. for c in controllers:
  780. c.check(listNonRunning=False)
  781. def ConfigureNodes(nodelist):
  782. network = _THE_NETWORK
  783. for n in nodelist:
  784. network._addNode(n)
  785. if n._env['bridgeauthority']:
  786. network._dfltEnv['hasbridgeauth'] = True
  787. def getTests():
  788. tests = []
  789. for x in os.listdir("scripts/chutney_tests/"):
  790. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  791. tests.append(os.path.splitext(x)[0])
  792. return tests
  793. def usage(network):
  794. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  795. "Known commands are: %s" % (
  796. " ".join(x for x in dir(network)
  797. if not x.startswith("_"))),
  798. "Known tests are: %s" % (
  799. " ".join(getTests()))
  800. ])
  801. def exit_on_error(err_msg):
  802. print("Error: {0}\n".format(err_msg))
  803. print(usage(_THE_NETWORK))
  804. sys.exit(1)
  805. def runConfigFile(verb, data):
  806. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  807. Node=Node,
  808. ConfigureNodes=ConfigureNodes,
  809. _THE_NETWORK=_THE_NETWORK)
  810. exec(data, _GLOBALS)
  811. network = _GLOBALS['_THE_NETWORK']
  812. # let's check if the verb is a valid test and run it
  813. if verb in getTests():
  814. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  815. try:
  816. return test_module.run_test(network)
  817. except AttributeError:
  818. print("Test {!r} has no 'run_test(network)' function".format(verb))
  819. return False
  820. # tell the user we don't know what their verb meant
  821. if not hasattr(network, verb):
  822. print(usage(network))
  823. print("Error: I don't know how to %s." % verb)
  824. return
  825. return getattr(network, verb)()
  826. def parseArgs():
  827. if len(sys.argv) < 3:
  828. exit_on_error("Not enough arguments given.")
  829. if not os.path.isfile(sys.argv[2]):
  830. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  831. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  832. def main():
  833. global _BASE_ENVIRON
  834. global _TORRC_OPTIONS
  835. global _THE_NETWORK
  836. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  837. # _TORRC_OPTIONS gets initialised on demand as a map of
  838. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  839. # Or it can be pre-populated as a static whitelist of options
  840. _TORRC_OPTIONS = dict()
  841. _THE_NETWORK = Network(_BASE_ENVIRON)
  842. args = parseArgs()
  843. f = open(args['network_cfg'])
  844. result = runConfigFile(args['action'], f)
  845. if result is False:
  846. return -1
  847. return 0
  848. if __name__ == '__main__':
  849. sys.exit(main())