TorNet.py 46 KB

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