TorNet.py 36 KB

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