TorNet.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  1. #!/usr/bin/env python
  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. # Future imports for Python 2.7, mandatory in 3.0
  10. from __future__ import division
  11. from __future__ import print_function
  12. from __future__ import unicode_literals
  13. import cgitb
  14. import errno
  15. import importlib
  16. import os
  17. import platform
  18. import re
  19. import signal
  20. import shutil
  21. import subprocess
  22. import sys
  23. import time
  24. from chutney.Debug import debug_flag, debug
  25. import chutney.Host
  26. import chutney.Templating
  27. import chutney.Traffic
  28. import chutney.Util
  29. _BASE_ENVIRON = None
  30. _TOR_VERSIONS = None
  31. _TORRC_OPTIONS = None
  32. _THE_NETWORK = None
  33. TORRC_OPTION_WARN_LIMIT = 10
  34. torrc_option_warn_count = 0
  35. # Get verbose tracebacks, so we can diagnose better.
  36. cgitb.enable(format="plain")
  37. class MissingBinaryException(Exception):
  38. pass
  39. def getenv_type(env_var, default, type_, type_name=None):
  40. """
  41. Return the value of the environment variable 'envar' as type_,
  42. or 'default' if no such variable exists.
  43. Raise ValueError using type_name if the environment variable is set,
  44. but type_() raises a ValueError on its value. (If type_name is None
  45. or empty, the ValueError uses type_'s string representation instead.)
  46. """
  47. strval = os.environ.get(env_var)
  48. if strval is None:
  49. return default
  50. try:
  51. return type_(strval)
  52. except ValueError:
  53. if not type_name:
  54. type_name = str(type_)
  55. raise ValueError(("Invalid value for environment variable '{}': "
  56. "expected {}, but got '{}'")
  57. .format(env_var, typename, strval))
  58. def getenv_int(env_var, default):
  59. """
  60. Return the value of the environment variable 'envar' as an int,
  61. or 'default' if no such variable exists.
  62. Raise ValueError if the environment variable is set, but is not an int.
  63. """
  64. return getenv_type(env_var, default, int, type_name='an int')
  65. def getenv_bool(env_var, default):
  66. """
  67. Return the value of the environment variable 'envar' as a bool,
  68. or 'default' if no such variable exists.
  69. Unlike bool(), converts 0, "False", and "No" to False.
  70. Raise ValueError if the environment variable is set, but is not a bool.
  71. """
  72. try:
  73. # Handle integer values
  74. return bool(getenv_int(env_var, default))
  75. except ValueError:
  76. # Handle values that the user probably expects to be False
  77. strval = os.environ.get(env_var)
  78. if strval.lower() in ['false', 'no']:
  79. return False
  80. else:
  81. return getenv_type(env_var, default, bool, type_name='a bool')
  82. def mkdir_p(d, mode=448):
  83. """Create directory 'd' and all of its parents as needed. Unlike
  84. os.makedirs, does not give an error if d already exists.
  85. 448 is the decimal representation of the octal number 0700. Since
  86. python2 only supports 0700 and python3 only supports 0o700, we can use
  87. neither.
  88. Note that python2 and python3 differ in how they create the
  89. permissions for the intermediate directories. In python3, 'mode'
  90. only sets the mode for the last directory created.
  91. """
  92. try:
  93. os.makedirs(d, mode=mode)
  94. except OSError as e:
  95. if e.errno == errno.EEXIST:
  96. return
  97. raise
  98. def make_datadir_subdirectory(datadir, subdir):
  99. """
  100. Create a datadirectory (if necessary) and a subdirectory of
  101. that datadirectory. Ensure that both are mode 700.
  102. """
  103. mkdir_p(datadir)
  104. mkdir_p(os.path.join(datadir, subdir))
  105. def get_absolute_chutney_path():
  106. # use the current directory as the default
  107. # (./chutney already sets CHUTNEY_PATH using the path to the script)
  108. # use tools/test-network.sh if you want chutney to try really hard to find
  109. # itself
  110. relative_chutney_path = os.environ.get('CHUTNEY_PATH', os.getcwd())
  111. return os.path.abspath(relative_chutney_path)
  112. def get_absolute_net_path():
  113. # use the chutney path as the default
  114. absolute_chutney_path = get_absolute_chutney_path()
  115. relative_net_path = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  116. # but what is it relative to?
  117. # let's check if it's in CHUTNEY_PATH first, to preserve
  118. # backwards-compatible behaviour
  119. chutney_net_path = os.path.join(absolute_chutney_path, relative_net_path)
  120. if os.path.isdir(chutney_net_path):
  121. return chutney_net_path
  122. # ok, it's relative to the current directory, whatever that is
  123. return os.path.abspath(relative_net_path)
  124. def get_absolute_nodes_path():
  125. # there's no way to customise this: we really don't need more options
  126. return os.path.join(get_absolute_net_path(), 'nodes')
  127. def get_new_absolute_nodes_path(now=time.time()):
  128. # automatically chosen to prevent path collisions, and result in an ordered
  129. # series of directory path names
  130. # should only be called by 'chutney configure', all other chutney commands
  131. # should use get_absolute_nodes_path()
  132. nodesdir = get_absolute_nodes_path()
  133. newdir = newdirbase = "%s.%d" % (nodesdir, now)
  134. # if the time is the same, fall back to a simple integer count
  135. # (this is very unlikely to happen unless the clock changes: it's not
  136. # possible to run multiple chutney networks at the same time)
  137. i = 0
  138. while os.path.exists(newdir):
  139. i += 1
  140. newdir = "%s.%d" % (newdirbase, i)
  141. return newdir
  142. def _warnMissingTor(tor_path, cmdline, tor_name="tor"):
  143. """Log a warning that the binary tor_name can't be found at tor_path
  144. while running cmdline.
  145. """
  146. print(("Cannot find the {} binary at '{}' for the command line '{}'. " +
  147. "Set the TOR_DIR environment variable to the directory " +
  148. "containing {}.")
  149. .format(tor_name, tor_path, " ".join(cmdline), tor_name))
  150. def run_tor(cmdline, exit_on_missing=True):
  151. """Run the tor command line cmdline, which must start with the path or
  152. name of a tor binary.
  153. Returns the combined stdout and stderr of the process.
  154. If exit_on_missing is true, warn and exit if the tor binary is missing.
  155. Otherwise, raise a MissingBinaryException.
  156. """
  157. if not debug_flag:
  158. cmdline.append("--quiet")
  159. try:
  160. stdouterr = subprocess.check_output(cmdline,
  161. stderr=subprocess.STDOUT,
  162. universal_newlines=True,
  163. bufsize=-1)
  164. debug(stdouterr)
  165. except OSError as e:
  166. # only catch file not found error
  167. if e.errno == errno.ENOENT:
  168. if exit_on_missing:
  169. _warnMissingTor(cmdline[0], cmdline)
  170. sys.exit(1)
  171. else:
  172. raise MissingBinaryException()
  173. else:
  174. raise
  175. except subprocess.CalledProcessError as e:
  176. # only catch file not found error
  177. if e.returncode == 127:
  178. if exit_on_missing:
  179. _warnMissingTor(cmdline[0], cmdline)
  180. sys.exit(1)
  181. else:
  182. raise MissingBinaryException()
  183. else:
  184. raise
  185. return stdouterr
  186. def launch_process(cmdline, tor_name="tor", stdin=None, exit_on_missing=True):
  187. """Launch the command line cmdline, which must start with the path or
  188. name of a binary. Use tor_name as the canonical name of the binary.
  189. Pass stdin to the Popen constructor.
  190. Returns the Popen object for the launched process.
  191. """
  192. if tor_name == "tor" and not debug_flag:
  193. cmdline.append("--quiet")
  194. elif tor_name == "tor-gencert" and debug_flag:
  195. cmdline.append("-v")
  196. try:
  197. p = subprocess.Popen(cmdline,
  198. stdin=stdin,
  199. stdout=subprocess.PIPE,
  200. stderr=subprocess.STDOUT,
  201. universal_newlines=True,
  202. bufsize=-1)
  203. except OSError as e:
  204. # only catch file not found error
  205. if e.errno == errno.ENOENT:
  206. if exit_on_missing:
  207. _warnMissingTor(cmdline[0], cmdline, tor_name=tor_name)
  208. sys.exit(1)
  209. else:
  210. raise MissingBinaryException()
  211. else:
  212. raise
  213. return p
  214. def run_tor_gencert(cmdline, passphrase):
  215. """Run the tor-gencert command line cmdline, which must start with the
  216. path or name of a tor-gencert binary.
  217. Then send passphrase to the stdin of the process.
  218. Returns the combined stdout and stderr of the process.
  219. """
  220. p = launch_process(cmdline,
  221. tor_name="tor-gencert",
  222. stdin=subprocess.PIPE)
  223. (stdouterr, empty_stderr) = p.communicate(passphrase + "\n")
  224. debug(stdouterr)
  225. assert p.returncode == 0 # XXXX BAD!
  226. assert empty_stderr is None
  227. return stdouterr
  228. @chutney.Util.memoized
  229. def tor_exists(tor):
  230. """Return true iff this tor binary exists."""
  231. try:
  232. run_tor([tor, "--quiet", "--version"], exit_on_missing=False)
  233. return True
  234. except MissingBinaryException:
  235. return False
  236. @chutney.Util.memoized
  237. def tor_gencert_exists(gencert):
  238. """Return true iff this tor-gencert binary exists."""
  239. try:
  240. p = launch_process([gencert, "--help"], exit_on_missing=False)
  241. p.wait()
  242. return True
  243. except MissingBinaryException:
  244. return False
  245. @chutney.Util.memoized
  246. def get_tor_version(tor):
  247. """Return the version of the tor binary.
  248. Versions are cached for each unique tor path.
  249. """
  250. cmdline = [
  251. tor,
  252. "--version",
  253. ]
  254. tor_version = run_tor(cmdline)
  255. # clean it up a bit
  256. tor_version = tor_version.strip()
  257. tor_version = tor_version.replace("version ", "")
  258. tor_version = tor_version.replace(").", ")")
  259. # check we received a tor version, and nothing else
  260. assert re.match(r'^[-+.() A-Za-z0-9]+$', tor_version)
  261. return tor_version
  262. @chutney.Util.memoized
  263. def get_torrc_options(tor):
  264. """Return the torrc options supported by the tor binary.
  265. Options are cached for each unique tor path.
  266. """
  267. cmdline = [
  268. tor,
  269. "--list-torrc-options",
  270. ]
  271. opts = run_tor(cmdline)
  272. # check we received a list of options, and nothing else
  273. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  274. torrc_opts = opts.split()
  275. return torrc_opts
  276. @chutney.Util.memoized
  277. def get_tor_modules(tor):
  278. """Check the list of compile-time modules advertised by the given
  279. 'tor' binary, and return a map from module name to a boolean
  280. describing whether it is supported.
  281. Unlisted modules are ones that Tor did not treat as compile-time
  282. optional modules.
  283. """
  284. cmdline = [
  285. tor,
  286. "--list-modules",
  287. "--quiet"
  288. ]
  289. try:
  290. mods = run_tor(cmdline)
  291. except subprocess.CalledProcessError as e:
  292. # Tor doesn't support --list-modules; act as if it said nothing.
  293. mods = ""
  294. supported = {}
  295. for line in mods.split("\n"):
  296. m = re.match(r'^(\S+): (yes|no)', line)
  297. if not m:
  298. continue
  299. supported[m.group(1)] = (m.group(2) == "yes")
  300. return supported
  301. def tor_has_module(tor, modname, default=True):
  302. """Return true iff the given tor binary supports a given compile-time
  303. module. If the module is not listed, return 'default'.
  304. """
  305. return get_tor_modules(tor).get(modname, default)
  306. class Node(object):
  307. """A Node represents a Tor node or a set of Tor nodes. It's created
  308. in a network configuration file.
  309. This class is responsible for holding the user's selected node
  310. configuration, and figuring out how the node needs to be
  311. configured and launched.
  312. """
  313. # Fields:
  314. # _parent
  315. # _env
  316. # _builder
  317. # _controller
  318. ########
  319. # Users are expected to call these:
  320. def __init__(self, parent=None, **kwargs):
  321. self._parent = parent
  322. self._env = self._createEnviron(parent, kwargs)
  323. self._builder = None
  324. self._controller = None
  325. def getN(self, N):
  326. return [Node(self) for _ in range(N)]
  327. def specialize(self, **kwargs):
  328. return Node(parent=self, **kwargs)
  329. def set_runtime(self, key, fn):
  330. """Specify a runtime function that gets invoked to find the
  331. runtime value of a key. It should take a single argument, which
  332. will be an environment.
  333. """
  334. setattr(self._env, "_get_"+key, fn)
  335. ######
  336. # Chutney uses these:
  337. def getBuilder(self):
  338. """Return a NodeBuilder instance to set up this node (that is, to
  339. write all the files that need to be in place so that this
  340. node can be run by a NodeController).
  341. """
  342. if self._builder is None:
  343. self._builder = LocalNodeBuilder(self._env)
  344. return self._builder
  345. def getController(self):
  346. """Return a NodeController instance to control this node (that is,
  347. to start it, stop it, see if it's running, etc.)
  348. """
  349. if self._controller is None:
  350. self._controller = LocalNodeController(self._env)
  351. return self._controller
  352. def setNodenum(self, num):
  353. """Assign a value to the 'nodenum' element of this node. Each node
  354. in a network gets its own nodenum.
  355. """
  356. self._env['nodenum'] = num
  357. #####
  358. # These are internal:
  359. def _createEnviron(self, parent, argdict):
  360. """Return an Environ that delegates to the parent node's Environ (if
  361. there is a parent node), or to the default environment.
  362. """
  363. if parent:
  364. parentenv = parent._env
  365. else:
  366. parentenv = self._getDefaultEnviron()
  367. return TorEnviron(parentenv, **argdict)
  368. def _getDefaultEnviron(self):
  369. """Return the default environment. Any variables that we can't find
  370. set for any particular node, we look for here.
  371. """
  372. return _BASE_ENVIRON
  373. class _NodeCommon(object):
  374. """Internal helper class for functionality shared by some NodeBuilders
  375. and some NodeControllers."""
  376. # XXXX maybe this should turn into a mixin.
  377. def __init__(self, env):
  378. self._env = env
  379. def expand(self, pat, includePath=(".",)):
  380. return chutney.Templating.Template(pat, includePath).format(self._env)
  381. def _getTorrcFname(self):
  382. """Return the name of the file where we'll be writing torrc"""
  383. return self.expand("${torrc_fname}")
  384. class NodeBuilder(_NodeCommon):
  385. """Abstract base class. A NodeBuilder is responsible for doing all the
  386. one-time prep needed to set up a node in a network.
  387. """
  388. def __init__(self, env):
  389. _NodeCommon.__init__(self, env)
  390. def checkConfig(self, net):
  391. """Try to format our torrc; raise an exception if we can't.
  392. """
  393. def preConfig(self, net):
  394. """Called on all nodes before any nodes configure: generates keys as
  395. needed.
  396. """
  397. def config(self, net):
  398. """Called to configure a node: creates a torrc file for it."""
  399. def postConfig(self, net):
  400. """Called on each nodes after all nodes configure."""
  401. def isSupported(self, net):
  402. """Return true if this node appears to have everything it needs;
  403. false otherwise."""
  404. class NodeController(_NodeCommon):
  405. """Abstract base class. A NodeController is responsible for running a
  406. node on the network.
  407. """
  408. def __init__(self, env):
  409. _NodeCommon.__init__(self, env)
  410. def check(self, listRunning=True, listNonRunning=False):
  411. """See if this node is running, stopped, or crashed. If it's running
  412. and listRunning is set, print a short statement. If it's
  413. stopped and listNonRunning is set, then print a short statement.
  414. If it's crashed, print a statement. Return True if the
  415. node is running, false otherwise.
  416. """
  417. def start(self):
  418. """Try to start this node; return True if we succeeded or it was
  419. already running, False if we failed."""
  420. def stop(self, sig=signal.SIGINT):
  421. """Try to stop this node by sending it the signal 'sig'."""
  422. class LocalNodeBuilder(NodeBuilder):
  423. # Environment members used:
  424. # torrc -- which torrc file to use
  425. # torrc_template_path -- path to search for torrc files and include files
  426. # authority -- bool -- are we an authority?
  427. # bridgeauthority -- bool -- are we a bridge authority?
  428. # relay -- bool -- are we a relay?
  429. # bridge -- bool -- are we a bridge?
  430. # hs -- bool -- are we a hidden service?
  431. # nodenum -- int -- set by chutney -- which unique node index is this?
  432. # dir -- path -- set by chutney -- data directory for this tor
  433. # tor_gencert -- path to tor_gencert binary
  434. # tor -- path to tor binary
  435. # auth_cert_lifetime -- lifetime of authority certs, in months.
  436. # ip -- primary IP address (usually IPv4) to listen on
  437. # ipv6_addr -- secondary IP address (usually IPv6) to listen on
  438. # orport, dirport -- used on authorities, relays, and bridges. The orport
  439. # is used for both IPv4 and IPv6, if present
  440. # fingerprint -- used only if authority
  441. # dirserver_flags -- used only if authority
  442. # nick -- nickname of this router
  443. # Environment members set
  444. # fingerprint -- hex router key fingerprint
  445. # nodenum -- int -- set by chutney -- which unique node index is this?
  446. def __init__(self, env):
  447. NodeBuilder.__init__(self, env)
  448. self._env = env
  449. def _createTorrcFile(self, checkOnly=False):
  450. """Write the torrc file for this node, disabling any options
  451. that are not supported by env's tor binary using comments.
  452. If checkOnly, just make sure that the formatting is indeed
  453. possible.
  454. """
  455. global torrc_option_warn_count
  456. fn_out = self._getTorrcFname()
  457. torrc_template = self._getTorrcTemplate()
  458. output = torrc_template.format(self._env)
  459. if checkOnly:
  460. # XXXX Is it time-consuming to format? If so, cache here.
  461. return
  462. # now filter the options we're about to write, commenting out
  463. # the options that the current tor binary doesn't support
  464. tor = self._env['tor']
  465. tor_version = get_tor_version(tor)
  466. torrc_opts = get_torrc_options(tor)
  467. # check if each option is supported before writing it
  468. # Unsupported option values may need special handling.
  469. with open(fn_out, 'w') as f:
  470. # we need to do case-insensitive option comparison
  471. lower_opts = [opt.lower() for opt in torrc_opts]
  472. # keep ends when splitting lines, so we can write them out
  473. # using writelines() without messing around with "\n"s
  474. for line in output.splitlines(True):
  475. # check if the first word on the line is a supported option,
  476. # preserving empty lines and comment lines
  477. sline = line.strip()
  478. if (len(sline) == 0 or
  479. sline[0] == '#' or
  480. sline.split()[0].lower() in lower_opts):
  481. pass
  482. else:
  483. warn_msg = (("The tor binary at {} does not support " +
  484. "the option in the torrc line:\n{}")
  485. .format(tor, line.strip()))
  486. if torrc_option_warn_count < TORRC_OPTION_WARN_LIMIT:
  487. print(warn_msg)
  488. torrc_option_warn_count += 1
  489. else:
  490. debug(warn_msg)
  491. # always dump the full output to the torrc file
  492. line = ("# {} version {} does not support: {}"
  493. .format(tor, tor_version, line))
  494. f.writelines([line])
  495. def _getTorrcTemplate(self):
  496. """Return the template used to write the torrc for this node."""
  497. template_path = self._env['torrc_template_path']
  498. return chutney.Templating.Template("$${include:$torrc}",
  499. includePath=template_path)
  500. def _getFreeVars(self):
  501. """Return a set of the free variables in the torrc template for this
  502. node.
  503. """
  504. template = self._getTorrcTemplate()
  505. return template.freevars(self._env)
  506. def checkConfig(self, net):
  507. """Try to format our torrc; raise an exception if we can't.
  508. """
  509. self._createTorrcFile(checkOnly=True)
  510. def preConfig(self, net):
  511. """Called on all nodes before any nodes configure: generates keys and
  512. hidden service directories as needed.
  513. """
  514. self._makeDataDir()
  515. if self._env['authority']:
  516. self._genAuthorityKey()
  517. if self._env['relay']:
  518. self._genRouterKey()
  519. if self._env['hs']:
  520. self._makeHiddenServiceDir()
  521. def config(self, net):
  522. """Called to configure a node: creates a torrc file for it."""
  523. self._createTorrcFile()
  524. # self._createScripts()
  525. def postConfig(self, net):
  526. """Called on each nodes after all nodes configure."""
  527. # self.net.addNode(self)
  528. pass
  529. def isSupported(self, net):
  530. """Return true if this node appears to have everything it needs;
  531. false otherwise."""
  532. if not tor_exists(self._env['tor']):
  533. print("No binary found for %r"%self._env['tor'])
  534. return False
  535. if self._env['authority']:
  536. if not tor_has_module(self._env['tor'], "dirauth"):
  537. print("No dirauth support in %r"%self._env['tor'])
  538. return False
  539. if not tor_gencert_exists(self._env['tor-gencert']):
  540. print("No binary found for tor-gencert %r"%self._env['tor-gencrrt'])
  541. def _makeDataDir(self):
  542. """Create the data directory (with keys subdirectory) for this node.
  543. """
  544. datadir = self._env['dir']
  545. make_datadir_subdirectory(datadir, "keys")
  546. def _makeHiddenServiceDir(self):
  547. """Create the hidden service subdirectory for this node.
  548. The directory name is stored under the 'hs_directory' environment
  549. key. It is combined with the 'dir' data directory key to yield the
  550. path to the hidden service directory.
  551. """
  552. datadir = self._env['dir']
  553. make_datadir_subdirectory(datadir, self._env['hs_directory'])
  554. def _genAuthorityKey(self):
  555. """Generate an authority identity and signing key for this authority,
  556. if they do not already exist."""
  557. datadir = self._env['dir']
  558. tor_gencert = self._env['tor_gencert']
  559. lifetime = self._env['auth_cert_lifetime']
  560. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  561. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  562. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  563. addr = self.expand("${ip}:${dirport}")
  564. passphrase = self._env['auth_passphrase']
  565. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  566. return
  567. cmdline = [
  568. tor_gencert,
  569. '--create-identity-key',
  570. '--passphrase-fd', '0',
  571. '-i', idfile,
  572. '-s', skfile,
  573. '-c', certfile,
  574. '-m', str(lifetime),
  575. '-a', addr,
  576. ]
  577. # nicknames are testNNNaa[OLD], but we want them to look tidy
  578. print("Creating identity key for {:12} with {}"
  579. .format(self._env['nick'], cmdline[0]))
  580. debug("Identity key path '{}', command '{}'"
  581. .format(idfile, " ".join(cmdline)))
  582. run_tor_gencert(cmdline, passphrase)
  583. def _genRouterKey(self):
  584. """Generate an identity key for this router, unless we already have,
  585. and set up the 'fingerprint' entry in the Environ.
  586. """
  587. datadir = self._env['dir']
  588. tor = self._env['tor']
  589. torrc = self._getTorrcFname()
  590. cmdline = [
  591. tor,
  592. "--ignore-missing-torrc",
  593. "-f", torrc,
  594. "--list-fingerprint",
  595. "--orport", "1",
  596. "--datadirectory", datadir,
  597. ]
  598. stdouterr = run_tor(cmdline)
  599. fingerprint = "".join((stdouterr.rstrip().split('\n')[-1]).split()[1:])
  600. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  601. print("Error when getting fingerprint using '%r'. It output '%r'."
  602. .format(" ".join(cmdline), stdouterr))
  603. sys.exit(1)
  604. self._env['fingerprint'] = fingerprint
  605. def _getAltAuthLines(self, hasbridgeauth=False):
  606. """Return a combination of AlternateDirAuthority,
  607. and AlternateBridgeAuthority lines for
  608. this Node, appropriately. Non-authorities return ""."""
  609. if not self._env['authority']:
  610. return ""
  611. datadir = self._env['dir']
  612. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  613. v3id = None
  614. with open(certfile, 'r') as f:
  615. for line in f:
  616. if line.startswith("fingerprint"):
  617. v3id = line.split()[1].strip()
  618. break
  619. assert v3id is not None
  620. if self._env['bridgeauthority']:
  621. # Bridge authorities return AlternateBridgeAuthority with
  622. # the 'bridge' flag set.
  623. options = ("AlternateBridgeAuthority",)
  624. self._env['dirserver_flags'] += " bridge"
  625. else:
  626. # Directory authorities return AlternateDirAuthority with
  627. # the 'v3ident' flag set.
  628. # XXXX This next line is needed for 'bridges' but breaks
  629. # 'basic'
  630. if hasbridgeauth:
  631. options = ("AlternateDirAuthority",)
  632. else:
  633. options = ("DirAuthority",)
  634. self._env['dirserver_flags'] += " v3ident=%s" % v3id
  635. authlines = ""
  636. for authopt in options:
  637. authlines += "%s %s orport=%s" % (
  638. authopt, self._env['nick'], self._env['orport'])
  639. # It's ok to give an authority's IPv6 address to an IPv4-only
  640. # client or relay: it will and must ignore it
  641. # and yes, the orport is the same on IPv4 and IPv6
  642. if self._env['ipv6_addr'] is not None:
  643. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  644. self._env['orport'])
  645. authlines += " %s %s:%s %s\n" % (
  646. self._env['dirserver_flags'], self._env['ip'],
  647. self._env['dirport'], self._env['fingerprint'])
  648. return authlines
  649. def _getBridgeLines(self):
  650. """Return potential Bridge line for this Node. Non-bridge
  651. relays return "".
  652. """
  653. if not self._env['bridge']:
  654. return ""
  655. if self._env['pt_bridge']:
  656. port = self._env['ptport']
  657. transport = self._env['pt_transport']
  658. extra = self._env['pt_extra']
  659. else:
  660. # the orport is the same on IPv4 and IPv6
  661. port = self._env['orport']
  662. transport = ""
  663. extra = ""
  664. BRIDGE_LINE_TEMPLATE = "Bridge %s %s:%s %s %s\n"
  665. bridgelines = BRIDGE_LINE_TEMPLATE % (transport,
  666. self._env['ip'],
  667. port,
  668. self._env['fingerprint'],
  669. extra)
  670. if self._env['ipv6_addr'] is not None:
  671. bridgelines += BRIDGE_LINE_TEMPLATE % (transport,
  672. self._env['ipv6_addr'],
  673. port,
  674. self._env['fingerprint'],
  675. extra)
  676. return bridgelines
  677. class LocalNodeController(NodeController):
  678. def __init__(self, env):
  679. NodeController.__init__(self, env)
  680. self._env = env
  681. def getNick(self):
  682. """Return the nickname for this node."""
  683. return self._env['nick']
  684. def getPid(self):
  685. """Assuming that this node has its pidfile in ${dir}/pid, return
  686. the pid of the running process, or None if there is no pid in the
  687. file.
  688. """
  689. pidfile = os.path.join(self._env['dir'], 'pid')
  690. if not os.path.exists(pidfile):
  691. return None
  692. with open(pidfile, 'r') as f:
  693. return int(f.read())
  694. def isRunning(self, pid=None):
  695. """Return true iff this node is running. (If 'pid' is provided, we
  696. assume that the pid provided is the one of this node. Otherwise
  697. we call getPid().
  698. """
  699. if pid is None:
  700. pid = self.getPid()
  701. if pid is None:
  702. return False
  703. try:
  704. os.kill(pid, 0) # "kill 0" == "are you there?"
  705. except OSError as e:
  706. if e.errno == errno.ESRCH:
  707. return False
  708. raise
  709. # okay, so the process exists. Say "True" for now.
  710. # XXXX check if this is really tor!
  711. return True
  712. def check(self, listRunning=True, listNonRunning=False):
  713. """See if this node is running, stopped, or crashed. If it's running
  714. and listRunning is set, print a short statement. If it's
  715. stopped and listNonRunning is set, then print a short statement.
  716. If it's crashed, print a statement. Return True if the
  717. node is running, false otherwise.
  718. """
  719. # XXX Split this into "check" and "print" parts.
  720. pid = self.getPid()
  721. nick = self._env['nick']
  722. datadir = self._env['dir']
  723. corefile = "core.%s" % pid
  724. tor_version = get_tor_version(self._env['tor'])
  725. if self.isRunning(pid):
  726. if listRunning:
  727. # PIDs are typically 65535 or less
  728. print("{:12} is running with PID {:5}: {}"
  729. .format(nick, pid, tor_version))
  730. return True
  731. elif os.path.exists(os.path.join(datadir, corefile)):
  732. if listNonRunning:
  733. print("{:12} seems to have crashed, and left core file {}: {}"
  734. .format(nick, corefile, tor_version))
  735. return False
  736. else:
  737. if listNonRunning:
  738. print("{:12} is stopped: {}"
  739. .format(nick, tor_version))
  740. return False
  741. def hup(self):
  742. """Send a SIGHUP to this node, if it's running."""
  743. pid = self.getPid()
  744. nick = self._env['nick']
  745. if self.isRunning(pid):
  746. print("Sending sighup to {}".format(nick))
  747. os.kill(pid, signal.SIGHUP)
  748. return True
  749. else:
  750. print("{:12} is not running".format(nick))
  751. return False
  752. def start(self):
  753. """Try to start this node; return True if we succeeded or it was
  754. already running, False if we failed."""
  755. if self.isRunning():
  756. print("{:12} is already running".format(self._env['nick']))
  757. return True
  758. tor_path = self._env['tor']
  759. torrc = self._getTorrcFname()
  760. cmdline = []
  761. if self._env['numa_settings'] is not None:
  762. (numa_node, processors) = self._env['numa_settings']
  763. cmdline.extend([
  764. 'numactl',
  765. '--membind={}'.format(numa_node),
  766. '--physcpubind={}'.format(','.join(map(str, processors))),
  767. ])
  768. #
  769. cmdline.extend([
  770. tor_path,
  771. "-f", torrc,
  772. ])
  773. p = launch_process(cmdline)
  774. if self.waitOnLaunch():
  775. # this requires that RunAsDaemon is set
  776. (stdouterr, empty_stderr) = p.communicate()
  777. debug(stdouterr)
  778. assert empty_stderr is None
  779. else:
  780. # this does not require RunAsDaemon to be set, but is slower.
  781. #
  782. # poll() only catches failures before the call itself
  783. # so let's sleep a little first
  784. # this does, of course, slow down process launch
  785. # which can require an adjustment to the voting interval
  786. #
  787. # avoid writing a newline or space when polling
  788. # so output comes out neatly
  789. sys.stdout.write('.')
  790. sys.stdout.flush()
  791. time.sleep(self._env['poll_launch_time'])
  792. p.poll()
  793. if p.returncode is not None and p.returncode != 0:
  794. if self._env['poll_launch_time'] is None:
  795. print(("Couldn't launch {:12} command '{}': " +
  796. "exit {}, output '{}'")
  797. .format(self._env['nick'],
  798. " ".join(cmdline),
  799. p.returncode,
  800. stdouterr))
  801. else:
  802. print(("Couldn't poll {:12} command '{}' " +
  803. "after waiting {} seconds for launch: " +
  804. "exit {}").format(self._env['nick'],
  805. " ".join(cmdline),
  806. self._env['poll_launch_time'],
  807. p.returncode))
  808. return False
  809. return True
  810. def stop(self, sig=signal.SIGINT):
  811. """Try to stop this node by sending it the signal 'sig'."""
  812. pid = self.getPid()
  813. if not self.isRunning(pid):
  814. print("{:12} is not running".format(self._env['nick']))
  815. return
  816. os.kill(pid, sig)
  817. def cleanup_lockfile(self):
  818. lf = self._env['lockfile']
  819. if not self.isRunning() and os.path.exists(lf):
  820. debug("Removing stale lock file for {} ..."
  821. .format(self._env['nick']))
  822. os.remove(lf)
  823. def waitOnLaunch(self):
  824. """Check whether we can wait() for the tor process to launch"""
  825. # TODO: is this the best place for this code?
  826. # RunAsDaemon default is 0
  827. runAsDaemon = False
  828. with open(self._getTorrcFname(), 'r') as f:
  829. for line in f.readlines():
  830. stline = line.strip()
  831. # if the line isn't all whitespace or blank
  832. if len(stline) > 0:
  833. splline = stline.split()
  834. # if the line has at least two tokens on it
  835. if (len(splline) > 0 and
  836. splline[0].lower() == "RunAsDaemon".lower() and
  837. splline[1] == "1"):
  838. # use the RunAsDaemon value from the torrc
  839. # TODO: multiple values?
  840. runAsDaemon = True
  841. if runAsDaemon:
  842. # we must use wait() instead of poll()
  843. self._env['poll_launch_time'] = None
  844. return True
  845. else:
  846. # we must use poll() instead of wait()
  847. if self._env['poll_launch_time'] is None:
  848. self._env['poll_launch_time'] = \
  849. self._env['poll_launch_time_default']
  850. return False
  851. def getLogfile(self, info=False):
  852. """Return the expected path to the logfile for this instance."""
  853. datadir = self._env['dir']
  854. if info:
  855. logname = "info.log"
  856. else:
  857. logname = "notice.log"
  858. return os.path.join(datadir, logname)
  859. def getLastBootstrapStatus(self):
  860. """Look through the logs and return the last bootstrap message
  861. received as a 3-tuple of percentage complete, keyword
  862. (optional), and message.
  863. """
  864. logfname = self.getLogfile()
  865. if not os.path.exists(logfname):
  866. return (-200, "no_logfile", "There is no logfile yet.")
  867. percent,keyword,message=-100,"no_message","No bootstrap messages yet."
  868. with open(logfname, 'r') as f:
  869. for line in f:
  870. m = re.search(r'Bootstrapped (\d+)%(?: \(([^\)]*)\))?: (.*)',
  871. line)
  872. if m:
  873. percent, keyword, message = m.groups()
  874. percent = int(percent)
  875. return (percent, keyword, message)
  876. def isBootstrapped(self):
  877. """Return true iff the logfile says that this instance is
  878. bootstrapped."""
  879. pct, _, _ = self.getLastBootstrapStatus()
  880. return pct == 100
  881. # XXX: document these options
  882. DEFAULTS = {
  883. 'authority': False,
  884. 'bridgeauthority': False,
  885. 'hasbridgeauth': False,
  886. 'relay': False,
  887. 'bridge': False,
  888. 'pt_bridge': False,
  889. 'pt_transport' : "",
  890. 'pt_extra' : "",
  891. 'hs': False,
  892. 'hs_directory': 'hidden_service',
  893. 'hs-hostname': None,
  894. 'connlimit': 60,
  895. 'net_base_dir': get_absolute_net_path(),
  896. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  897. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  898. 'auth_cert_lifetime': 12,
  899. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  900. # we default to ipv6_addr None to support IPv4-only systems
  901. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  902. 'dirserver_flags': 'no-v2',
  903. 'chutney_dir': get_absolute_chutney_path(),
  904. 'torrc_fname': '${dir}/torrc',
  905. 'orport_base': 5000,
  906. 'dirport_base': 7000,
  907. 'controlport_base': 8000,
  908. 'socksport_base': 9000,
  909. 'extorport_base' : 9500,
  910. 'ptport_base' : 9900,
  911. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  912. 'bridges': "Bridge bleargh bad torrc file!",
  913. 'core': True,
  914. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  915. # otherwise, poll after that many seconds (can be fractional/decimal)
  916. 'poll_launch_time': None,
  917. # Used when poll_launch_time is None, but RunAsDaemon is not set
  918. # Set low so that we don't interfere with the voting interval
  919. 'poll_launch_time_default': 0.1,
  920. # the number of bytes of random data we send on each connection
  921. 'data_bytes': getenv_int('CHUTNEY_DATA_BYTES', 10 * 1024),
  922. # the number of times each client will connect
  923. 'connection_count': getenv_int('CHUTNEY_CONNECTIONS', 1),
  924. # Do we want every client to connect to every HS, or one client
  925. # to connect to each HS?
  926. # (Clients choose an exit at random, so this doesn't apply to exits.)
  927. 'hs_multi_client': getenv_int('CHUTNEY_HS_MULTI_CLIENT', 0),
  928. # How long should verify (and similar commands) wait for a successful
  929. # outcome? (seconds)
  930. # We check BOOTSTRAP_TIME for compatibility with old versions of
  931. # test-network.sh
  932. 'bootstrap_time': getenv_int('CHUTNEY_BOOTSTRAP_TIME',
  933. getenv_int('BOOTSTRAP_TIME',
  934. 60)),
  935. # the PID of the controlling script (for __OwningControllerProcess)
  936. 'controlling_pid': getenv_int('CHUTNEY_CONTROLLING_PID', 0),
  937. # a DNS config file (for ServerDNSResolvConfFile)
  938. 'dns_conf': (os.environ.get('CHUTNEY_DNS_CONF', '/etc/resolv.conf')
  939. if 'CHUTNEY_DNS_CONF' in os.environ
  940. else None),
  941. # The phase at which this instance needs to be
  942. # configured/launched, if we're doing multiphase
  943. # configuration/launch.
  944. 'config_phase' : 1,
  945. 'launch_phase' : 1,
  946. 'CUR_CONFIG_PHASE': getenv_int('CHUTNEY_CONFIG_PHASE', 1),
  947. 'CUR_LAUNCH_PHASE': getenv_int('CHUTNEY_LAUNCH_PHASE', 1),
  948. # the Sandbox torrc option value
  949. # defaults to 1 on Linux, and 0 otherwise
  950. 'sandbox': int(getenv_bool('CHUTNEY_TOR_SANDBOX',
  951. platform.system() == 'Linux')),
  952. 'num_cpus': None,
  953. 'numa_settings': None,
  954. 'measureme_log_dir': '${dir}',
  955. }
  956. class TorEnviron(chutney.Templating.Environ):
  957. """Subclass of chutney.Templating.Environ to implement commonly-used
  958. substitutions.
  959. Environment fields provided:
  960. orport, controlport, socksport, dirport: *Port torrc option
  961. dir: DataDirectory torrc option
  962. nick: Nickname torrc option
  963. tor_gencert: name or path of the tor-gencert binary
  964. auth_passphrase: obsoleted by CookieAuthentication
  965. torrc_template_path: path to chutney torrc_templates directory
  966. hs_hostname: the hostname of the key generated by a hidden service
  967. owning_controller_process: the __OwningControllerProcess torrc line,
  968. disabled if tor should continue after the script exits
  969. server_dns_resolv_conf: the ServerDNSResolvConfFile torrc line,
  970. disabled if tor should use the default DNS conf.
  971. If the dns_conf file is missing, this option is also disabled:
  972. otherwise, exits would not work due to tor bug #21900.
  973. sandbox: Sets Sandbox to the value of CHUTNEY_TOR_SANDBOX.
  974. The default is 1 on Linux, and 0 on other platforms.
  975. Chutney users can disable the sandbox using:
  976. export CHUTNEY_TOR_SANDBOX=0
  977. if it doesn't work on their version of glibc.
  978. Environment fields used:
  979. nodenum: chutney's internal node number for the node
  980. tag: a short text string that represents the type of node
  981. orport_base, controlport_base, socksport_base, dirport_base: the
  982. initial port numbers used by nodenum 0. Each additional node adds
  983. 1 to the port numbers.
  984. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  985. present)
  986. chutney_dir: directory of the chutney source code
  987. tor: name or path of the tor binary
  988. net_base_dir: path to the chutney net directory
  989. hs_directory: name of the hidden service directory
  990. nick: Nickname torrc option (debugging only)
  991. hs-hostname (note hyphen): cached hidden service hostname value
  992. controlling_pid: the PID of the controlling process. After this
  993. process exits, the child tor processes will exit
  994. dns_conf: the path to a DNS config file for Tor Exits. If this file
  995. is empty or unreadable, Tor will try 127.0.0.1:53.
  996. """
  997. def __init__(self, parent=None, **kwargs):
  998. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  999. def _get_orport(self, my):
  1000. return my['orport_base'] + my['nodenum']
  1001. def _get_controlport(self, my):
  1002. return my['controlport_base'] + my['nodenum']
  1003. def _get_socksport(self, my):
  1004. return my['socksport_base'] + my['nodenum']
  1005. def _get_dirport(self, my):
  1006. return my['dirport_base'] + my['nodenum']
  1007. def _get_extorport(self, my):
  1008. return my['extorport_base'] + my['nodenum']
  1009. def _get_ptport(self, my):
  1010. return my['ptport_base'] + my['nodenum']
  1011. def _get_dir(self, my):
  1012. return os.path.abspath(os.path.join(my['net_base_dir'],
  1013. "nodes",
  1014. "%03d%s" % (
  1015. my['nodenum'], my['tag'])))
  1016. def _get_nick(self, my):
  1017. return "test%03d%s" % (my['nodenum'], my['tag'])
  1018. def _get_tor_gencert(self, my):
  1019. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  1020. def _get_auth_passphrase(self, my):
  1021. return self['nick'] # OMG TEH SECURE!
  1022. def _get_torrc_template_path(self, my):
  1023. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  1024. def _get_lockfile(self, my):
  1025. return os.path.join(self['dir'], 'lock')
  1026. # A hs generates its key on first run,
  1027. # so check for it at the last possible moment,
  1028. # but cache it in memory to avoid repeatedly reading the file
  1029. # XXXX - this is not like the other functions in this class,
  1030. # as it reads from a file created by the hidden service
  1031. def _get_hs_hostname(self, my):
  1032. if my['hs-hostname'] is None:
  1033. datadir = my['dir']
  1034. # a file containing a single line with the hs' .onion address
  1035. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  1036. 'hostname')
  1037. try:
  1038. with open(hs_hostname_file, 'r') as hostnamefp:
  1039. hostname = hostnamefp.read()
  1040. # the hostname file ends with a newline
  1041. hostname = hostname.strip()
  1042. my['hs-hostname'] = hostname
  1043. except IOError as e:
  1044. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  1045. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  1046. return my['hs-hostname']
  1047. def _get_num_cpus_line(self, my):
  1048. num_cpus = my['num_cpus']
  1049. num_cpus_line = 'NumCPUs {}'.format(num_cpus)
  1050. if num_cpus is None:
  1051. num_cpus_line = '#' + num_cpus_line
  1052. return num_cpus_line
  1053. def _get_owning_controller_process(self, my):
  1054. cpid = my['controlling_pid']
  1055. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  1056. # if we want to leave the network running, or controlling_pid is 1
  1057. # (or invalid)
  1058. if cpid <= 1:
  1059. return '#' + ocp_line
  1060. else:
  1061. return ocp_line
  1062. # the default resolv.conf path is set at compile time
  1063. # there's no easy way to get it out of tor, so we use the typical value
  1064. DEFAULT_DNS_RESOLV_CONF = "/etc/resolv.conf"
  1065. # if we can't find the specified file, use this one as a substitute
  1066. OFFLINE_DNS_RESOLV_CONF = "/dev/null"
  1067. def _get_server_dns_resolv_conf(self, my):
  1068. if my['dns_conf'] == "":
  1069. # if the user asked for tor's default
  1070. return "#ServerDNSResolvConfFile using tor's compile-time default"
  1071. elif my['dns_conf'] is None:
  1072. # if there is no DNS conf file set
  1073. debug("CHUTNEY_DNS_CONF not specified, using '{}'."
  1074. .format(TorEnviron.DEFAULT_DNS_RESOLV_CONF))
  1075. dns_conf = TorEnviron.DEFAULT_DNS_RESOLV_CONF
  1076. else:
  1077. dns_conf = my['dns_conf']
  1078. dns_conf = os.path.abspath(dns_conf)
  1079. # work around Tor bug #21900, where exits fail when the DNS conf
  1080. # file does not exist, or is a broken symlink
  1081. # (os.path.exists returns False for broken symbolic links)
  1082. if not os.path.exists(dns_conf):
  1083. # Issue a warning so the user notices
  1084. print("CHUTNEY_DNS_CONF '{}' does not exist, using '{}'."
  1085. .format(dns_conf, TorEnviron.OFFLINE_DNS_RESOLV_CONF))
  1086. dns_conf = TorEnviron.OFFLINE_DNS_RESOLV_CONF
  1087. return "ServerDNSResolvConfFile %s" % (dns_conf)
  1088. KNOWN_REQUIREMENTS = {
  1089. "IPV6": chutney.Host.is_ipv6_supported
  1090. }
  1091. class Network(object):
  1092. """A network of Tor nodes, plus functions to manipulate them
  1093. """
  1094. def __init__(self, defaultEnviron):
  1095. self._nodes = []
  1096. self._requirements = []
  1097. self._dfltEnv = defaultEnviron
  1098. self._nextnodenum = 0
  1099. def _addNode(self, n):
  1100. n.setNodenum(self._nextnodenum)
  1101. self._nextnodenum += 1
  1102. self._nodes.append(n)
  1103. def _addRequirement(self, requirement):
  1104. requirement = requirement.upper()
  1105. if requirement not in KNOWN_REQUIREMENTS:
  1106. raise RuntimemeError(("Unrecognized requirement %r"%requirement))
  1107. self._requirements.append(requirement)
  1108. def move_aside_nodes_dir(self):
  1109. """Move aside the nodes directory, if it exists and is not a link.
  1110. Used for backwards-compatibility only: nodes is created as a link to
  1111. a new directory with a unique name in the current implementation.
  1112. """
  1113. nodesdir = get_absolute_nodes_path()
  1114. # only move the directory if it exists
  1115. if not os.path.exists(nodesdir):
  1116. return
  1117. # and if it's not a link
  1118. if os.path.islink(nodesdir):
  1119. return
  1120. # subtract 1 second to avoid collisions and get the correct ordering
  1121. newdir = get_new_absolute_nodes_path(time.time() - 1)
  1122. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  1123. os.rename(nodesdir, newdir)
  1124. def create_new_nodes_dir(self):
  1125. """Create a new directory with a unique name, and symlink it to nodes
  1126. """
  1127. # for backwards compatibility, move aside the old nodes directory
  1128. # (if it's not a link)
  1129. self.move_aside_nodes_dir()
  1130. # the unique directory we'll create
  1131. newnodesdir = get_new_absolute_nodes_path()
  1132. # the canonical name we'll link it to
  1133. nodeslink = get_absolute_nodes_path()
  1134. # this path should be unique and should not exist
  1135. if os.path.exists(newnodesdir):
  1136. raise RuntimeError(
  1137. 'get_new_absolute_nodes_path returned a path that exists')
  1138. # if this path exists, it must be a link
  1139. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  1140. raise RuntimeError(
  1141. 'get_absolute_nodes_path returned a path that exists and is not a link')
  1142. # create the new, uniquely named directory, and link it to nodes
  1143. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  1144. # this gets created with mode 0700, that's probably ok
  1145. mkdir_p(newnodesdir)
  1146. try:
  1147. os.unlink(nodeslink)
  1148. except OSError as e:
  1149. # it's ok if the link doesn't exist, we're just about to make it
  1150. if e.errno == errno.ENOENT:
  1151. pass
  1152. else:
  1153. raise
  1154. os.symlink(newnodesdir, nodeslink)
  1155. def _checkConfig(self):
  1156. for n in self._nodes:
  1157. n.getBuilder().checkConfig(self)
  1158. def supported(self):
  1159. """Check whether this network is supported by the set of binaries
  1160. and host information we have.
  1161. """
  1162. missing_any = False
  1163. for r in self._requirements:
  1164. if not KNOWN_REQUIREMENTS[r]():
  1165. print(("Can't run this network: %s is missing."))
  1166. missing_any = True
  1167. for n in self._nodes:
  1168. if not n.getBuilder().isSupported(self):
  1169. missing_any = False
  1170. if missing_any:
  1171. sys.exit(1)
  1172. def configure(self):
  1173. phase = self._dfltEnv['CUR_CONFIG_PHASE']
  1174. if phase == 1:
  1175. self.create_new_nodes_dir()
  1176. network = self
  1177. altauthlines = []
  1178. bridgelines = []
  1179. all_builders = [ n.getBuilder() for n in self._nodes ]
  1180. builders = [ b for b in all_builders
  1181. if b._env['config_phase'] == phase ]
  1182. self._checkConfig()
  1183. # XXX don't change node names or types or count if anything is
  1184. # XXX running!
  1185. for b in all_builders:
  1186. b.preConfig(network)
  1187. altauthlines.append(b._getAltAuthLines(
  1188. self._dfltEnv['hasbridgeauth']))
  1189. bridgelines.append(b._getBridgeLines())
  1190. self._dfltEnv['authorities'] = "".join(altauthlines)
  1191. self._dfltEnv['bridges'] = "".join(bridgelines)
  1192. for b in builders:
  1193. b.config(network)
  1194. for b in builders:
  1195. b.postConfig(network)
  1196. def status(self):
  1197. statuses = [n.getController().check(listNonRunning=True)
  1198. for n in self._nodes]
  1199. n_ok = len([x for x in statuses if x])
  1200. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  1201. return n_ok == len(self._nodes)
  1202. def restart(self):
  1203. self.stop()
  1204. self.start()
  1205. def start(self):
  1206. # format polling correctly - avoid printing a newline
  1207. sys.stdout.write("Starting nodes")
  1208. sys.stdout.flush()
  1209. rv = all([n.getController().start() for n in self._nodes
  1210. if n._env['launch_phase'] ==
  1211. self._dfltEnv['CUR_LAUNCH_PHASE']])
  1212. # now print a newline unconditionally - this stops poll()ing
  1213. # output from being squashed together, at the cost of a blank
  1214. # line in wait()ing output
  1215. print("")
  1216. return rv
  1217. def hup(self):
  1218. print("Sending SIGHUP to nodes")
  1219. return all([n.getController().hup() for n in self._nodes])
  1220. def wait_for_bootstrap(self):
  1221. print("Waiting for nodes to bootstrap...")
  1222. limit = getenv_int("CHUTNEY_START_TIME", 60)
  1223. delay = 0.5
  1224. controllers = [n.getController() for n in self._nodes]
  1225. elapsed = 0.0
  1226. most_recent_status = [ None ] * len(controllers)
  1227. while True:
  1228. all_bootstrapped = True
  1229. most_recent_status = [ ]
  1230. for c in controllers:
  1231. pct, kwd, msg = c.getLastBootstrapStatus()
  1232. most_recent_status.append((pct, kwd, msg))
  1233. if pct != 100:
  1234. all_bootstrapped = False
  1235. if all_bootstrapped:
  1236. print("Everything bootstrapped after %s sec"%elapsed)
  1237. return True
  1238. if elapsed >= limit:
  1239. break
  1240. time.sleep(delay)
  1241. elapsed += delay
  1242. print("Bootstrap failed. Node status:")
  1243. for c, status in zip(controllers,most_recent_status):
  1244. c.check(listRunning=False, listNonRunning=True)
  1245. print("{}: {}".format(c.getNick(), status))
  1246. return False
  1247. def stop(self):
  1248. controllers = [n.getController() for n in self._nodes]
  1249. for sig, desc in [(signal.SIGINT, "SIGINT"),
  1250. (signal.SIGINT, "another SIGINT"),
  1251. (signal.SIGKILL, "SIGKILL")]:
  1252. print("Sending %s to nodes" % desc)
  1253. for c in controllers:
  1254. if c.isRunning():
  1255. c.stop(sig=sig)
  1256. print("Waiting for nodes to finish.")
  1257. wrote_dot = False
  1258. for n in range(15):
  1259. time.sleep(1)
  1260. if all(not c.isRunning() for c in controllers):
  1261. # make the output clearer by adding a newline
  1262. if wrote_dot:
  1263. sys.stdout.write("\n")
  1264. sys.stdout.flush()
  1265. # check for stale lock file when Tor crashes
  1266. for c in controllers:
  1267. c.cleanup_lockfile()
  1268. return
  1269. sys.stdout.write(".")
  1270. wrote_dot = True
  1271. sys.stdout.flush()
  1272. for c in controllers:
  1273. c.check(listNonRunning=False)
  1274. # make the output clearer by adding a newline
  1275. if wrote_dot:
  1276. sys.stdout.write("\n")
  1277. sys.stdout.flush()
  1278. def Require(feature):
  1279. network = _THE_NETWORK
  1280. network._addRequirement(feature)
  1281. def ConfigureNodes(nodelist):
  1282. network = _THE_NETWORK
  1283. for n in nodelist:
  1284. network._addNode(n)
  1285. if n._env['bridgeauthority']:
  1286. network._dfltEnv['hasbridgeauth'] = True
  1287. def getTests():
  1288. tests = []
  1289. chutney_path = get_absolute_chutney_path()
  1290. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  1291. chutney_path += "/"
  1292. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  1293. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  1294. tests.append(os.path.splitext(x)[0])
  1295. return tests
  1296. def usage(network):
  1297. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  1298. "Known commands are: %s" % (
  1299. " ".join(x for x in dir(network)
  1300. if not x.startswith("_"))),
  1301. "Known tests are: %s" % (
  1302. " ".join(getTests()))
  1303. ])
  1304. def exit_on_error(err_msg):
  1305. print("Error: {0}\n".format(err_msg))
  1306. print(usage(_THE_NETWORK))
  1307. sys.exit(1)
  1308. def runConfigFile(verb, data):
  1309. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  1310. Node=Node,
  1311. Require=Require,
  1312. ConfigureNodes=ConfigureNodes,
  1313. _THE_NETWORK=_THE_NETWORK,
  1314. torrc_option_warn_count=0,
  1315. TORRC_OPTION_WARN_LIMIT=10)
  1316. exec(data, _GLOBALS)
  1317. network = _GLOBALS['_THE_NETWORK']
  1318. # let's check if the verb is a valid test and run it
  1319. if verb in getTests():
  1320. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  1321. try:
  1322. run_test = test_module.run_test
  1323. except AttributeError as e:
  1324. print("Error running test {!r}: {}".format(verb, e))
  1325. return False
  1326. return run_test(network)
  1327. # tell the user we don't know what their verb meant
  1328. if not hasattr(network, verb):
  1329. print(usage(network))
  1330. print("Error: I don't know how to %s." % verb)
  1331. return
  1332. return getattr(network, verb)()
  1333. def parseArgs():
  1334. if len(sys.argv) < 3:
  1335. exit_on_error("Not enough arguments given.")
  1336. if not os.path.isfile(sys.argv[2]):
  1337. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  1338. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  1339. def main():
  1340. global _BASE_ENVIRON
  1341. global _THE_NETWORK
  1342. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  1343. _THE_NETWORK = Network(_BASE_ENVIRON)
  1344. args = parseArgs()
  1345. f = open(args['network_cfg'])
  1346. result = runConfigFile(args['action'], f.read())
  1347. if result is False:
  1348. return -1
  1349. return 0
  1350. if __name__ == '__main__':
  1351. sys.exit(main())