TorNet.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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=448):
  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. 448 is the decimal representation of the octal number 0700. Since
  32. python2 only supports 0700 and python3 only supports 0o700, 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
  163. # ipv6_addr -- IPv6 address to listen on
  164. # orport, dirport -- used on authorities, relays, and bridges
  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. """
  290. datadir = self._env['dir']
  291. mkdir_p(os.path.join(datadir, self._env['hs_directory']))
  292. def _genAuthorityKey(self):
  293. """Generate an authority identity and signing key for this authority,
  294. if they do not already exist."""
  295. datadir = self._env['dir']
  296. tor_gencert = self._env['tor_gencert']
  297. lifetime = self._env['auth_cert_lifetime']
  298. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  299. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  300. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  301. addr = self.expand("${ip}:${dirport}")
  302. passphrase = self._env['auth_passphrase']
  303. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  304. return
  305. cmdline = [
  306. tor_gencert,
  307. '--create-identity-key',
  308. '--passphrase-fd', '0',
  309. '-i', idfile,
  310. '-s', skfile,
  311. '-c', certfile,
  312. '-m', str(lifetime),
  313. '-a', addr]
  314. print("Creating identity key %s for %s with %s" % (
  315. idfile, self._env['nick'], " ".join(cmdline)))
  316. try:
  317. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  318. except OSError as e:
  319. # only catch file not found error
  320. if e.errno == errno.ENOENT:
  321. print("Cannot find tor-gencert binary %r. Use "
  322. "CHUTNEY_TOR_GENCERT environment variable to set the "
  323. "path, or put the binary into $PATH." % tor_gencert)
  324. sys.exit(0)
  325. else:
  326. raise
  327. p.communicate(passphrase + "\n")
  328. assert p.returncode == 0 # XXXX BAD!
  329. def _genRouterKey(self):
  330. """Generate an identity key for this router, unless we already have,
  331. and set up the 'fingerprint' entry in the Environ.
  332. """
  333. datadir = self._env['dir']
  334. tor = self._env['tor']
  335. torrc = self._getTorrcFname()
  336. cmdline = [
  337. tor,
  338. "--quiet",
  339. "--ignore-missing-torrc",
  340. "-f", torrc,
  341. "--list-fingerprint",
  342. "--orport", "1",
  343. "--datadirectory", datadir]
  344. try:
  345. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  346. except OSError as e:
  347. # only catch file not found error
  348. if e.errno == errno.ENOENT:
  349. print("Cannot find tor binary %r. Use "
  350. "CHUTNEY_TOR environment variable to set the "
  351. "path, or put the binary into $PATH." % tor)
  352. sys.exit(0)
  353. else:
  354. raise
  355. stdout, stderr = p.communicate()
  356. fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
  357. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  358. print(("Error when calling %r. It gave %r as a fingerprint "
  359. " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
  360. sys.exit(1)
  361. self._env['fingerprint'] = fingerprint
  362. def _getAltAuthLines(self, hasbridgeauth=False):
  363. """Return a combination of AlternateDirAuthority,
  364. AlternateHSAuthority and AlternateBridgeAuthority lines for
  365. this Node, appropriately. Non-authorities return ""."""
  366. if not self._env['authority']:
  367. return ""
  368. datadir = self._env['dir']
  369. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  370. v3id = None
  371. with open(certfile, 'r') as f:
  372. for line in f:
  373. if line.startswith("fingerprint"):
  374. v3id = line.split()[1].strip()
  375. break
  376. assert v3id is not None
  377. if self._env['bridgeauthority']:
  378. # Bridge authorities return AlternateBridgeAuthority with
  379. # the 'bridge' flag set.
  380. options = ("AlternateBridgeAuthority",)
  381. self._env['dirserver_flags'] += " bridge"
  382. else:
  383. # Directory authorities return AlternateDirAuthority with
  384. # the 'hs' and 'v3ident' flags set.
  385. # XXXX This next line is needed for 'bridges' but breaks
  386. # 'basic'
  387. if hasbridgeauth:
  388. options = ("AlternateDirAuthority",)
  389. else:
  390. options = ("DirAuthority",)
  391. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  392. authlines = ""
  393. for authopt in options:
  394. authlines += "%s %s orport=%s" % (
  395. authopt, self._env['nick'], self._env['orport'])
  396. # It's ok to give an authority's IPv6 address to an IPv4-only
  397. # client or relay: it will and must ignore it
  398. if self._env['ipv6_addr'] is not None:
  399. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  400. self._env['orport'])
  401. authlines += " %s %s:%s %s\n" % (
  402. self._env['dirserver_flags'], self._env['ip'],
  403. self._env['dirport'], self._env['fingerprint'])
  404. return authlines
  405. def _getBridgeLines(self):
  406. """Return potential Bridge line for this Node. Non-bridge
  407. relays return "".
  408. """
  409. if not self._env['bridge']:
  410. return ""
  411. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  412. self._env['orport'])
  413. if self._env['ipv6_addr'] is not None:
  414. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  415. self._env['orport'])
  416. return bridgelines
  417. class LocalNodeController(NodeController):
  418. def __init__(self, env):
  419. NodeController.__init__(self, env)
  420. self._env = env
  421. def getPid(self):
  422. """Assuming that this node has its pidfile in ${dir}/pid, return
  423. the pid of the running process, or None if there is no pid in the
  424. file.
  425. """
  426. pidfile = os.path.join(self._env['dir'], 'pid')
  427. if not os.path.exists(pidfile):
  428. return None
  429. with open(pidfile, 'r') as f:
  430. return int(f.read())
  431. def isRunning(self, pid=None):
  432. """Return true iff this node is running. (If 'pid' is provided, we
  433. assume that the pid provided is the one of this node. Otherwise
  434. we call getPid().
  435. """
  436. if pid is None:
  437. pid = self.getPid()
  438. if pid is None:
  439. return False
  440. try:
  441. os.kill(pid, 0) # "kill 0" == "are you there?"
  442. except OSError as e:
  443. if e.errno == errno.ESRCH:
  444. return False
  445. raise
  446. # okay, so the process exists. Say "True" for now.
  447. # XXXX check if this is really tor!
  448. return True
  449. def check(self, listRunning=True, listNonRunning=False):
  450. """See if this node is running, stopped, or crashed. If it's running
  451. and listRunning is set, print a short statement. If it's
  452. stopped and listNonRunning is set, then print a short statement.
  453. If it's crashed, print a statement. Return True if the
  454. node is running, false otherwise.
  455. """
  456. # XXX Split this into "check" and "print" parts.
  457. pid = self.getPid()
  458. nick = self._env['nick']
  459. datadir = self._env['dir']
  460. corefile = "core.%s" % pid
  461. if self.isRunning(pid):
  462. if listRunning:
  463. print("%s is running with PID %s" % (nick, pid))
  464. return True
  465. elif os.path.exists(os.path.join(datadir, corefile)):
  466. if listNonRunning:
  467. print("%s seems to have crashed, and left core file %s" % (
  468. nick, corefile))
  469. return False
  470. else:
  471. if listNonRunning:
  472. print("%s is stopped" % nick)
  473. return False
  474. def hup(self):
  475. """Send a SIGHUP to this node, if it's running."""
  476. pid = self.getPid()
  477. nick = self._env['nick']
  478. if self.isRunning(pid):
  479. print("Sending sighup to %s" % nick)
  480. os.kill(pid, signal.SIGHUP)
  481. return True
  482. else:
  483. print("%s is not running" % nick)
  484. return False
  485. def start(self):
  486. """Try to start this node; return True if we succeeded or it was
  487. already running, False if we failed."""
  488. if self.isRunning():
  489. print("%s is already running" % self._env['nick'])
  490. return True
  491. tor_path = self._env['tor']
  492. torrc = self._getTorrcFname()
  493. cmdline = [
  494. tor_path,
  495. "--quiet",
  496. "-f", torrc,
  497. ]
  498. try:
  499. p = subprocess.Popen(cmdline)
  500. except OSError as e:
  501. # only catch file not found error
  502. if e.errno == errno.ENOENT:
  503. print("Cannot find tor binary %r. Use CHUTNEY_TOR "
  504. "environment variable to set the path, or put the "
  505. "binary into $PATH." % tor_path)
  506. sys.exit(0)
  507. else:
  508. raise
  509. if self.waitOnLaunch():
  510. # this requires that RunAsDaemon is set
  511. p.wait()
  512. else:
  513. # this does not require RunAsDaemon to be set, but is slower.
  514. #
  515. # poll() only catches failures before the call itself
  516. # so let's sleep a little first
  517. # this does, of course, slow down process launch
  518. # which can require an adjustment to the voting interval
  519. #
  520. # avoid writing a newline or space when polling
  521. # so output comes out neatly
  522. sys.stdout.write('.')
  523. sys.stdout.flush()
  524. time.sleep(self._env['poll_launch_time'])
  525. p.poll()
  526. if p.returncode is not None and p.returncode != 0:
  527. if self._env['poll_launch_time'] is None:
  528. print("Couldn't launch %s (%s): %s" % (self._env['nick'],
  529. " ".join(cmdline),
  530. p.returncode))
  531. else:
  532. print("Couldn't poll %s (%s) "
  533. "after waiting %s seconds for launch"
  534. ": %s" % (self._env['nick'],
  535. " ".join(cmdline),
  536. self._env['poll_launch_time'],
  537. p.returncode))
  538. return False
  539. return True
  540. def stop(self, sig=signal.SIGINT):
  541. """Try to stop this node by sending it the signal 'sig'."""
  542. pid = self.getPid()
  543. if not self.isRunning(pid):
  544. print("%s is not running" % self._env['nick'])
  545. return
  546. os.kill(pid, sig)
  547. def cleanup_lockfile(self):
  548. lf = self._env['lockfile']
  549. if not self.isRunning() and os.path.exists(lf):
  550. print('Removing stale lock file for {0} ...'.format(
  551. self._env['nick']))
  552. os.remove(lf)
  553. def waitOnLaunch(self):
  554. """Check whether we can wait() for the tor process to launch"""
  555. # TODO: is this the best place for this code?
  556. # RunAsDaemon default is 0
  557. runAsDaemon = False
  558. with open(self._getTorrcFname(), 'r') as f:
  559. for line in f.readlines():
  560. stline = line.strip()
  561. # if the line isn't all whitespace or blank
  562. if len(stline) > 0:
  563. splline = stline.split()
  564. # if the line has at least two tokens on it
  565. if (len(splline) > 0 and
  566. splline[0].lower() == "RunAsDaemon".lower() and
  567. splline[1] == "1"):
  568. # use the RunAsDaemon value from the torrc
  569. # TODO: multiple values?
  570. runAsDaemon = True
  571. if runAsDaemon:
  572. # we must use wait() instead of poll()
  573. self._env['poll_launch_time'] = None
  574. return True
  575. else:
  576. # we must use poll() instead of wait()
  577. if self._env['poll_launch_time'] is None:
  578. self._env['poll_launch_time'] = \
  579. self._env['poll_launch_time_default']
  580. return False
  581. DEFAULTS = {
  582. 'authority': False,
  583. 'bridgeauthority': False,
  584. 'hasbridgeauth': False,
  585. 'relay': False,
  586. 'bridge': False,
  587. 'hs': False,
  588. 'hs_directory': 'hidden_service',
  589. 'hs-hostname': None,
  590. 'connlimit': 60,
  591. 'net_base_dir': os.environ.get('CHUTNEY_DATA_DIR', 'net'),
  592. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  593. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  594. 'auth_cert_lifetime': 12,
  595. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  596. # Pre-0.2.8 clients will fail to parse ipv6 auth lines,
  597. # so we default to ipv6_addr None
  598. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  599. 'dirserver_flags': 'no-v2',
  600. 'chutney_dir': '.',
  601. 'torrc_fname': '${dir}/torrc',
  602. 'orport_base': 5000,
  603. 'dirport_base': 7000,
  604. 'controlport_base': 8000,
  605. 'socksport_base': 9000,
  606. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  607. 'bridges': "Bridge bleargh bad torrc file!",
  608. 'core': True,
  609. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  610. # otherwise, poll after that many seconds (can be fractional/decimal)
  611. 'poll_launch_time': None,
  612. # Used when poll_launch_time is None, but RunAsDaemon is not set
  613. # Set low so that we don't interfere with the voting interval
  614. 'poll_launch_time_default': 0.1,
  615. # the number of bytes of random data we send on each connection
  616. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  617. # the number of times each client will connect
  618. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  619. # Do we want every client to connect to every HS, or one client
  620. # to connect to each HS?
  621. # (Clients choose an exit at random, so this doesn't apply to exits.)
  622. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  623. # How long should verify (and similar commands) wait for a successful
  624. # outcome? (seconds)
  625. # We check BOOTSTRAP_TIME for compatibility with old versions of
  626. # test-network.sh
  627. 'bootstrap_time': int(os.environ.get('CHUTNEY_BOOTSTRAP_TIME',
  628. os.environ.get('BOOTSTRAP_TIME',
  629. 60))),
  630. }
  631. class TorEnviron(chutney.Templating.Environ):
  632. """Subclass of chutney.Templating.Environ to implement commonly-used
  633. substitutions.
  634. Environment fields provided:
  635. orport, controlport, socksport, dirport:
  636. dir:
  637. nick:
  638. tor_gencert:
  639. auth_passphrase:
  640. torrc_template_path:
  641. hs_hostname:
  642. Environment fields used:
  643. nodenum
  644. tag
  645. orport_base, controlport_base, socksport_base, dirport_base
  646. tor-gencert (note hyphen)
  647. chutney_dir
  648. tor
  649. dir
  650. hs_directory
  651. nick (debugging only)
  652. hs-hostname (note hyphen)
  653. XXXX document the above. Or document all fields in one place?
  654. """
  655. def __init__(self, parent=None, **kwargs):
  656. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  657. def _get_orport(self, my):
  658. return my['orport_base'] + my['nodenum']
  659. def _get_controlport(self, my):
  660. return my['controlport_base'] + my['nodenum']
  661. def _get_socksport(self, my):
  662. return my['socksport_base'] + my['nodenum']
  663. def _get_dirport(self, my):
  664. return my['dirport_base'] + my['nodenum']
  665. def _get_dir(self, my):
  666. return os.path.abspath(os.path.join(my['net_base_dir'],
  667. "nodes",
  668. "%03d%s" % (
  669. my['nodenum'], my['tag'])))
  670. def _get_nick(self, my):
  671. return "test%03d%s" % (my['nodenum'], my['tag'])
  672. def _get_tor_gencert(self, my):
  673. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  674. def _get_auth_passphrase(self, my):
  675. return self['nick'] # OMG TEH SECURE!
  676. def _get_torrc_template_path(self, my):
  677. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  678. def _get_lockfile(self, my):
  679. return os.path.join(self['dir'], 'lock')
  680. # A hs generates its key on first run,
  681. # so check for it at the last possible moment,
  682. # but cache it in memory to avoid repeatedly reading the file
  683. # XXXX - this is not like the other functions in this class,
  684. # as it reads from a file created by the hidden service
  685. def _get_hs_hostname(self, my):
  686. if my['hs-hostname'] is None:
  687. datadir = my['dir']
  688. # a file containing a single line with the hs' .onion address
  689. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  690. 'hostname')
  691. try:
  692. with open(hs_hostname_file, 'r') as hostnamefp:
  693. hostname = hostnamefp.read()
  694. # the hostname file ends with a newline
  695. hostname = hostname.strip()
  696. my['hs-hostname'] = hostname
  697. except IOError as e:
  698. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  699. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  700. return my['hs-hostname']
  701. class Network(object):
  702. """A network of Tor nodes, plus functions to manipulate them
  703. """
  704. def __init__(self, defaultEnviron):
  705. self._nodes = []
  706. self._dfltEnv = defaultEnviron
  707. self._nextnodenum = 0
  708. def _addNode(self, n):
  709. n.setNodenum(self._nextnodenum)
  710. self._nextnodenum += 1
  711. self._nodes.append(n)
  712. def move_aside_nodes(self):
  713. net_base_dir = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  714. nodesdir = os.path.join(net_base_dir, 'nodes')
  715. if not os.path.exists(nodesdir):
  716. return
  717. newdir = newdirbase = "%s.%d" % (nodesdir, time.time())
  718. i = 0
  719. while os.path.exists(newdir):
  720. i += 1
  721. newdir = "%s.%d" % (newdirbase, i)
  722. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  723. os.rename(nodesdir, newdir)
  724. def _checkConfig(self):
  725. for n in self._nodes:
  726. n.getBuilder().checkConfig(self)
  727. def configure(self):
  728. # shutil.rmtree(os.path.join(os.getcwd(),'net','nodes'),ignore_errors=True)
  729. self.move_aside_nodes()
  730. network = self
  731. altauthlines = []
  732. bridgelines = []
  733. builders = [n.getBuilder() for n in self._nodes]
  734. self._checkConfig()
  735. # XXX don't change node names or types or count if anything is
  736. # XXX running!
  737. for b in builders:
  738. b.preConfig(network)
  739. altauthlines.append(b._getAltAuthLines(
  740. self._dfltEnv['hasbridgeauth']))
  741. bridgelines.append(b._getBridgeLines())
  742. self._dfltEnv['authorities'] = "".join(altauthlines)
  743. self._dfltEnv['bridges'] = "".join(bridgelines)
  744. for b in builders:
  745. b.config(network)
  746. for b in builders:
  747. b.postConfig(network)
  748. def status(self):
  749. statuses = [n.getController().check() for n in self._nodes]
  750. n_ok = len([x for x in statuses if x])
  751. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  752. return n_ok == len(self._nodes)
  753. def restart(self):
  754. self.stop()
  755. self.start()
  756. def start(self):
  757. if self._dfltEnv['poll_launch_time'] is not None:
  758. # format polling correctly - avoid printing a newline
  759. sys.stdout.write("Starting nodes")
  760. sys.stdout.flush()
  761. else:
  762. print("Starting nodes")
  763. rv = all([n.getController().start() for n in self._nodes])
  764. # now print a newline unconditionally - this stops poll()ing
  765. # output from being squashed together, at the cost of a blank
  766. # line in wait()ing output
  767. print("")
  768. return rv
  769. def hup(self):
  770. print("Sending SIGHUP to nodes")
  771. return all([n.getController().hup() for n in self._nodes])
  772. def stop(self):
  773. controllers = [n.getController() for n in self._nodes]
  774. for sig, desc in [(signal.SIGINT, "SIGINT"),
  775. (signal.SIGINT, "another SIGINT"),
  776. (signal.SIGKILL, "SIGKILL")]:
  777. print("Sending %s to nodes" % desc)
  778. for c in controllers:
  779. if c.isRunning():
  780. c.stop(sig=sig)
  781. print("Waiting for nodes to finish.")
  782. for n in range(15):
  783. time.sleep(1)
  784. if all(not c.isRunning() for c in controllers):
  785. # check for stale lock file when Tor crashes
  786. for c in controllers:
  787. c.cleanup_lockfile()
  788. return
  789. sys.stdout.write(".")
  790. sys.stdout.flush()
  791. for c in controllers:
  792. c.check(listNonRunning=False)
  793. def ConfigureNodes(nodelist):
  794. network = _THE_NETWORK
  795. for n in nodelist:
  796. network._addNode(n)
  797. if n._env['bridgeauthority']:
  798. network._dfltEnv['hasbridgeauth'] = True
  799. def getTests():
  800. tests = []
  801. chutney_path = os.environ.get('CHUTNEY_PATH', '')
  802. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  803. chutney_path += "/"
  804. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  805. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  806. tests.append(os.path.splitext(x)[0])
  807. return tests
  808. def usage(network):
  809. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  810. "Known commands are: %s" % (
  811. " ".join(x for x in dir(network)
  812. if not x.startswith("_"))),
  813. "Known tests are: %s" % (
  814. " ".join(getTests()))
  815. ])
  816. def exit_on_error(err_msg):
  817. print("Error: {0}\n".format(err_msg))
  818. print(usage(_THE_NETWORK))
  819. sys.exit(1)
  820. def runConfigFile(verb, data):
  821. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  822. Node=Node,
  823. ConfigureNodes=ConfigureNodes,
  824. _THE_NETWORK=_THE_NETWORK)
  825. exec(data, _GLOBALS)
  826. network = _GLOBALS['_THE_NETWORK']
  827. # let's check if the verb is a valid test and run it
  828. if verb in getTests():
  829. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  830. try:
  831. return test_module.run_test(network)
  832. except AttributeError:
  833. print("Test {!r} has no 'run_test(network)' function".format(verb))
  834. return False
  835. # tell the user we don't know what their verb meant
  836. if not hasattr(network, verb):
  837. print(usage(network))
  838. print("Error: I don't know how to %s." % verb)
  839. return
  840. return getattr(network, verb)()
  841. def parseArgs():
  842. if len(sys.argv) < 3:
  843. exit_on_error("Not enough arguments given.")
  844. if not os.path.isfile(sys.argv[2]):
  845. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  846. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  847. def main():
  848. global _BASE_ENVIRON
  849. global _TORRC_OPTIONS
  850. global _THE_NETWORK
  851. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  852. # _TORRC_OPTIONS gets initialised on demand as a map of
  853. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  854. # Or it can be pre-populated as a static whitelist of options
  855. _TORRC_OPTIONS = dict()
  856. _THE_NETWORK = Network(_BASE_ENVIRON)
  857. args = parseArgs()
  858. f = open(args['network_cfg'])
  859. result = runConfigFile(args['action'], f)
  860. if result is False:
  861. return -1
  862. return 0
  863. if __name__ == '__main__':
  864. sys.exit(main())