TorNet.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. import chutney.Templating
  22. import chutney.Traffic
  23. _BASE_ENVIRON = None
  24. _TORRC_OPTIONS = None
  25. _THE_NETWORK = None
  26. # Get verbose tracebacks, so we can diagnose better.
  27. cgitb.enable(format="plain")
  28. def mkdir_p(d, mode=511):
  29. """Create directory 'd' and all of its parents as needed. Unlike
  30. os.makedirs, does not give an error if d already exists.
  31. 511 is the decimal representation of the octal number 0777. Since
  32. python2 only supports 0777 and python3 only supports 0o777, we can use
  33. neither.
  34. """
  35. try:
  36. os.makedirs(d, mode=mode)
  37. except OSError as e:
  38. if e.errno == errno.EEXIST:
  39. return
  40. raise
  41. class Node(object):
  42. """A Node represents a Tor node or a set of Tor nodes. It's created
  43. in a network configuration file.
  44. This class is responsible for holding the user's selected node
  45. configuration, and figuring out how the node needs to be
  46. configured and launched.
  47. """
  48. # Fields:
  49. # _parent
  50. # _env
  51. # _builder
  52. # _controller
  53. ########
  54. # Users are expected to call these:
  55. def __init__(self, parent=None, **kwargs):
  56. self._parent = parent
  57. self._env = self._createEnviron(parent, kwargs)
  58. self._builder = None
  59. self._controller = None
  60. def getN(self, N):
  61. return [Node(self) for _ in range(N)]
  62. def specialize(self, **kwargs):
  63. return Node(parent=self, **kwargs)
  64. ######
  65. # Chutney uses these:
  66. def getBuilder(self):
  67. """Return a NodeBuilder instance to set up this node (that is, to
  68. write all the files that need to be in place so that this
  69. node can be run by a NodeController).
  70. """
  71. if self._builder is None:
  72. self._builder = LocalNodeBuilder(self._env)
  73. return self._builder
  74. def getController(self):
  75. """Return a NodeController instance to control this node (that is,
  76. to start it, stop it, see if it's running, etc.)
  77. """
  78. if self._controller is None:
  79. self._controller = LocalNodeController(self._env)
  80. return self._controller
  81. def setNodenum(self, num):
  82. """Assign a value to the 'nodenum' element of this node. Each node
  83. in a network gets its own nodenum.
  84. """
  85. self._env['nodenum'] = num
  86. #####
  87. # These are internal:
  88. def _createEnviron(self, parent, argdict):
  89. """Return an Environ that delegates to the parent node's Environ (if
  90. there is a parent node), or to the default environment.
  91. """
  92. if parent:
  93. parentenv = parent._env
  94. else:
  95. parentenv = self._getDefaultEnviron()
  96. return TorEnviron(parentenv, **argdict)
  97. def _getDefaultEnviron(self):
  98. """Return the default environment. Any variables that we can't find
  99. set for any particular node, we look for here.
  100. """
  101. return _BASE_ENVIRON
  102. class _NodeCommon(object):
  103. """Internal helper class for functionality shared by some NodeBuilders
  104. and some NodeControllers."""
  105. # XXXX maybe this should turn into a mixin.
  106. def __init__(self, env):
  107. self._env = env
  108. def expand(self, pat, includePath=(".",)):
  109. return chutney.Templating.Template(pat, includePath).format(self._env)
  110. def _getTorrcFname(self):
  111. """Return the name of the file where we'll be writing torrc"""
  112. return self.expand("${torrc_fname}")
  113. class NodeBuilder(_NodeCommon):
  114. """Abstract base class. A NodeBuilder is responsible for doing all the
  115. one-time prep needed to set up a node in a network.
  116. """
  117. def __init__(self, env):
  118. _NodeCommon.__init__(self, env)
  119. def checkConfig(self, net):
  120. """Try to format our torrc; raise an exception if we can't.
  121. """
  122. def preConfig(self, net):
  123. """Called on all nodes before any nodes configure: generates keys as
  124. needed.
  125. """
  126. def config(self, net):
  127. """Called to configure a node: creates a torrc file for it."""
  128. def postConfig(self, net):
  129. """Called on each nodes after all nodes configure."""
  130. class NodeController(_NodeCommon):
  131. """Abstract base class. A NodeController is responsible for running a
  132. node on the network.
  133. """
  134. def __init__(self, env):
  135. _NodeCommon.__init__(self, env)
  136. def check(self, listRunning=True, listNonRunning=False):
  137. """See if this node is running, stopped, or crashed. If it's running
  138. and listRunning is set, print a short statement. If it's
  139. stopped and listNonRunning is set, then print a short statement.
  140. If it's crashed, print a statement. Return True if the
  141. node is running, false otherwise.
  142. """
  143. def start(self):
  144. """Try to start this node; return True if we succeeded or it was
  145. already running, False if we failed."""
  146. def stop(self, sig=signal.SIGINT):
  147. """Try to stop this node by sending it the signal 'sig'."""
  148. class LocalNodeBuilder(NodeBuilder):
  149. # Environment members used:
  150. # torrc -- which torrc file to use
  151. # torrc_template_path -- path to search for torrc files and include files
  152. # authority -- bool -- are we an authority?
  153. # bridgeauthority -- bool -- are we a bridge authority?
  154. # relay -- bool -- are we a relay?
  155. # bridge -- bool -- are we a bridge?
  156. # hs -- bool -- are we a hidden service?
  157. # nodenum -- int -- set by chutney -- which unique node index is this?
  158. # dir -- path -- set by chutney -- data directory for this tor
  159. # tor_gencert -- path to tor_gencert binary
  160. # tor -- path to tor binary
  161. # auth_cert_lifetime -- lifetime of authority certs, in months.
  162. # ip -- IP to listen on
  163. # ipv6_addr -- IPv6 address to listen on
  164. # orport, dirport -- used on authorities, relays, and bridges
  165. # fingerprint -- used only if authority
  166. # dirserver_flags -- used only if authority
  167. # nick -- nickname of this router
  168. # Environment members set
  169. # fingerprint -- hex router key fingerprint
  170. # nodenum -- int -- set by chutney -- which unique node index is this?
  171. def __init__(self, env):
  172. NodeBuilder.__init__(self, env)
  173. self._env = env
  174. def _createTorrcFile(self, checkOnly=False):
  175. """Write the torrc file for this node, disabling any options
  176. that are not supported by env's tor binary using comments.
  177. If checkOnly, just make sure that the formatting is indeed
  178. possible.
  179. """
  180. fn_out = self._getTorrcFname()
  181. torrc_template = self._getTorrcTemplate()
  182. output = torrc_template.format(self._env)
  183. if checkOnly:
  184. # XXXX Is it time-consuming to format? If so, cache here.
  185. return
  186. # now filter the options we're about to write, commenting out
  187. # the options that the current tor binary doesn't support
  188. tor = self._env['tor']
  189. # find the options the current tor binary supports, and cache them
  190. if tor not in _TORRC_OPTIONS:
  191. # Note: some versions of tor (e.g. 0.2.4.23) require
  192. # --list-torrc-options to be the first argument
  193. cmdline = [
  194. tor,
  195. "--list-torrc-options",
  196. "--hush"]
  197. try:
  198. opts = subprocess.check_output(cmdline, bufsize=-1,
  199. universal_newlines=True)
  200. except OSError as e:
  201. # only catch file not found error
  202. if e.errno == errno.ENOENT:
  203. print("Cannot find tor binary %r. Use "
  204. "CHUTNEY_TOR environment variable to set the "
  205. "path, or put the binary into $PATH." % tor)
  206. sys.exit(0)
  207. else:
  208. raise
  209. # check we received a list of options, and nothing else
  210. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  211. torrc_opts = opts.split()
  212. # cache the options for this tor binary's path
  213. _TORRC_OPTIONS[tor] = torrc_opts
  214. else:
  215. torrc_opts = _TORRC_OPTIONS[tor]
  216. # check if each option is supported before writing it
  217. # TODO: what about unsupported values?
  218. # e.g. tor 0.2.4.23 doesn't support TestingV3AuthInitialVoteDelay 2
  219. # but later version do. I say throw this one to the user.
  220. with open(fn_out, 'w') as f:
  221. # we need to do case-insensitive option comparison
  222. # even if this is a static whitelist,
  223. # so we convert to lowercase as close to the loop as possible
  224. lower_opts = [opt.lower() for opt in torrc_opts]
  225. # keep ends when splitting lines, so we can write them out
  226. # using writelines() without messing around with "\n"s
  227. for line in output.splitlines(True):
  228. # check if the first word on the line is a supported option,
  229. # preserving empty lines and comment lines
  230. sline = line.strip()
  231. if (len(sline) == 0 or
  232. sline[0] == '#' or
  233. sline.split()[0].lower() in lower_opts):
  234. f.writelines([line])
  235. else:
  236. # well, this could get spammy
  237. # TODO: warn once per option per tor binary
  238. # TODO: print tor version?
  239. print(("The tor binary at %r does not support the "
  240. "option in the torrc line:\n"
  241. "%r") % (tor, line.strip()))
  242. # we could decide to skip these lines entirely
  243. # TODO: write tor version?
  244. f.writelines(["# " + tor + " unsupported: " + line])
  245. def _getTorrcTemplate(self):
  246. """Return the template used to write the torrc for this node."""
  247. template_path = self._env['torrc_template_path']
  248. return chutney.Templating.Template("$${include:$torrc}",
  249. includePath=template_path)
  250. def _getFreeVars(self):
  251. """Return a set of the free variables in the torrc template for this
  252. node.
  253. """
  254. template = self._getTorrcTemplate()
  255. return template.freevars(self._env)
  256. def checkConfig(self, net):
  257. """Try to format our torrc; raise an exception if we can't.
  258. """
  259. self._createTorrcFile(checkOnly=True)
  260. def preConfig(self, net):
  261. """Called on all nodes before any nodes configure: generates keys and
  262. hidden service directories as needed.
  263. """
  264. self._makeDataDir()
  265. if self._env['authority']:
  266. self._genAuthorityKey()
  267. if self._env['relay']:
  268. self._genRouterKey()
  269. if self._env['hs']:
  270. self._makeHiddenServiceDir()
  271. def config(self, net):
  272. """Called to configure a node: creates a torrc file for it."""
  273. self._createTorrcFile()
  274. # self._createScripts()
  275. def postConfig(self, net):
  276. """Called on each nodes after all nodes configure."""
  277. # self.net.addNode(self)
  278. pass
  279. def _makeDataDir(self):
  280. """Create the data directory (with keys subdirectory) for this node.
  281. """
  282. datadir = self._env['dir']
  283. mkdir_p(os.path.join(datadir, 'keys'))
  284. def _makeHiddenServiceDir(self):
  285. """Create the hidden service subdirectory for this node.
  286. The directory name is stored under the 'hs_directory' environment
  287. key. It is combined with the 'dir' data directory key to yield the
  288. path to the hidden service directory.
  289. 448 is the decimal representation of the octal number 0700. Since
  290. python2 only supports 0700 and python3 only supports 0o700, we can
  291. use neither.
  292. """
  293. datadir = self._env['dir']
  294. mkdir_p(os.path.join(datadir, self._env['hs_directory']), 448)
  295. def _genAuthorityKey(self):
  296. """Generate an authority identity and signing key for this authority,
  297. if they do not already exist."""
  298. datadir = self._env['dir']
  299. tor_gencert = self._env['tor_gencert']
  300. lifetime = self._env['auth_cert_lifetime']
  301. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  302. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  303. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  304. addr = self.expand("${ip}:${dirport}")
  305. passphrase = self._env['auth_passphrase']
  306. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  307. return
  308. cmdline = [
  309. tor_gencert,
  310. '--create-identity-key',
  311. '--passphrase-fd', '0',
  312. '-i', idfile,
  313. '-s', skfile,
  314. '-c', certfile,
  315. '-m', str(lifetime),
  316. '-a', addr]
  317. print("Creating identity key %s for %s with %s" % (
  318. idfile, self._env['nick'], " ".join(cmdline)))
  319. try:
  320. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  321. except OSError as e:
  322. # only catch file not found error
  323. if e.errno == errno.ENOENT:
  324. print("Cannot find tor-gencert binary %r. Use "
  325. "CHUTNEY_TOR_GENCERT environment variable to set the "
  326. "path, or put the binary into $PATH." % tor_gencert)
  327. sys.exit(0)
  328. else:
  329. raise
  330. p.communicate(passphrase + "\n")
  331. assert p.returncode == 0 # XXXX BAD!
  332. def _genRouterKey(self):
  333. """Generate an identity key for this router, unless we already have,
  334. and set up the 'fingerprint' entry in the Environ.
  335. """
  336. datadir = self._env['dir']
  337. tor = self._env['tor']
  338. torrc = self._getTorrcFname()
  339. cmdline = [
  340. tor,
  341. "--quiet",
  342. "--ignore-missing-torrc",
  343. "-f", torrc,
  344. "--list-fingerprint",
  345. "--orport", "1",
  346. "--datadirectory", datadir]
  347. try:
  348. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  349. except OSError as e:
  350. # only catch file not found error
  351. if e.errno == errno.ENOENT:
  352. print("Cannot find tor binary %r. Use "
  353. "CHUTNEY_TOR environment variable to set the "
  354. "path, or put the binary into $PATH." % tor)
  355. sys.exit(0)
  356. else:
  357. raise
  358. stdout, stderr = p.communicate()
  359. fingerprint = "".join((stdout.rstrip().split('\n')[-1]).split()[1:])
  360. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  361. print(("Error when calling %r. It gave %r as a fingerprint "
  362. " and %r on stderr.") % (" ".join(cmdline), stdout, stderr))
  363. sys.exit(1)
  364. self._env['fingerprint'] = fingerprint
  365. def _getAltAuthLines(self, hasbridgeauth=False):
  366. """Return a combination of AlternateDirAuthority,
  367. AlternateHSAuthority and AlternateBridgeAuthority lines for
  368. this Node, appropriately. Non-authorities return ""."""
  369. if not self._env['authority']:
  370. return ""
  371. datadir = self._env['dir']
  372. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  373. v3id = None
  374. with open(certfile, 'r') as f:
  375. for line in f:
  376. if line.startswith("fingerprint"):
  377. v3id = line.split()[1].strip()
  378. break
  379. assert v3id is not None
  380. if self._env['bridgeauthority']:
  381. # Bridge authorities return AlternateBridgeAuthority with
  382. # the 'bridge' flag set.
  383. options = ("AlternateBridgeAuthority",)
  384. self._env['dirserver_flags'] += " bridge"
  385. else:
  386. # Directory authorities return AlternateDirAuthority with
  387. # the 'hs' and 'v3ident' flags set.
  388. # XXXX This next line is needed for 'bridges' but breaks
  389. # 'basic'
  390. if hasbridgeauth:
  391. options = ("AlternateDirAuthority",)
  392. else:
  393. options = ("DirAuthority",)
  394. self._env['dirserver_flags'] += " hs v3ident=%s" % v3id
  395. authlines = ""
  396. for authopt in options:
  397. authlines += "%s %s orport=%s" % (
  398. authopt, self._env['nick'], self._env['orport'])
  399. # It's ok to give an authority's IPv6 address to an IPv4-only
  400. # client or relay: it will and must ignore it
  401. if self._env['ipv6_addr'] is not None:
  402. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  403. self._env['orport'])
  404. authlines += " %s %s:%s %s\n" % (
  405. self._env['dirserver_flags'], self._env['ip'],
  406. self._env['dirport'], self._env['fingerprint'])
  407. return authlines
  408. def _getBridgeLines(self):
  409. """Return potential Bridge line for this Node. Non-bridge
  410. relays return "".
  411. """
  412. if not self._env['bridge']:
  413. return ""
  414. bridgelines = "Bridge %s:%s\n" % (self._env['ip'],
  415. self._env['orport'])
  416. if self._env['ipv6_addr'] is not None:
  417. bridgelines += "Bridge %s:%s\n" % (self._env['ipv6_addr'],
  418. self._env['orport'])
  419. return bridgelines
  420. class LocalNodeController(NodeController):
  421. def __init__(self, env):
  422. NodeController.__init__(self, env)
  423. self._env = env
  424. def getPid(self):
  425. """Assuming that this node has its pidfile in ${dir}/pid, return
  426. the pid of the running process, or None if there is no pid in the
  427. file.
  428. """
  429. pidfile = os.path.join(self._env['dir'], 'pid')
  430. if not os.path.exists(pidfile):
  431. return None
  432. with open(pidfile, 'r') as f:
  433. return int(f.read())
  434. def isRunning(self, pid=None):
  435. """Return true iff this node is running. (If 'pid' is provided, we
  436. assume that the pid provided is the one of this node. Otherwise
  437. we call getPid().
  438. """
  439. if pid is None:
  440. pid = self.getPid()
  441. if pid is None:
  442. return False
  443. try:
  444. os.kill(pid, 0) # "kill 0" == "are you there?"
  445. except OSError as e:
  446. if e.errno == errno.ESRCH:
  447. return False
  448. raise
  449. # okay, so the process exists. Say "True" for now.
  450. # XXXX check if this is really tor!
  451. return True
  452. def check(self, listRunning=True, listNonRunning=False):
  453. """See if this node is running, stopped, or crashed. If it's running
  454. and listRunning is set, print a short statement. If it's
  455. stopped and listNonRunning is set, then print a short statement.
  456. If it's crashed, print a statement. Return True if the
  457. node is running, false otherwise.
  458. """
  459. # XXX Split this into "check" and "print" parts.
  460. pid = self.getPid()
  461. nick = self._env['nick']
  462. datadir = self._env['dir']
  463. corefile = "core.%s" % pid
  464. if self.isRunning(pid):
  465. if listRunning:
  466. print("%s is running with PID %s" % (nick, pid))
  467. return True
  468. elif os.path.exists(os.path.join(datadir, corefile)):
  469. if listNonRunning:
  470. print("%s seems to have crashed, and left core file %s" % (
  471. nick, corefile))
  472. return False
  473. else:
  474. if listNonRunning:
  475. print("%s is stopped" % nick)
  476. return False
  477. def hup(self):
  478. """Send a SIGHUP to this node, if it's running."""
  479. pid = self.getPid()
  480. nick = self._env['nick']
  481. if self.isRunning(pid):
  482. print("Sending sighup to %s" % nick)
  483. os.kill(pid, signal.SIGHUP)
  484. return True
  485. else:
  486. print("%s is not running" % nick)
  487. return False
  488. def start(self):
  489. """Try to start this node; return True if we succeeded or it was
  490. already running, False if we failed."""
  491. if self.isRunning():
  492. print("%s is already running" % self._env['nick'])
  493. return True
  494. tor_path = self._env['tor']
  495. torrc = self._getTorrcFname()
  496. cmdline = [
  497. tor_path,
  498. "--quiet",
  499. "-f", torrc,
  500. ]
  501. try:
  502. p = subprocess.Popen(cmdline)
  503. except OSError as e:
  504. # only catch file not found error
  505. if e.errno == errno.ENOENT:
  506. print("Cannot find tor binary %r. Use CHUTNEY_TOR "
  507. "environment variable to set the path, or put the "
  508. "binary into $PATH." % tor_path)
  509. sys.exit(0)
  510. else:
  511. raise
  512. if self.waitOnLaunch():
  513. # this requires that RunAsDaemon is set
  514. p.wait()
  515. else:
  516. # this does not require RunAsDaemon to be set, but is slower.
  517. #
  518. # poll() only catches failures before the call itself
  519. # so let's sleep a little first
  520. # this does, of course, slow down process launch
  521. # which can require an adjustment to the voting interval
  522. #
  523. # avoid writing a newline or space when polling
  524. # so output comes out neatly
  525. sys.stdout.write('.')
  526. sys.stdout.flush()
  527. time.sleep(self._env['poll_launch_time'])
  528. p.poll()
  529. if p.returncode is not None and p.returncode != 0:
  530. if self._env['poll_launch_time'] is None:
  531. print("Couldn't launch %s (%s): %s" % (self._env['nick'],
  532. " ".join(cmdline),
  533. p.returncode))
  534. else:
  535. print("Couldn't poll %s (%s) "
  536. "after waiting %s seconds for launch"
  537. ": %s" % (self._env['nick'],
  538. " ".join(cmdline),
  539. self._env['poll_launch_time'],
  540. p.returncode))
  541. return False
  542. return True
  543. def stop(self, sig=signal.SIGINT):
  544. """Try to stop this node by sending it the signal 'sig'."""
  545. pid = self.getPid()
  546. if not self.isRunning(pid):
  547. print("%s is not running" % self._env['nick'])
  548. return
  549. os.kill(pid, sig)
  550. def cleanup_lockfile(self):
  551. lf = self._env['lockfile']
  552. if not self.isRunning() and os.path.exists(lf):
  553. print('Removing stale lock file for {0} ...'.format(
  554. self._env['nick']))
  555. os.remove(lf)
  556. def waitOnLaunch(self):
  557. """Check whether we can wait() for the tor process to launch"""
  558. # TODO: is this the best place for this code?
  559. # RunAsDaemon default is 0
  560. runAsDaemon = False
  561. with open(self._getTorrcFname(), 'r') as f:
  562. for line in f.readlines():
  563. stline = line.strip()
  564. # if the line isn't all whitespace or blank
  565. if len(stline) > 0:
  566. splline = stline.split()
  567. # if the line has at least two tokens on it
  568. if (len(splline) > 0 and
  569. splline[0].lower() == "RunAsDaemon".lower() and
  570. splline[1] == "1"):
  571. # use the RunAsDaemon value from the torrc
  572. # TODO: multiple values?
  573. runAsDaemon = True
  574. if runAsDaemon:
  575. # we must use wait() instead of poll()
  576. self._env['poll_launch_time'] = None
  577. return True
  578. else:
  579. # we must use poll() instead of wait()
  580. if self._env['poll_launch_time'] is None:
  581. self._env['poll_launch_time'] = \
  582. self._env['poll_launch_time_default']
  583. return False
  584. DEFAULTS = {
  585. 'authority': False,
  586. 'bridgeauthority': False,
  587. 'hasbridgeauth': False,
  588. 'relay': False,
  589. 'bridge': False,
  590. 'hs': False,
  591. 'hs_directory': 'hidden_service',
  592. 'hs-hostname': None,
  593. 'connlimit': 60,
  594. 'net_base_dir': os.environ.get('CHUTNEY_DATA_DIR', 'net'),
  595. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  596. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  597. 'auth_cert_lifetime': 12,
  598. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  599. # Pre-0.2.8 clients will fail to parse ipv6 auth lines,
  600. # so we default to ipv6_addr None
  601. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  602. 'dirserver_flags': 'no-v2',
  603. 'chutney_dir': '.',
  604. 'torrc_fname': '${dir}/torrc',
  605. 'orport_base': 5000,
  606. 'dirport_base': 7000,
  607. 'controlport_base': 8000,
  608. 'socksport_base': 9000,
  609. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  610. 'bridges': "Bridge bleargh bad torrc file!",
  611. 'core': True,
  612. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  613. # otherwise, poll after that many seconds (can be fractional/decimal)
  614. 'poll_launch_time': None,
  615. # Used when poll_launch_time is None, but RunAsDaemon is not set
  616. # Set low so that we don't interfere with the voting interval
  617. 'poll_launch_time_default': 0.1,
  618. # the number of bytes of random data we send on each connection
  619. 'data_bytes': int(os.environ.get('CHUTNEY_DATA_BYTES', 10 * 1024)),
  620. # the number of times each client will connect
  621. 'connection_count': int(os.environ.get('CHUTNEY_CONNECTIONS', 1)),
  622. # Do we want every client to connect to every HS, or one client
  623. # to connect to each HS?
  624. # (Clients choose an exit at random, so this doesn't apply to exits.)
  625. 'hs_multi_client': int(os.environ.get('CHUTNEY_HS_MULTI_CLIENT', 0)),
  626. # How long should verify (and similar commands) wait for a successful
  627. # outcome? (seconds)
  628. # We check BOOTSTRAP_TIME for compatibility with old versions of
  629. # test-network.sh
  630. 'bootstrap_time': int(os.environ.get('CHUTNEY_BOOTSTRAP_TIME',
  631. os.environ.get('BOOTSTRAP_TIME',
  632. 60))),
  633. }
  634. class TorEnviron(chutney.Templating.Environ):
  635. """Subclass of chutney.Templating.Environ to implement commonly-used
  636. substitutions.
  637. Environment fields provided:
  638. orport, controlport, socksport, dirport:
  639. dir:
  640. nick:
  641. tor_gencert:
  642. auth_passphrase:
  643. torrc_template_path:
  644. hs_hostname:
  645. Environment fields used:
  646. nodenum
  647. tag
  648. orport_base, controlport_base, socksport_base, dirport_base
  649. tor-gencert (note hyphen)
  650. chutney_dir
  651. tor
  652. dir
  653. hs_directory
  654. nick (debugging only)
  655. hs-hostname (note hyphen)
  656. XXXX document the above. Or document all fields in one place?
  657. """
  658. def __init__(self, parent=None, **kwargs):
  659. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  660. def _get_orport(self, my):
  661. return my['orport_base'] + my['nodenum']
  662. def _get_controlport(self, my):
  663. return my['controlport_base'] + my['nodenum']
  664. def _get_socksport(self, my):
  665. return my['socksport_base'] + my['nodenum']
  666. def _get_dirport(self, my):
  667. return my['dirport_base'] + my['nodenum']
  668. def _get_dir(self, my):
  669. return os.path.abspath(os.path.join(my['net_base_dir'],
  670. "nodes",
  671. "%03d%s" % (
  672. my['nodenum'], my['tag'])))
  673. def _get_nick(self, my):
  674. return "test%03d%s" % (my['nodenum'], my['tag'])
  675. def _get_tor_gencert(self, my):
  676. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  677. def _get_auth_passphrase(self, my):
  678. return self['nick'] # OMG TEH SECURE!
  679. def _get_torrc_template_path(self, my):
  680. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  681. def _get_lockfile(self, my):
  682. return os.path.join(self['dir'], 'lock')
  683. # A hs generates its key on first run,
  684. # so check for it at the last possible moment,
  685. # but cache it in memory to avoid repeatedly reading the file
  686. # XXXX - this is not like the other functions in this class,
  687. # as it reads from a file created by the hidden service
  688. def _get_hs_hostname(self, my):
  689. if my['hs-hostname'] is None:
  690. datadir = my['dir']
  691. # a file containing a single line with the hs' .onion address
  692. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  693. 'hostname')
  694. try:
  695. with open(hs_hostname_file, 'r') as hostnamefp:
  696. hostname = hostnamefp.read()
  697. # the hostname file ends with a newline
  698. hostname = hostname.strip()
  699. my['hs-hostname'] = hostname
  700. except IOError as e:
  701. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  702. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  703. return my['hs-hostname']
  704. class Network(object):
  705. """A network of Tor nodes, plus functions to manipulate them
  706. """
  707. def __init__(self, defaultEnviron):
  708. self._nodes = []
  709. self._dfltEnv = defaultEnviron
  710. self._nextnodenum = 0
  711. def _addNode(self, n):
  712. n.setNodenum(self._nextnodenum)
  713. self._nextnodenum += 1
  714. self._nodes.append(n)
  715. def move_aside_nodes(self):
  716. net_base_dir = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  717. nodesdir = os.path.join(net_base_dir, 'nodes')
  718. if not os.path.exists(nodesdir):
  719. return
  720. newdir = newdirbase = "%s.%d" % (nodesdir, time.time())
  721. i = 0
  722. while os.path.exists(newdir):
  723. i += 1
  724. newdir = "%s.%d" % (newdirbase, i)
  725. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  726. os.rename(nodesdir, newdir)
  727. def _checkConfig(self):
  728. for n in self._nodes:
  729. n.getBuilder().checkConfig(self)
  730. def configure(self):
  731. # shutil.rmtree(os.path.join(os.getcwd(),'net','nodes'),ignore_errors=True)
  732. self.move_aside_nodes()
  733. network = self
  734. altauthlines = []
  735. bridgelines = []
  736. builders = [n.getBuilder() for n in self._nodes]
  737. self._checkConfig()
  738. # XXX don't change node names or types or count if anything is
  739. # XXX running!
  740. for b in builders:
  741. b.preConfig(network)
  742. altauthlines.append(b._getAltAuthLines(
  743. self._dfltEnv['hasbridgeauth']))
  744. bridgelines.append(b._getBridgeLines())
  745. self._dfltEnv['authorities'] = "".join(altauthlines)
  746. self._dfltEnv['bridges'] = "".join(bridgelines)
  747. for b in builders:
  748. b.config(network)
  749. for b in builders:
  750. b.postConfig(network)
  751. def status(self):
  752. statuses = [n.getController().check() for n in self._nodes]
  753. n_ok = len([x for x in statuses if x])
  754. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  755. return n_ok == len(self._nodes)
  756. def restart(self):
  757. self.stop()
  758. self.start()
  759. def start(self):
  760. if self._dfltEnv['poll_launch_time'] is not None:
  761. # format polling correctly - avoid printing a newline
  762. sys.stdout.write("Starting nodes")
  763. sys.stdout.flush()
  764. else:
  765. print("Starting nodes")
  766. rv = all([n.getController().start() for n in self._nodes])
  767. # now print a newline unconditionally - this stops poll()ing
  768. # output from being squashed together, at the cost of a blank
  769. # line in wait()ing output
  770. print("")
  771. return rv
  772. def hup(self):
  773. print("Sending SIGHUP to nodes")
  774. return all([n.getController().hup() for n in self._nodes])
  775. def stop(self):
  776. controllers = [n.getController() for n in self._nodes]
  777. for sig, desc in [(signal.SIGINT, "SIGINT"),
  778. (signal.SIGINT, "another SIGINT"),
  779. (signal.SIGKILL, "SIGKILL")]:
  780. print("Sending %s to nodes" % desc)
  781. for c in controllers:
  782. if c.isRunning():
  783. c.stop(sig=sig)
  784. print("Waiting for nodes to finish.")
  785. for n in range(15):
  786. time.sleep(1)
  787. if all(not c.isRunning() for c in controllers):
  788. # check for stale lock file when Tor crashes
  789. for c in controllers:
  790. c.cleanup_lockfile()
  791. return
  792. sys.stdout.write(".")
  793. sys.stdout.flush()
  794. for c in controllers:
  795. c.check(listNonRunning=False)
  796. def ConfigureNodes(nodelist):
  797. network = _THE_NETWORK
  798. for n in nodelist:
  799. network._addNode(n)
  800. if n._env['bridgeauthority']:
  801. network._dfltEnv['hasbridgeauth'] = True
  802. def getTests():
  803. tests = []
  804. chutney_path = os.environ.get('CHUTNEY_PATH', '')
  805. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  806. chutney_path += "/"
  807. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  808. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  809. tests.append(os.path.splitext(x)[0])
  810. return tests
  811. def usage(network):
  812. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  813. "Known commands are: %s" % (
  814. " ".join(x for x in dir(network)
  815. if not x.startswith("_"))),
  816. "Known tests are: %s" % (
  817. " ".join(getTests()))
  818. ])
  819. def exit_on_error(err_msg):
  820. print("Error: {0}\n".format(err_msg))
  821. print(usage(_THE_NETWORK))
  822. sys.exit(1)
  823. def runConfigFile(verb, data):
  824. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  825. Node=Node,
  826. ConfigureNodes=ConfigureNodes,
  827. _THE_NETWORK=_THE_NETWORK)
  828. exec(data, _GLOBALS)
  829. network = _GLOBALS['_THE_NETWORK']
  830. # let's check if the verb is a valid test and run it
  831. if verb in getTests():
  832. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  833. try:
  834. return test_module.run_test(network)
  835. except AttributeError:
  836. print("Test {!r} has no 'run_test(network)' function".format(verb))
  837. return False
  838. # tell the user we don't know what their verb meant
  839. if not hasattr(network, verb):
  840. print(usage(network))
  841. print("Error: I don't know how to %s." % verb)
  842. return
  843. return getattr(network, verb)()
  844. def parseArgs():
  845. if len(sys.argv) < 3:
  846. exit_on_error("Not enough arguments given.")
  847. if not os.path.isfile(sys.argv[2]):
  848. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  849. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  850. def main():
  851. global _BASE_ENVIRON
  852. global _TORRC_OPTIONS
  853. global _THE_NETWORK
  854. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  855. # _TORRC_OPTIONS gets initialised on demand as a map of
  856. # "/path/to/tor" => ["SupportedOption1", "SupportedOption2", ...]
  857. # Or it can be pre-populated as a static whitelist of options
  858. _TORRC_OPTIONS = dict()
  859. _THE_NETWORK = Network(_BASE_ENVIRON)
  860. args = parseArgs()
  861. f = open(args['network_cfg'])
  862. result = runConfigFile(args['action'], f)
  863. if result is False:
  864. return -1
  865. return 0
  866. if __name__ == '__main__':
  867. sys.exit(main())