TorNet.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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. def get_absolute_chutney_path():
  42. # use the current directory as the default
  43. # (./chutney already sets CHUTNEY_PATH using the path to the script)
  44. # use tools/test-network.sh if you want chutney to try really hard to find
  45. # itself
  46. relative_chutney_path = os.environ.get('CHUTNEY_PATH', os.getcwd())
  47. return os.path.abspath(relative_chutney_path)
  48. def get_absolute_net_path():
  49. # use the chutney path as the default
  50. absolute_chutney_path = get_absolute_chutney_path()
  51. relative_net_path = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  52. # but what is it relative to?
  53. # let's check if it's in CHUTNEY_PATH first, to preserve
  54. # backwards-compatible behaviour
  55. chutney_net_path = os.path.join(absolute_chutney_path, relative_net_path)
  56. if os.path.isdir(chutney_net_path):
  57. return chutney_net_path
  58. # ok, it's relative to the current directory, whatever that is
  59. return os.path.abspath(relative_net_path)
  60. def get_absolute_nodes_path():
  61. # there's no way to customise this: we really don't need more options
  62. return os.path.join(get_absolute_net_path(), 'nodes')
  63. def get_new_absolute_nodes_path(now=time.time()):
  64. # automatically chosen to prevent path collisions, and result in an ordered
  65. # series of directory path names
  66. # should only be called by 'chutney configure', all other chutney commands
  67. # should use get_absolute_nodes_path()
  68. nodesdir = get_absolute_nodes_path()
  69. newdir = newdirbase = "%s.%d" % (nodesdir, now)
  70. # if the time is the same, fall back to a simple integer count
  71. # (this is very unlikely to happen unless the clock changes: it's not
  72. # possible to run multiple chutney networks at the same time)
  73. i = 0
  74. while os.path.exists(newdir):
  75. i += 1
  76. newdir = "%s.%d" % (newdirbase, i)
  77. return newdir
  78. class Node(object):
  79. """A Node represents a Tor node or a set of Tor nodes. It's created
  80. in a network configuration file.
  81. This class is responsible for holding the user's selected node
  82. configuration, and figuring out how the node needs to be
  83. configured and launched.
  84. """
  85. # Fields:
  86. # _parent
  87. # _env
  88. # _builder
  89. # _controller
  90. ########
  91. # Users are expected to call these:
  92. def __init__(self, parent=None, **kwargs):
  93. self._parent = parent
  94. self._env = self._createEnviron(parent, kwargs)
  95. self._builder = None
  96. self._controller = None
  97. def getN(self, N):
  98. return [Node(self) for _ in range(N)]
  99. def specialize(self, **kwargs):
  100. return Node(parent=self, **kwargs)
  101. ######
  102. # Chutney uses these:
  103. def getBuilder(self):
  104. """Return a NodeBuilder instance to set up this node (that is, to
  105. write all the files that need to be in place so that this
  106. node can be run by a NodeController).
  107. """
  108. if self._builder is None:
  109. self._builder = LocalNodeBuilder(self._env)
  110. return self._builder
  111. def getController(self):
  112. """Return a NodeController instance to control this node (that is,
  113. to start it, stop it, see if it's running, etc.)
  114. """
  115. if self._controller is None:
  116. self._controller = LocalNodeController(self._env)
  117. return self._controller
  118. def setNodenum(self, num):
  119. """Assign a value to the 'nodenum' element of this node. Each node
  120. in a network gets its own nodenum.
  121. """
  122. self._env['nodenum'] = num
  123. #####
  124. # These are internal:
  125. def _createEnviron(self, parent, argdict):
  126. """Return an Environ that delegates to the parent node's Environ (if
  127. there is a parent node), or to the default environment.
  128. """
  129. if parent:
  130. parentenv = parent._env
  131. else:
  132. parentenv = self._getDefaultEnviron()
  133. return TorEnviron(parentenv, **argdict)
  134. def _getDefaultEnviron(self):
  135. """Return the default environment. Any variables that we can't find
  136. set for any particular node, we look for here.
  137. """
  138. return _BASE_ENVIRON
  139. class _NodeCommon(object):
  140. """Internal helper class for functionality shared by some NodeBuilders
  141. and some NodeControllers."""
  142. # XXXX maybe this should turn into a mixin.
  143. def __init__(self, env):
  144. self._env = env
  145. def expand(self, pat, includePath=(".",)):
  146. return chutney.Templating.Template(pat, includePath).format(self._env)
  147. def _getTorrcFname(self):
  148. """Return the name of the file where we'll be writing torrc"""
  149. return self.expand("${torrc_fname}")
  150. class NodeBuilder(_NodeCommon):
  151. """Abstract base class. A NodeBuilder is responsible for doing all the
  152. one-time prep needed to set up a node in a network.
  153. """
  154. def __init__(self, env):
  155. _NodeCommon.__init__(self, env)
  156. def checkConfig(self, net):
  157. """Try to format our torrc; raise an exception if we can't.
  158. """
  159. def preConfig(self, net):
  160. """Called on all nodes before any nodes configure: generates keys as
  161. needed.
  162. """
  163. def config(self, net):
  164. """Called to configure a node: creates a torrc file for it."""
  165. def postConfig(self, net):
  166. """Called on each nodes after all nodes configure."""
  167. class NodeController(_NodeCommon):
  168. """Abstract base class. A NodeController is responsible for running a
  169. node on the network.
  170. """
  171. def __init__(self, env):
  172. _NodeCommon.__init__(self, env)
  173. def check(self, listRunning=True, listNonRunning=False):
  174. """See if this node is running, stopped, or crashed. If it's running
  175. and listRunning is set, print a short statement. If it's
  176. stopped and listNonRunning is set, then print a short statement.
  177. If it's crashed, print a statement. Return True if the
  178. node is running, false otherwise.
  179. """
  180. def start(self):
  181. """Try to start this node; return True if we succeeded or it was
  182. already running, False if we failed."""
  183. def stop(self, sig=signal.SIGINT):
  184. """Try to stop this node by sending it the signal 'sig'."""
  185. class LocalNodeBuilder(NodeBuilder):
  186. # Environment members used:
  187. # torrc -- which torrc file to use
  188. # torrc_template_path -- path to search for torrc files and include files
  189. # authority -- bool -- are we an authority?
  190. # bridgeauthority -- bool -- are we a bridge authority?
  191. # relay -- bool -- are we a relay?
  192. # bridge -- bool -- are we a bridge?
  193. # hs -- bool -- are we a hidden service?
  194. # nodenum -- int -- set by chutney -- which unique node index is this?
  195. # dir -- path -- set by chutney -- data directory for this tor
  196. # tor_gencert -- path to tor_gencert binary
  197. # tor -- path to tor binary
  198. # auth_cert_lifetime -- lifetime of authority certs, in months.
  199. # ip -- IP to listen on
  200. # ipv6_addr -- IPv6 address to listen on
  201. # orport, dirport -- used on authorities, relays, and bridges
  202. # fingerprint -- used only if authority
  203. # dirserver_flags -- used only if authority
  204. # nick -- nickname of this router
  205. # Environment members set
  206. # fingerprint -- hex router key fingerprint
  207. # nodenum -- int -- set by chutney -- which unique node index is this?
  208. def __init__(self, env):
  209. NodeBuilder.__init__(self, env)
  210. self._env = env
  211. def _createTorrcFile(self, checkOnly=False):
  212. """Write the torrc file for this node, disabling any options
  213. that are not supported by env's tor binary using comments.
  214. If checkOnly, just make sure that the formatting is indeed
  215. possible.
  216. """
  217. fn_out = self._getTorrcFname()
  218. torrc_template = self._getTorrcTemplate()
  219. output = torrc_template.format(self._env)
  220. if checkOnly:
  221. # XXXX Is it time-consuming to format? If so, cache here.
  222. return
  223. # now filter the options we're about to write, commenting out
  224. # the options that the current tor binary doesn't support
  225. tor = self._env['tor']
  226. # find the options the current tor binary supports, and cache them
  227. if tor not in _TORRC_OPTIONS:
  228. # Note: some versions of tor (e.g. 0.2.4.23) require
  229. # --list-torrc-options to be the first argument
  230. cmdline = [
  231. tor,
  232. "--list-torrc-options",
  233. "--hush"]
  234. try:
  235. opts = subprocess.check_output(cmdline, bufsize=-1,
  236. universal_newlines=True)
  237. except OSError as e:
  238. # only catch file not found error
  239. if e.errno == errno.ENOENT:
  240. print("Cannot find tor binary %r. Use "
  241. "CHUTNEY_TOR environment variable to set the "
  242. "path, or put the binary into $PATH." % tor)
  243. sys.exit(0)
  244. else:
  245. raise
  246. # check we received a list of options, and nothing else
  247. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  248. torrc_opts = opts.split()
  249. # cache the options for this tor binary's path
  250. _TORRC_OPTIONS[tor] = torrc_opts
  251. else:
  252. torrc_opts = _TORRC_OPTIONS[tor]
  253. # check if each option is supported before writing it
  254. # TODO: what about unsupported values?
  255. # e.g. tor 0.2.4.23 doesn't support TestingV3AuthInitialVoteDelay 2
  256. # but later version do. I say throw this one to the user.
  257. with open(fn_out, 'w') as f:
  258. # we need to do case-insensitive option comparison
  259. # even if this is a static whitelist,
  260. # so we convert to lowercase as close to the loop as possible
  261. lower_opts = [opt.lower() for opt in torrc_opts]
  262. # keep ends when splitting lines, so we can write them out
  263. # using writelines() without messing around with "\n"s
  264. for line in output.splitlines(True):
  265. # check if the first word on the line is a supported option,
  266. # preserving empty lines and comment lines
  267. sline = line.strip()
  268. if (len(sline) == 0 or
  269. sline[0] == '#' or
  270. sline.split()[0].lower() in lower_opts):
  271. f.writelines([line])
  272. else:
  273. # well, this could get spammy
  274. # TODO: warn once per option per tor binary
  275. # TODO: print tor version?
  276. print(("The tor binary at %r does not support the "
  277. "option in the torrc line:\n"
  278. "%r") % (tor, line.strip()))
  279. # we could decide to skip these lines entirely
  280. # TODO: write tor version?
  281. f.writelines(["# " + tor + " unsupported: " + line])
  282. def _getTorrcTemplate(self):
  283. """Return the template used to write the torrc for this node."""
  284. template_path = self._env['torrc_template_path']
  285. return chutney.Templating.Template("$${include:$torrc}",
  286. includePath=template_path)
  287. def _getFreeVars(self):
  288. """Return a set of the free variables in the torrc template for this
  289. node.
  290. """
  291. template = self._getTorrcTemplate()
  292. return template.freevars(self._env)
  293. def checkConfig(self, net):
  294. """Try to format our torrc; raise an exception if we can't.
  295. """
  296. self._createTorrcFile(checkOnly=True)
  297. def preConfig(self, net):
  298. """Called on all nodes before any nodes configure: generates keys and
  299. hidden service directories as needed.
  300. """
  301. self._makeDataDir()
  302. if self._env['authority']:
  303. self._genAuthorityKey()
  304. if self._env['relay']:
  305. self._genRouterKey()
  306. if self._env['hs']:
  307. self._makeHiddenServiceDir()
  308. def config(self, net):
  309. """Called to configure a node: creates a torrc file for it."""
  310. self._createTorrcFile()
  311. # self._createScripts()
  312. def postConfig(self, net):
  313. """Called on each nodes after all nodes configure."""
  314. # self.net.addNode(self)
  315. pass
  316. def _makeDataDir(self):
  317. """Create the data directory (with keys subdirectory) for this node.
  318. """
  319. datadir = self._env['dir']
  320. mkdir_p(os.path.join(datadir, 'keys'))
  321. def _makeHiddenServiceDir(self):
  322. """Create the hidden service subdirectory for this node.
  323. The directory name is stored under the 'hs_directory' environment
  324. key. It is combined with the 'dir' data directory key to yield the
  325. path to the hidden service directory.
  326. """
  327. datadir = self._env['dir']
  328. mkdir_p(os.path.join(datadir, self._env['hs_directory']))
  329. def _genAuthorityKey(self):
  330. """Generate an authority identity and signing key for this authority,
  331. if they do not already exist."""
  332. datadir = self._env['dir']
  333. tor_gencert = self._env['tor_gencert']
  334. lifetime = self._env['auth_cert_lifetime']
  335. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  336. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  337. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  338. addr = self.expand("${ip}:${dirport}")
  339. passphrase = self._env['auth_passphrase']
  340. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  341. return
  342. cmdline = [
  343. tor_gencert,
  344. '--create-identity-key',
  345. '--passphrase-fd', '0',
  346. '-i', idfile,
  347. '-s', skfile,
  348. '-c', certfile,
  349. '-m', str(lifetime),
  350. '-a', addr]
  351. print("Creating identity key %s for %s with %s" % (
  352. idfile, self._env['nick'], " ".join(cmdline)))
  353. try:
  354. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  355. except OSError as e:
  356. # only catch file not found error
  357. if e.errno == errno.ENOENT:
  358. print("Cannot find tor-gencert binary %r. Use "
  359. "CHUTNEY_TOR_GENCERT environment variable to set the "
  360. "path, or put the binary into $PATH." % tor_gencert)
  361. sys.exit(0)
  362. else:
  363. raise
  364. p.communicate(passphrase + "\n")
  365. assert p.returncode == 0 # XXXX BAD!
  366. def _genRouterKey(self):
  367. """Generate an identity key for this router, unless we already have,
  368. and set up the 'fingerprint' entry in the Environ.
  369. """
  370. datadir = self._env['dir']
  371. tor = self._env['tor']
  372. torrc = self._getTorrcFname()
  373. cmdline = [
  374. tor,
  375. "--quiet",
  376. "--ignore-missing-torrc",
  377. "-f", torrc,
  378. "--list-fingerprint",
  379. "--orport", "1",
  380. "--datadirectory", datadir]
  381. try:
  382. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  383. except OSError as e:
  384. # only catch file not found error
  385. if e.errno == errno.ENOENT:
  386. print("Cannot find tor binary %r. Use "
  387. "CHUTNEY_TOR environment variable to set the "
  388. "path, or put the binary into $PATH." % tor)
  389. sys.exit(0)
  390. else:
  391. raise
  392. stdout, stderr = p.communicate()
  393. fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
  394. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  395. print(("Error when calling %r. It gave %r as a fingerprint "
  396. " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
  397. sys.exit(1)
  398. self._env['fingerprint'] = fingerprint
  399. def _getAltAuthLines(self, hasbridgeauth=False):
  400. """Return a combination of AlternateDirAuthority,
  401. AlternateHSAuthority and AlternateBridgeAuthority lines for
  402. this Node, appropriately. Non-authorities return ""."""
  403. if not self._env['authority']:
  404. return ""
  405. datadir = self._env['dir']
  406. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  407. v3id = None
  408. with open(certfile, 'r') as f:
  409. for line in f:
  410. if line.startswith("fingerprint"):
  411. v3id = line.split()[1].strip()
  412. break
  413. assert v3id is not None
  414. if self._env['bridgeauthority']:
  415. # Bridge authorities return AlternateBridgeAuthority with
  416. # the 'bridge' flag set.
  417. options = ("AlternateBridgeAuthority",)
  418. self._env['dirserver_flags'] += " bridge"
  419. else:
  420. # Directory authorities return AlternateDirAuthority with
  421. # the 'hs' and 'v3ident' flags set.
  422. # XXXX This next line is needed for 'bridges' but breaks
  423. # 'basic'
  424. if hasbridgeauth:
  425. options = ("AlternateDirAuthority",)
  426. else:
  427. options = ("DirAuthority",)
  428. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  429. authlines = ""
  430. for authopt in options:
  431. authlines += "%s %s orport=%s" % (
  432. authopt, self._env['nick'], self._env['orport'])
  433. # It's ok to give an authority's IPv6 address to an IPv4-only
  434. # client or relay: it will and must ignore it
  435. if self._env['ipv6_addr'] is not None:
  436. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  437. self._env['orport'])
  438. authlines += " %s %s:%s %s\n" % (
  439. self._env['dirserver_flags'], self._env['ip'],
  440. self._env['dirport'], self._env['fingerprint'])
  441. return authlines
  442. def _getBridgeLines(self):
  443. """Return potential Bridge line for this Node. Non-bridge
  444. relays return "".
  445. """
  446. if not self._env['bridge']:
  447. return ""
  448. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  449. self._env['orport'])
  450. if self._env['ipv6_addr'] is not None:
  451. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  452. self._env['orport'])
  453. return bridgelines
  454. class LocalNodeController(NodeController):
  455. def __init__(self, env):
  456. NodeController.__init__(self, env)
  457. self._env = env
  458. def getPid(self):
  459. """Assuming that this node has its pidfile in ${dir}/pid, return
  460. the pid of the running process, or None if there is no pid in the
  461. file.
  462. """
  463. pidfile = os.path.join(self._env['dir'], 'pid')
  464. if not os.path.exists(pidfile):
  465. return None
  466. with open(pidfile, 'r') as f:
  467. return int(f.read())
  468. def isRunning(self, pid=None):
  469. """Return true iff this node is running. (If 'pid' is provided, we
  470. assume that the pid provided is the one of this node. Otherwise
  471. we call getPid().
  472. """
  473. if pid is None:
  474. pid = self.getPid()
  475. if pid is None:
  476. return False
  477. try:
  478. os.kill(pid, 0) # "kill 0" == "are you there?"
  479. except OSError as e:
  480. if e.errno == errno.ESRCH:
  481. return False
  482. raise
  483. # okay, so the process exists. Say "True" for now.
  484. # XXXX check if this is really tor!
  485. return True
  486. def check(self, listRunning=True, listNonRunning=False):
  487. """See if this node is running, stopped, or crashed. If it's running
  488. and listRunning is set, print a short statement. If it's
  489. stopped and listNonRunning is set, then print a short statement.
  490. If it's crashed, print a statement. Return True if the
  491. node is running, false otherwise.
  492. """
  493. # XXX Split this into "check" and "print" parts.
  494. pid = self.getPid()
  495. nick = self._env['nick']
  496. datadir = self._env['dir']
  497. corefile = "core.%s" % pid
  498. if self.isRunning(pid):
  499. if listRunning:
  500. print("%s is running with PID %s" % (nick, pid))
  501. return True
  502. elif os.path.exists(os.path.join(datadir, corefile)):
  503. if listNonRunning:
  504. print("%s seems to have crashed, and left core file %s" % (
  505. nick, corefile))
  506. return False
  507. else:
  508. if listNonRunning:
  509. print("%s is stopped" % nick)
  510. return False
  511. def hup(self):
  512. """Send a SIGHUP to this node, if it's running."""
  513. pid = self.getPid()
  514. nick = self._env['nick']
  515. if self.isRunning(pid):
  516. print("Sending sighup to %s" % nick)
  517. os.kill(pid, signal.SIGHUP)
  518. return True
  519. else:
  520. print("%s is not running" % nick)
  521. return False
  522. def start(self):
  523. """Try to start this node; return True if we succeeded or it was
  524. already running, False if we failed."""
  525. if self.isRunning():
  526. print("%s is already running" % self._env['nick'])
  527. return True
  528. tor_path = self._env['tor']
  529. torrc = self._getTorrcFname()
  530. cmdline = [
  531. tor_path,
  532. "--quiet",
  533. "-f", torrc,
  534. ]
  535. try:
  536. p = subprocess.Popen(cmdline)
  537. except OSError as e:
  538. # only catch file not found error
  539. if e.errno == errno.ENOENT:
  540. print("Cannot find tor binary %r. Use CHUTNEY_TOR "
  541. "environment variable to set the path, or put the "
  542. "binary into $PATH." % tor_path)
  543. sys.exit(0)
  544. else:
  545. raise
  546. if self.waitOnLaunch():
  547. # this requires that RunAsDaemon is set
  548. p.wait()
  549. else:
  550. # this does not require RunAsDaemon to be set, but is slower.
  551. #
  552. # poll() only catches failures before the call itself
  553. # so let's sleep a little first
  554. # this does, of course, slow down process launch
  555. # which can require an adjustment to the voting interval
  556. #
  557. # avoid writing a newline or space when polling
  558. # so output comes out neatly
  559. sys.stdout.write('.')
  560. sys.stdout.flush()
  561. time.sleep(self._env['poll_launch_time'])
  562. p.poll()
  563. if p.returncode is not None and p.returncode != 0:
  564. if self._env['poll_launch_time'] is None:
  565. print("Couldn't launch %s (%s): %s" % (self._env['nick'],
  566. " ".join(cmdline),
  567. p.returncode))
  568. else:
  569. print("Couldn't poll %s (%s) "
  570. "after waiting %s seconds for launch"
  571. ": %s" % (self._env['nick'],
  572. " ".join(cmdline),
  573. self._env['poll_launch_time'],
  574. p.returncode))
  575. return False
  576. return True
  577. def stop(self, sig=signal.SIGINT):
  578. """Try to stop this node by sending it the signal 'sig'."""
  579. pid = self.getPid()
  580. if not self.isRunning(pid):
  581. print("%s is not running" % self._env['nick'])
  582. return
  583. os.kill(pid, sig)
  584. def cleanup_lockfile(self):
  585. lf = self._env['lockfile']
  586. if not self.isRunning() and os.path.exists(lf):
  587. print('Removing stale lock file for {0} ...'.format(
  588. self._env['nick']))
  589. os.remove(lf)
  590. def waitOnLaunch(self):
  591. """Check whether we can wait() for the tor process to launch"""
  592. # TODO: is this the best place for this code?
  593. # RunAsDaemon default is 0
  594. runAsDaemon = False
  595. with open(self._getTorrcFname(), 'r') as f:
  596. for line in f.readlines():
  597. stline = line.strip()
  598. # if the line isn't all whitespace or blank
  599. if len(stline) > 0:
  600. splline = stline.split()
  601. # if the line has at least two tokens on it
  602. if (len(splline) > 0 and
  603. splline[0].lower() == "RunAsDaemon".lower() and
  604. splline[1] == "1"):
  605. # use the RunAsDaemon value from the torrc
  606. # TODO: multiple values?
  607. runAsDaemon = True
  608. if runAsDaemon:
  609. # we must use wait() instead of poll()
  610. self._env['poll_launch_time'] = None
  611. return True
  612. else:
  613. # we must use poll() instead of wait()
  614. if self._env['poll_launch_time'] is None:
  615. self._env['poll_launch_time'] = \
  616. self._env['poll_launch_time_default']
  617. return False
  618. # XXX: document these options
  619. DEFAULTS = {
  620. 'authority': False,
  621. 'bridgeauthority': False,
  622. 'hasbridgeauth': False,
  623. 'relay': False,
  624. 'bridge': False,
  625. 'hs': False,
  626. 'hs_directory': 'hidden_service',
  627. 'hs-hostname': None,
  628. 'connlimit': 60,
  629. 'net_base_dir': get_absolute_net_path(),
  630. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  631. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  632. 'auth_cert_lifetime': 12,
  633. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  634. # Pre-0.2.8 clients will fail to parse ipv6 auth lines,
  635. # so we default to ipv6_addr None
  636. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  637. 'dirserver_flags': 'no-v2',
  638. 'chutney_dir': get_absolute_chutney_path(),
  639. 'torrc_fname': '${dir}/torrc',
  640. 'orport_base': 5000,
  641. 'dirport_base': 7000,
  642. 'controlport_base': 8000,
  643. 'socksport_base': 9000,
  644. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  645. 'bridges': "Bridge bleargh bad torrc file!",
  646. 'core': True,
  647. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  648. # otherwise, poll after that many seconds (can be fractional/decimal)
  649. 'poll_launch_time': None,
  650. # Used when poll_launch_time is None, but RunAsDaemon is not set
  651. # Set low so that we don't interfere with the voting interval
  652. 'poll_launch_time_default': 0.1,
  653. # the number of bytes of random data we send on each connection
  654. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  655. # the number of times each client will connect
  656. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  657. # Do we want every client to connect to every HS, or one client
  658. # to connect to each HS?
  659. # (Clients choose an exit at random, so this doesn't apply to exits.)
  660. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  661. # How long should verify (and similar commands) wait for a successful
  662. # outcome? (seconds)
  663. # We check BOOTSTRAP_TIME for compatibility with old versions of
  664. # test-network.sh
  665. 'bootstrap_time': int(os.environ.get('CHUTNEY_BOOTSTRAP_TIME',
  666. os.environ.get('BOOTSTRAP_TIME',
  667. 60))),
  668. # the PID of the controlling script (for __OwningControllerProcess)
  669. 'controlling_pid': (int(os.environ.get('CHUTNEY_CONTROLLING_PID', 0))
  670. if 'CHUTNEY_CONTROLLING_PID' in os.environ
  671. else None),
  672. }
  673. class TorEnviron(chutney.Templating.Environ):
  674. """Subclass of chutney.Templating.Environ to implement commonly-used
  675. substitutions.
  676. Environment fields provided:
  677. orport, controlport, socksport, dirport: *Port torrc option
  678. dir: DataDirectory torrc option
  679. nick: Nickname torrc option
  680. tor_gencert: name or path of the tor-gencert binary
  681. auth_passphrase: obsoleted by CookieAuthentication
  682. torrc_template_path: path to chutney torrc_templates directory
  683. hs_hostname: the hostname of the key generated by a hidden service
  684. owning_controller_process: the __OwningControllerProcess torrc line,
  685. disabled if tor should continue after the script exits
  686. Environment fields used:
  687. nodenum: chutney's internal node number for the node
  688. tag: a short text string that represents the type of node
  689. orport_base, controlport_base, socksport_base, dirport_base: the
  690. initial port numbers used by nodenum 0. Each additional node adds
  691. 1 to the port numbers.
  692. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  693. present)
  694. chutney_dir: directory of the chutney source code
  695. tor: name or path of the tor binary
  696. net_base_dir: path to the chutney net directory
  697. hs_directory: name of the hidden service directory
  698. nick: Nickname torrc option (debugging only)
  699. hs-hostname (note hyphen): cached hidden service hostname value
  700. controlling_pid: the PID of the controlling process. After this
  701. process exits, the child tor processes will exit
  702. """
  703. def __init__(self, parent=None, **kwargs):
  704. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  705. def _get_orport(self, my):
  706. return my['orport_base'] + my['nodenum']
  707. def _get_controlport(self, my):
  708. return my['controlport_base'] + my['nodenum']
  709. def _get_socksport(self, my):
  710. return my['socksport_base'] + my['nodenum']
  711. def _get_dirport(self, my):
  712. return my['dirport_base'] + my['nodenum']
  713. def _get_dir(self, my):
  714. return os.path.abspath(os.path.join(my['net_base_dir'],
  715. "nodes",
  716. "%03d%s" % (
  717. my['nodenum'], my['tag'])))
  718. def _get_nick(self, my):
  719. return "test%03d%s" % (my['nodenum'], my['tag'])
  720. def _get_tor_gencert(self, my):
  721. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  722. def _get_auth_passphrase(self, my):
  723. return self['nick'] # OMG TEH SECURE!
  724. def _get_torrc_template_path(self, my):
  725. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  726. def _get_lockfile(self, my):
  727. return os.path.join(self['dir'], 'lock')
  728. # A hs generates its key on first run,
  729. # so check for it at the last possible moment,
  730. # but cache it in memory to avoid repeatedly reading the file
  731. # XXXX - this is not like the other functions in this class,
  732. # as it reads from a file created by the hidden service
  733. def _get_hs_hostname(self, my):
  734. if my['hs-hostname'] is None:
  735. datadir = my['dir']
  736. # a file containing a single line with the hs' .onion address
  737. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  738. 'hostname')
  739. try:
  740. with open(hs_hostname_file, 'r') as hostnamefp:
  741. hostname = hostnamefp.read()
  742. # the hostname file ends with a newline
  743. hostname = hostname.strip()
  744. my['hs-hostname'] = hostname
  745. except IOError as e:
  746. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  747. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  748. return my['hs-hostname']
  749. def _get_owning_controller_process(self, my):
  750. cpid = my['controlling_pid']
  751. if cpid is None:
  752. cpid = 0
  753. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  754. # if we want to leave the network running, or controlling_pid is 1
  755. # (or invalid)
  756. if (os.environ.get('CHUTNEY_START_TIME', 0) < 0 or
  757. os.environ.get('CHUTNEY_BOOTSTRAP_TIME', 0) < 0 or
  758. os.environ.get('CHUTNEY_STOP_TIME', 0) < 0 or
  759. cpid <= 1):
  760. return '#' + ocp_line
  761. else:
  762. return ocp_line
  763. class Network(object):
  764. """A network of Tor nodes, plus functions to manipulate them
  765. """
  766. def __init__(self, defaultEnviron):
  767. self._nodes = []
  768. self._dfltEnv = defaultEnviron
  769. self._nextnodenum = 0
  770. def _addNode(self, n):
  771. n.setNodenum(self._nextnodenum)
  772. self._nextnodenum += 1
  773. self._nodes.append(n)
  774. def move_aside_nodes_dir(self):
  775. """Move aside the nodes directory, if it exists and is not a link.
  776. Used for backwards-compatibility only: nodes is created as a link to
  777. a new directory with a unique name in the current implementation.
  778. """
  779. nodesdir = get_absolute_nodes_path()
  780. # only move the directory if it exists
  781. if not os.path.exists(nodesdir):
  782. return
  783. # and if it's not a link
  784. if os.path.islink(nodesdir):
  785. return
  786. # subtract 1 second to avoid collisions and get the correct ordering
  787. newdir = get_new_absolute_nodes_path(time.time() - 1)
  788. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  789. os.rename(nodesdir, newdir)
  790. def create_new_nodes_dir(self):
  791. """Create a new directory with a unique name, and symlink it to nodes
  792. """
  793. # for backwards compatibility, move aside the old nodes directory
  794. # (if it's not a link)
  795. self.move_aside_nodes_dir()
  796. # the unique directory we'll create
  797. newnodesdir = get_new_absolute_nodes_path()
  798. # the canonical name we'll link it to
  799. nodeslink = get_absolute_nodes_path()
  800. # this path should be unique and should not exist
  801. if os.path.exists(newnodesdir):
  802. raise RuntimeError(
  803. 'get_new_absolute_nodes_path returned a path that exists')
  804. # if this path exists, it must be a link
  805. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  806. raise RuntimeError(
  807. 'get_absolute_nodes_path returned a path that exists and is not a link')
  808. # create the new, uniquely named directory, and link it to nodes
  809. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  810. # this gets created with mode 0700, that's probably ok
  811. mkdir_p(newnodesdir)
  812. try:
  813. os.unlink(nodeslink)
  814. except OSError as e:
  815. # it's ok if the link doesn't exist, we're just about to make it
  816. if e.errno == errno.ENOENT:
  817. pass
  818. else:
  819. raise
  820. os.symlink(newnodesdir, nodeslink)
  821. def _checkConfig(self):
  822. for n in self._nodes:
  823. n.getBuilder().checkConfig(self)
  824. def configure(self):
  825. self.create_new_nodes_dir()
  826. network = self
  827. altauthlines = []
  828. bridgelines = []
  829. builders = [n.getBuilder() for n in self._nodes]
  830. self._checkConfig()
  831. # XXX don't change node names or types or count if anything is
  832. # XXX running!
  833. for b in builders:
  834. b.preConfig(network)
  835. altauthlines.append(b._getAltAuthLines(
  836. self._dfltEnv['hasbridgeauth']))
  837. bridgelines.append(b._getBridgeLines())
  838. self._dfltEnv['authorities'] = "".join(altauthlines)
  839. self._dfltEnv['bridges'] = "".join(bridgelines)
  840. for b in builders:
  841. b.config(network)
  842. for b in builders:
  843. b.postConfig(network)
  844. def status(self):
  845. statuses = [n.getController().check() for n in self._nodes]
  846. n_ok = len([x for x in statuses if x])
  847. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  848. return n_ok == len(self._nodes)
  849. def restart(self):
  850. self.stop()
  851. self.start()
  852. def start(self):
  853. if self._dfltEnv['poll_launch_time'] is not None:
  854. # format polling correctly - avoid printing a newline
  855. sys.stdout.write("Starting nodes")
  856. sys.stdout.flush()
  857. else:
  858. print("Starting nodes")
  859. rv = all([n.getController().start() for n in self._nodes])
  860. # now print a newline unconditionally - this stops poll()ing
  861. # output from being squashed together, at the cost of a blank
  862. # line in wait()ing output
  863. print("")
  864. return rv
  865. def hup(self):
  866. print("Sending SIGHUP to nodes")
  867. return all([n.getController().hup() for n in self._nodes])
  868. def stop(self):
  869. controllers = [n.getController() for n in self._nodes]
  870. for sig, desc in [(signal.SIGINT, "SIGINT"),
  871. (signal.SIGINT, "another SIGINT"),
  872. (signal.SIGKILL, "SIGKILL")]:
  873. print("Sending %s to nodes" % desc)
  874. for c in controllers:
  875. if c.isRunning():
  876. c.stop(sig=sig)
  877. print("Waiting for nodes to finish.")
  878. wrote_dot = False
  879. for n in range(15):
  880. time.sleep(1)
  881. if all(not c.isRunning() for c in controllers):
  882. # make the output clearer by adding a newline
  883. if wrote_dot:
  884. sys.stdout.write("\n")
  885. sys.stdout.flush()
  886. # check for stale lock file when Tor crashes
  887. for c in controllers:
  888. c.cleanup_lockfile()
  889. return
  890. sys.stdout.write(".")
  891. wrote_dot = True
  892. sys.stdout.flush()
  893. for c in controllers:
  894. c.check(listNonRunning=False)
  895. # make the output clearer by adding a newline
  896. if wrote_dot:
  897. sys.stdout.write("\n")
  898. sys.stdout.flush()
  899. def ConfigureNodes(nodelist):
  900. network = _THE_NETWORK
  901. for n in nodelist:
  902. network._addNode(n)
  903. if n._env['bridgeauthority']:
  904. network._dfltEnv['hasbridgeauth'] = True
  905. def getTests():
  906. tests = []
  907. chutney_path = get_absolute_chutney_path()
  908. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  909. chutney_path += "/"
  910. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  911. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  912. tests.append(os.path.splitext(x)[0])
  913. return tests
  914. def usage(network):
  915. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  916. "Known commands are: %s" % (
  917. " ".join(x for x in dir(network)
  918. if not x.startswith("_"))),
  919. "Known tests are: %s" % (
  920. " ".join(getTests()))
  921. ])
  922. def exit_on_error(err_msg):
  923. print("Error: {0}\n".format(err_msg))
  924. print(usage(_THE_NETWORK))
  925. sys.exit(1)
  926. def runConfigFile(verb, data):
  927. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  928. Node=Node,
  929. ConfigureNodes=ConfigureNodes,
  930. _THE_NETWORK=_THE_NETWORK)
  931. exec(data, _GLOBALS)
  932. network = _GLOBALS['_THE_NETWORK']
  933. # let's check if the verb is a valid test and run it
  934. if verb in getTests():
  935. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  936. try:
  937. return test_module.run_test(network)
  938. except AttributeError:
  939. print("Test {!r} has no 'run_test(network)' function".format(verb))
  940. return False
  941. # tell the user we don't know what their verb meant
  942. if not hasattr(network, verb):
  943. print(usage(network))
  944. print("Error: I don't know how to %s." % verb)
  945. return
  946. return getattr(network, verb)()
  947. def parseArgs():
  948. if len(sys.argv) < 3:
  949. exit_on_error("Not enough arguments given.")
  950. if not os.path.isfile(sys.argv[2]):
  951. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  952. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  953. def main():
  954. global _BASE_ENVIRON
  955. global _TORRC_OPTIONS
  956. global _THE_NETWORK
  957. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  958. # _TORRC_OPTIONS gets initialised on demand as a map of
  959. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  960. # Or it can be pre-populated as a static whitelist of options
  961. _TORRC_OPTIONS = dict()
  962. _THE_NETWORK = Network(_BASE_ENVIRON)
  963. args = parseArgs()
  964. f = open(args['network_cfg'])
  965. result = runConfigFile(args['action'], f)
  966. if result is False:
  967. return -1
  968. return 0
  969. if __name__ == '__main__':
  970. sys.exit(main())