TorNet.py 46 KB

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