TorNet.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570
  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. if self._env['valgrind_settings'] is not None:
  770. cmdline.append('valgrind')
  771. cmdline.extend(self._env['valgrind_settings'])
  772. cmdline.append('--log-file={}'.format(self._env['valgrind_log']))
  773. #
  774. cmdline.extend([
  775. tor_path,
  776. "-f", torrc,
  777. ])
  778. p = launch_process(cmdline)
  779. if self.waitOnLaunch():
  780. # this requires that RunAsDaemon is set
  781. (stdouterr, empty_stderr) = p.communicate()
  782. debug(stdouterr)
  783. assert empty_stderr is None
  784. else:
  785. # this does not require RunAsDaemon to be set, but is slower.
  786. #
  787. # poll() only catches failures before the call itself
  788. # so let's sleep a little first
  789. # this does, of course, slow down process launch
  790. # which can require an adjustment to the voting interval
  791. #
  792. # avoid writing a newline or space when polling
  793. # so output comes out neatly
  794. sys.stdout.write('.')
  795. sys.stdout.flush()
  796. time.sleep(self._env['poll_launch_time'])
  797. p.poll()
  798. if p.returncode is not None and p.returncode != 0:
  799. if self._env['poll_launch_time'] is None:
  800. print(("Couldn't launch {:12} command '{}': " +
  801. "exit {}, output '{}'")
  802. .format(self._env['nick'],
  803. " ".join(cmdline),
  804. p.returncode,
  805. stdouterr))
  806. else:
  807. print(("Couldn't poll {:12} command '{}' " +
  808. "after waiting {} seconds for launch: " +
  809. "exit {}").format(self._env['nick'],
  810. " ".join(cmdline),
  811. self._env['poll_launch_time'],
  812. p.returncode))
  813. return False
  814. return True
  815. def stop(self, sig=signal.SIGINT):
  816. """Try to stop this node by sending it the signal 'sig'."""
  817. pid = self.getPid()
  818. if not self.isRunning(pid):
  819. print("{:12} is not running".format(self._env['nick']))
  820. return
  821. os.kill(pid, sig)
  822. def cleanup_lockfile(self):
  823. lf = self._env['lockfile']
  824. if not self.isRunning() and os.path.exists(lf):
  825. debug("Removing stale lock file for {} ..."
  826. .format(self._env['nick']))
  827. os.remove(lf)
  828. def waitOnLaunch(self):
  829. """Check whether we can wait() for the tor process to launch"""
  830. # TODO: is this the best place for this code?
  831. # RunAsDaemon default is 0
  832. runAsDaemon = False
  833. with open(self._getTorrcFname(), 'r') as f:
  834. for line in f.readlines():
  835. stline = line.strip()
  836. # if the line isn't all whitespace or blank
  837. if len(stline) > 0:
  838. splline = stline.split()
  839. # if the line has at least two tokens on it
  840. if (len(splline) > 0 and
  841. splline[0].lower() == "RunAsDaemon".lower() and
  842. splline[1] == "1"):
  843. # use the RunAsDaemon value from the torrc
  844. # TODO: multiple values?
  845. runAsDaemon = True
  846. if runAsDaemon:
  847. # we must use wait() instead of poll()
  848. self._env['poll_launch_time'] = None
  849. return True
  850. else:
  851. # we must use poll() instead of wait()
  852. if self._env['poll_launch_time'] is None:
  853. self._env['poll_launch_time'] = \
  854. self._env['poll_launch_time_default']
  855. return False
  856. def getLogfile(self, info=False):
  857. """Return the expected path to the logfile for this instance."""
  858. datadir = self._env['dir']
  859. if info:
  860. logname = "info.log"
  861. else:
  862. logname = "notice.log"
  863. return os.path.join(datadir, logname)
  864. def getLastBootstrapStatus(self):
  865. """Look through the logs and return the last bootstrap message
  866. received as a 3-tuple of percentage complete, keyword
  867. (optional), and message.
  868. """
  869. logfname = self.getLogfile()
  870. if not os.path.exists(logfname):
  871. return (-200, "no_logfile", "There is no logfile yet.")
  872. percent,keyword,message=-100,"no_message","No bootstrap messages yet."
  873. with open(logfname, 'r') as f:
  874. for line in f:
  875. m = re.search(r'Bootstrapped (\d+)%(?: \(([^\)]*)\))?: (.*)',
  876. line)
  877. if m:
  878. percent, keyword, message = m.groups()
  879. percent = int(percent)
  880. return (percent, keyword, message)
  881. def isBootstrapped(self):
  882. """Return true iff the logfile says that this instance is
  883. bootstrapped."""
  884. pct, _, _ = self.getLastBootstrapStatus()
  885. return pct == 100
  886. # XXX: document these options
  887. DEFAULTS = {
  888. 'authority': False,
  889. 'bridgeauthority': False,
  890. 'hasbridgeauth': False,
  891. 'relay': False,
  892. 'bridge': False,
  893. 'pt_bridge': False,
  894. 'pt_transport' : "",
  895. 'pt_extra' : "",
  896. 'hs': False,
  897. 'hs_directory': 'hidden_service',
  898. 'hs-hostname': None,
  899. 'connlimit': 60,
  900. 'net_base_dir': get_absolute_net_path(),
  901. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  902. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  903. 'auth_cert_lifetime': 12,
  904. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  905. # we default to ipv6_addr None to support IPv4-only systems
  906. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  907. 'dirserver_flags': 'no-v2',
  908. 'chutney_dir': get_absolute_chutney_path(),
  909. 'torrc_fname': '${dir}/torrc',
  910. 'orport_base': 5000,
  911. 'dirport_base': 7000,
  912. 'controlport_base': 8000,
  913. 'socksport_base': 9000,
  914. 'extorport_base' : 9500,
  915. 'ptport_base' : 9900,
  916. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  917. 'bridges': "Bridge bleargh bad torrc file!",
  918. 'core': True,
  919. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  920. # otherwise, poll after that many seconds (can be fractional/decimal)
  921. 'poll_launch_time': None,
  922. # Used when poll_launch_time is None, but RunAsDaemon is not set
  923. # Set low so that we don't interfere with the voting interval
  924. 'poll_launch_time_default': 0.1,
  925. # the number of bytes of random data we send on each connection
  926. 'data_bytes': getenv_int('CHUTNEY_DATA_BYTES', 10 * 1024),
  927. # the number of times each client will connect
  928. 'connection_count': getenv_int('CHUTNEY_CONNECTIONS', 1),
  929. # Do we want every client to connect to every HS, or one client
  930. # to connect to each HS?
  931. # (Clients choose an exit at random, so this doesn't apply to exits.)
  932. 'hs_multi_client': getenv_int('CHUTNEY_HS_MULTI_CLIENT', 0),
  933. # How long should verify (and similar commands) wait for a successful
  934. # outcome? (seconds)
  935. # We check BOOTSTRAP_TIME for compatibility with old versions of
  936. # test-network.sh
  937. 'bootstrap_time': getenv_int('CHUTNEY_BOOTSTRAP_TIME',
  938. getenv_int('BOOTSTRAP_TIME',
  939. 60)),
  940. # the PID of the controlling script (for __OwningControllerProcess)
  941. 'controlling_pid': getenv_int('CHUTNEY_CONTROLLING_PID', 0),
  942. # a DNS config file (for ServerDNSResolvConfFile)
  943. 'dns_conf': (os.environ.get('CHUTNEY_DNS_CONF', '/etc/resolv.conf')
  944. if 'CHUTNEY_DNS_CONF' in os.environ
  945. else None),
  946. # The phase at which this instance needs to be
  947. # configured/launched, if we're doing multiphase
  948. # configuration/launch.
  949. 'config_phase' : 1,
  950. 'launch_phase' : 1,
  951. 'CUR_CONFIG_PHASE': getenv_int('CHUTNEY_CONFIG_PHASE', 1),
  952. 'CUR_LAUNCH_PHASE': getenv_int('CHUTNEY_LAUNCH_PHASE', 1),
  953. # the Sandbox torrc option value
  954. # defaults to 1 on Linux, and 0 otherwise
  955. 'sandbox': int(getenv_bool('CHUTNEY_TOR_SANDBOX',
  956. platform.system() == 'Linux')),
  957. 'num_cpus': None,
  958. 'numa_settings': None,
  959. 'measureme_log_dir': '${dir}',
  960. 'valgrind_settings': None,
  961. }
  962. class TorEnviron(chutney.Templating.Environ):
  963. """Subclass of chutney.Templating.Environ to implement commonly-used
  964. substitutions.
  965. Environment fields provided:
  966. orport, controlport, socksport, dirport: *Port torrc option
  967. dir: DataDirectory torrc option
  968. nick: Nickname torrc option
  969. tor_gencert: name or path of the tor-gencert binary
  970. auth_passphrase: obsoleted by CookieAuthentication
  971. torrc_template_path: path to chutney torrc_templates directory
  972. hs_hostname: the hostname of the key generated by a hidden service
  973. owning_controller_process: the __OwningControllerProcess torrc line,
  974. disabled if tor should continue after the script exits
  975. server_dns_resolv_conf: the ServerDNSResolvConfFile torrc line,
  976. disabled if tor should use the default DNS conf.
  977. If the dns_conf file is missing, this option is also disabled:
  978. otherwise, exits would not work due to tor bug #21900.
  979. sandbox: Sets Sandbox to the value of CHUTNEY_TOR_SANDBOX.
  980. The default is 1 on Linux, and 0 on other platforms.
  981. Chutney users can disable the sandbox using:
  982. export CHUTNEY_TOR_SANDBOX=0
  983. if it doesn't work on their version of glibc.
  984. Environment fields used:
  985. nodenum: chutney's internal node number for the node
  986. tag: a short text string that represents the type of node
  987. orport_base, controlport_base, socksport_base, dirport_base: the
  988. initial port numbers used by nodenum 0. Each additional node adds
  989. 1 to the port numbers.
  990. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  991. present)
  992. chutney_dir: directory of the chutney source code
  993. tor: name or path of the tor binary
  994. net_base_dir: path to the chutney net directory
  995. hs_directory: name of the hidden service directory
  996. nick: Nickname torrc option (debugging only)
  997. hs-hostname (note hyphen): cached hidden service hostname value
  998. controlling_pid: the PID of the controlling process. After this
  999. process exits, the child tor processes will exit
  1000. dns_conf: the path to a DNS config file for Tor Exits. If this file
  1001. is empty or unreadable, Tor will try 127.0.0.1:53.
  1002. """
  1003. def __init__(self, parent=None, **kwargs):
  1004. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  1005. def _get_orport(self, my):
  1006. return my['orport_base'] + my['nodenum']
  1007. def _get_controlport(self, my):
  1008. return my['controlport_base'] + my['nodenum']
  1009. def _get_socksport(self, my):
  1010. return my['socksport_base'] + my['nodenum']
  1011. def _get_dirport(self, my):
  1012. return my['dirport_base'] + my['nodenum']
  1013. def _get_extorport(self, my):
  1014. return my['extorport_base'] + my['nodenum']
  1015. def _get_ptport(self, my):
  1016. return my['ptport_base'] + my['nodenum']
  1017. def _get_dir(self, my):
  1018. return os.path.abspath(os.path.join(my['net_base_dir'],
  1019. "nodes",
  1020. "%03d%s" % (
  1021. my['nodenum'], my['tag'])))
  1022. def _get_nick(self, my):
  1023. return "test%03d%s" % (my['nodenum'], my['tag'])
  1024. def _get_tor_gencert(self, my):
  1025. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  1026. def _get_auth_passphrase(self, my):
  1027. return self['nick'] # OMG TEH SECURE!
  1028. def _get_torrc_template_path(self, my):
  1029. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  1030. def _get_lockfile(self, my):
  1031. return os.path.join(self['dir'], 'lock')
  1032. def _get_valgrind_log(self, my):
  1033. return os.path.join(self['dir'], 'valgrind.log')
  1034. # A hs generates its key on first run,
  1035. # so check for it at the last possible moment,
  1036. # but cache it in memory to avoid repeatedly reading the file
  1037. # XXXX - this is not like the other functions in this class,
  1038. # as it reads from a file created by the hidden service
  1039. def _get_hs_hostname(self, my):
  1040. if my['hs-hostname'] is None:
  1041. datadir = my['dir']
  1042. # a file containing a single line with the hs' .onion address
  1043. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  1044. 'hostname')
  1045. try:
  1046. with open(hs_hostname_file, 'r') as hostnamefp:
  1047. hostname = hostnamefp.read()
  1048. # the hostname file ends with a newline
  1049. hostname = hostname.strip()
  1050. my['hs-hostname'] = hostname
  1051. except IOError as e:
  1052. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  1053. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  1054. return my['hs-hostname']
  1055. def _get_num_cpus_line(self, my):
  1056. num_cpus = my['num_cpus']
  1057. num_cpus_line = 'NumCPUs {}'.format(num_cpus)
  1058. if num_cpus is None:
  1059. num_cpus_line = '#' + num_cpus_line
  1060. return num_cpus_line
  1061. def _get_owning_controller_process(self, my):
  1062. cpid = my['controlling_pid']
  1063. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  1064. # if we want to leave the network running, or controlling_pid is 1
  1065. # (or invalid)
  1066. if cpid <= 1:
  1067. return '#' + ocp_line
  1068. else:
  1069. return ocp_line
  1070. # the default resolv.conf path is set at compile time
  1071. # there's no easy way to get it out of tor, so we use the typical value
  1072. DEFAULT_DNS_RESOLV_CONF = "/etc/resolv.conf"
  1073. # if we can't find the specified file, use this one as a substitute
  1074. OFFLINE_DNS_RESOLV_CONF = "/dev/null"
  1075. def _get_server_dns_resolv_conf(self, my):
  1076. if my['dns_conf'] == "":
  1077. # if the user asked for tor's default
  1078. return "#ServerDNSResolvConfFile using tor's compile-time default"
  1079. elif my['dns_conf'] is None:
  1080. # if there is no DNS conf file set
  1081. debug("CHUTNEY_DNS_CONF not specified, using '{}'."
  1082. .format(TorEnviron.DEFAULT_DNS_RESOLV_CONF))
  1083. dns_conf = TorEnviron.DEFAULT_DNS_RESOLV_CONF
  1084. else:
  1085. dns_conf = my['dns_conf']
  1086. dns_conf = os.path.abspath(dns_conf)
  1087. # work around Tor bug #21900, where exits fail when the DNS conf
  1088. # file does not exist, or is a broken symlink
  1089. # (os.path.exists returns False for broken symbolic links)
  1090. if not os.path.exists(dns_conf):
  1091. # Issue a warning so the user notices
  1092. print("CHUTNEY_DNS_CONF '{}' does not exist, using '{}'."
  1093. .format(dns_conf, TorEnviron.OFFLINE_DNS_RESOLV_CONF))
  1094. dns_conf = TorEnviron.OFFLINE_DNS_RESOLV_CONF
  1095. return "ServerDNSResolvConfFile %s" % (dns_conf)
  1096. KNOWN_REQUIREMENTS = {
  1097. "IPV6": chutney.Host.is_ipv6_supported
  1098. }
  1099. class Network(object):
  1100. """A network of Tor nodes, plus functions to manipulate them
  1101. """
  1102. def __init__(self, defaultEnviron):
  1103. self._nodes = []
  1104. self._requirements = []
  1105. self._dfltEnv = defaultEnviron
  1106. self._nextnodenum = 0
  1107. def _addNode(self, n):
  1108. n.setNodenum(self._nextnodenum)
  1109. self._nextnodenum += 1
  1110. self._nodes.append(n)
  1111. def _addRequirement(self, requirement):
  1112. requirement = requirement.upper()
  1113. if requirement not in KNOWN_REQUIREMENTS:
  1114. raise RuntimemeError(("Unrecognized requirement %r"%requirement))
  1115. self._requirements.append(requirement)
  1116. def move_aside_nodes_dir(self):
  1117. """Move aside the nodes directory, if it exists and is not a link.
  1118. Used for backwards-compatibility only: nodes is created as a link to
  1119. a new directory with a unique name in the current implementation.
  1120. """
  1121. nodesdir = get_absolute_nodes_path()
  1122. # only move the directory if it exists
  1123. if not os.path.exists(nodesdir):
  1124. return
  1125. # and if it's not a link
  1126. if os.path.islink(nodesdir):
  1127. return
  1128. # subtract 1 second to avoid collisions and get the correct ordering
  1129. newdir = get_new_absolute_nodes_path(time.time() - 1)
  1130. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  1131. os.rename(nodesdir, newdir)
  1132. def create_new_nodes_dir(self):
  1133. """Create a new directory with a unique name, and symlink it to nodes
  1134. """
  1135. # for backwards compatibility, move aside the old nodes directory
  1136. # (if it's not a link)
  1137. self.move_aside_nodes_dir()
  1138. # the unique directory we'll create
  1139. newnodesdir = get_new_absolute_nodes_path()
  1140. # the canonical name we'll link it to
  1141. nodeslink = get_absolute_nodes_path()
  1142. # this path should be unique and should not exist
  1143. if os.path.exists(newnodesdir):
  1144. raise RuntimeError(
  1145. 'get_new_absolute_nodes_path returned a path that exists')
  1146. # if this path exists, it must be a link
  1147. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  1148. raise RuntimeError(
  1149. 'get_absolute_nodes_path returned a path that exists and is not a link')
  1150. # create the new, uniquely named directory, and link it to nodes
  1151. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  1152. # this gets created with mode 0700, that's probably ok
  1153. mkdir_p(newnodesdir)
  1154. try:
  1155. os.unlink(nodeslink)
  1156. except OSError as e:
  1157. # it's ok if the link doesn't exist, we're just about to make it
  1158. if e.errno == errno.ENOENT:
  1159. pass
  1160. else:
  1161. raise
  1162. os.symlink(newnodesdir, nodeslink)
  1163. def _checkConfig(self):
  1164. for n in self._nodes:
  1165. n.getBuilder().checkConfig(self)
  1166. def supported(self):
  1167. """Check whether this network is supported by the set of binaries
  1168. and host information we have.
  1169. """
  1170. missing_any = False
  1171. for r in self._requirements:
  1172. if not KNOWN_REQUIREMENTS[r]():
  1173. print(("Can't run this network: %s is missing."))
  1174. missing_any = True
  1175. for n in self._nodes:
  1176. if not n.getBuilder().isSupported(self):
  1177. missing_any = False
  1178. if missing_any:
  1179. sys.exit(1)
  1180. def configure(self):
  1181. phase = self._dfltEnv['CUR_CONFIG_PHASE']
  1182. if phase == 1:
  1183. self.create_new_nodes_dir()
  1184. network = self
  1185. altauthlines = []
  1186. bridgelines = []
  1187. all_builders = [ n.getBuilder() for n in self._nodes ]
  1188. builders = [ b for b in all_builders
  1189. if b._env['config_phase'] == phase ]
  1190. self._checkConfig()
  1191. # XXX don't change node names or types or count if anything is
  1192. # XXX running!
  1193. for b in all_builders:
  1194. b.preConfig(network)
  1195. altauthlines.append(b._getAltAuthLines(
  1196. self._dfltEnv['hasbridgeauth']))
  1197. bridgelines.append(b._getBridgeLines())
  1198. self._dfltEnv['authorities'] = "".join(altauthlines)
  1199. self._dfltEnv['bridges'] = "".join(bridgelines)
  1200. for b in builders:
  1201. b.config(network)
  1202. for b in builders:
  1203. b.postConfig(network)
  1204. def status(self):
  1205. statuses = [n.getController().check(listNonRunning=True)
  1206. for n in self._nodes]
  1207. n_ok = len([x for x in statuses if x])
  1208. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  1209. return n_ok == len(self._nodes)
  1210. def restart(self):
  1211. self.stop()
  1212. self.start()
  1213. def start(self):
  1214. # format polling correctly - avoid printing a newline
  1215. sys.stdout.write("Starting nodes")
  1216. sys.stdout.flush()
  1217. rv = all([n.getController().start() for n in self._nodes
  1218. if n._env['launch_phase'] ==
  1219. self._dfltEnv['CUR_LAUNCH_PHASE']])
  1220. # now print a newline unconditionally - this stops poll()ing
  1221. # output from being squashed together, at the cost of a blank
  1222. # line in wait()ing output
  1223. print("")
  1224. return rv
  1225. def hup(self):
  1226. print("Sending SIGHUP to nodes")
  1227. return all([n.getController().hup() for n in self._nodes])
  1228. def wait_for_bootstrap(self):
  1229. print("Waiting for nodes to bootstrap...")
  1230. limit = getenv_int("CHUTNEY_START_TIME", 60)
  1231. delay = 0.5
  1232. controllers = [n.getController() for n in self._nodes]
  1233. elapsed = 0.0
  1234. most_recent_status = [ None ] * len(controllers)
  1235. while True:
  1236. all_bootstrapped = True
  1237. most_recent_status = [ ]
  1238. for c in controllers:
  1239. pct, kwd, msg = c.getLastBootstrapStatus()
  1240. most_recent_status.append((pct, kwd, msg))
  1241. if pct != 100:
  1242. all_bootstrapped = False
  1243. if all_bootstrapped:
  1244. print("Everything bootstrapped after %s sec"%elapsed)
  1245. return True
  1246. if elapsed >= limit:
  1247. break
  1248. time.sleep(delay)
  1249. elapsed += delay
  1250. print("Bootstrap failed. Node status:")
  1251. for c, status in zip(controllers,most_recent_status):
  1252. c.check(listRunning=False, listNonRunning=True)
  1253. print("{}: {}".format(c.getNick(), status))
  1254. return False
  1255. def stop(self):
  1256. controllers = [n.getController() for n in self._nodes]
  1257. for sig, desc in [(signal.SIGINT, "SIGINT"),
  1258. (signal.SIGINT, "another SIGINT"),
  1259. (signal.SIGKILL, "SIGKILL")]:
  1260. print("Sending %s to nodes" % desc)
  1261. for c in controllers:
  1262. if c.isRunning():
  1263. c.stop(sig=sig)
  1264. print("Waiting for nodes to finish.")
  1265. wrote_dot = False
  1266. for n in range(15):
  1267. time.sleep(1)
  1268. if all(not c.isRunning() for c in controllers):
  1269. # make the output clearer by adding a newline
  1270. if wrote_dot:
  1271. sys.stdout.write("\n")
  1272. sys.stdout.flush()
  1273. # check for stale lock file when Tor crashes
  1274. for c in controllers:
  1275. c.cleanup_lockfile()
  1276. return
  1277. sys.stdout.write(".")
  1278. wrote_dot = True
  1279. sys.stdout.flush()
  1280. for c in controllers:
  1281. c.check(listNonRunning=False)
  1282. # make the output clearer by adding a newline
  1283. if wrote_dot:
  1284. sys.stdout.write("\n")
  1285. sys.stdout.flush()
  1286. def Require(feature):
  1287. network = _THE_NETWORK
  1288. network._addRequirement(feature)
  1289. def ConfigureNodes(nodelist):
  1290. network = _THE_NETWORK
  1291. for n in nodelist:
  1292. network._addNode(n)
  1293. if n._env['bridgeauthority']:
  1294. network._dfltEnv['hasbridgeauth'] = True
  1295. def getTests():
  1296. tests = []
  1297. chutney_path = get_absolute_chutney_path()
  1298. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  1299. chutney_path += "/"
  1300. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  1301. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  1302. tests.append(os.path.splitext(x)[0])
  1303. return tests
  1304. def usage(network):
  1305. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  1306. "Known commands are: %s" % (
  1307. " ".join(x for x in dir(network)
  1308. if not x.startswith("_"))),
  1309. "Known tests are: %s" % (
  1310. " ".join(getTests()))
  1311. ])
  1312. def exit_on_error(err_msg):
  1313. print("Error: {0}\n".format(err_msg))
  1314. print(usage(_THE_NETWORK))
  1315. sys.exit(1)
  1316. def runConfigFile(verb, data):
  1317. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  1318. Node=Node,
  1319. Require=Require,
  1320. ConfigureNodes=ConfigureNodes,
  1321. _THE_NETWORK=_THE_NETWORK,
  1322. torrc_option_warn_count=0,
  1323. TORRC_OPTION_WARN_LIMIT=10)
  1324. exec(data, _GLOBALS)
  1325. network = _GLOBALS['_THE_NETWORK']
  1326. # let's check if the verb is a valid test and run it
  1327. if verb in getTests():
  1328. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  1329. try:
  1330. run_test = test_module.run_test
  1331. except AttributeError as e:
  1332. print("Error running test {!r}: {}".format(verb, e))
  1333. return False
  1334. return run_test(network)
  1335. # tell the user we don't know what their verb meant
  1336. if not hasattr(network, verb):
  1337. print(usage(network))
  1338. print("Error: I don't know how to %s." % verb)
  1339. return
  1340. return getattr(network, verb)()
  1341. def parseArgs():
  1342. if len(sys.argv) < 3:
  1343. exit_on_error("Not enough arguments given.")
  1344. if not os.path.isfile(sys.argv[2]):
  1345. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  1346. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  1347. def main():
  1348. global _BASE_ENVIRON
  1349. global _THE_NETWORK
  1350. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  1351. _THE_NETWORK = Network(_BASE_ENVIRON)
  1352. args = parseArgs()
  1353. f = open(args['network_cfg'])
  1354. result = runConfigFile(args['action'], f.read())
  1355. if result is False:
  1356. return -1
  1357. return 0
  1358. if __name__ == '__main__':
  1359. sys.exit(main())