TorNet.py 54 KB

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