TorNet.py 46 KB

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