TorNet.py 58 KB

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