TorNet.py 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. # Copyright 2013 The Tor Project
  5. #
  6. # You may do anything with this work that copyright law would normally
  7. # restrict, so long as you retain the above notice(s) and this license
  8. # in all redistributed copies and derived works. There is no warranty.
  9. # Future imports for Python 2.7, mandatory in 3.0
  10. from __future__ import division
  11. from __future__ import print_function
  12. from __future__ import unicode_literals
  13. import cgitb
  14. import errno
  15. import importlib
  16. import os
  17. import platform
  18. import re
  19. import signal
  20. import shutil
  21. import subprocess
  22. import sys
  23. import time
  24. from chutney.Debug import debug_flag, debug
  25. import chutney.Host
  26. import chutney.Templating
  27. import chutney.Traffic
  28. import chutney.Util
  29. _BASE_ENVIRON = None
  30. _TOR_VERSIONS = None
  31. _TORRC_OPTIONS = None
  32. _THE_NETWORK = None
  33. TORRC_OPTION_WARN_LIMIT = 10
  34. torrc_option_warn_count = 0
  35. # Get verbose tracebacks, so we can diagnose better.
  36. cgitb.enable(format="plain")
  37. class MissingBinaryException(Exception):
  38. pass
  39. def getenv_type(env_var, default, type_, type_name=None):
  40. """
  41. Return the value of the environment variable 'envar' as type_,
  42. or 'default' if no such variable exists.
  43. Raise ValueError using type_name if the environment variable is set,
  44. but type_() raises a ValueError on its value. (If type_name is None
  45. or empty, the ValueError uses type_'s string representation instead.)
  46. """
  47. strval = os.environ.get(env_var)
  48. if strval is None:
  49. return default
  50. try:
  51. return type_(strval)
  52. except ValueError:
  53. if not type_name:
  54. type_name = str(type_)
  55. raise ValueError(("Invalid value for environment variable '{}': "
  56. "expected {}, but got '{}'")
  57. .format(env_var, typename, strval))
  58. def getenv_int(env_var, default):
  59. """
  60. Return the value of the environment variable 'envar' as an int,
  61. or 'default' if no such variable exists.
  62. Raise ValueError if the environment variable is set, but is not an int.
  63. """
  64. return getenv_type(env_var, default, int, type_name='an int')
  65. def getenv_bool(env_var, default):
  66. """
  67. Return the value of the environment variable 'envar' as a bool,
  68. or 'default' if no such variable exists.
  69. Unlike bool(), converts 0, "False", and "No" to False.
  70. Raise ValueError if the environment variable is set, but is not a bool.
  71. """
  72. try:
  73. # Handle integer values
  74. return bool(getenv_int(env_var, default))
  75. except ValueError:
  76. # Handle values that the user probably expects to be False
  77. strval = os.environ.get(env_var)
  78. if strval.lower() in ['false', 'no']:
  79. return False
  80. else:
  81. return getenv_type(env_var, default, bool, type_name='a bool')
  82. def mkdir_p(d, mode=448):
  83. """Create directory 'd' and all of its parents as needed. Unlike
  84. os.makedirs, does not give an error if d already exists.
  85. 448 is the decimal representation of the octal number 0700. Since
  86. python2 only supports 0700 and python3 only supports 0o700, we can use
  87. neither.
  88. Note that python2 and python3 differ in how they create the
  89. permissions for the intermediate directories. In python3, 'mode'
  90. only sets the mode for the last directory created.
  91. """
  92. try:
  93. os.makedirs(d, mode=mode)
  94. except OSError as e:
  95. if e.errno == errno.EEXIST:
  96. return
  97. raise
  98. def make_datadir_subdirectory(datadir, subdir):
  99. """
  100. Create a datadirectory (if necessary) and a subdirectory of
  101. that datadirectory. Ensure that both are mode 700.
  102. """
  103. mkdir_p(datadir)
  104. mkdir_p(os.path.join(datadir, subdir))
  105. def get_absolute_chutney_path():
  106. # use the current directory as the default
  107. # (./chutney already sets CHUTNEY_PATH using the path to the script)
  108. # use tools/test-network.sh if you want chutney to try really hard to find
  109. # itself
  110. relative_chutney_path = os.environ.get('CHUTNEY_PATH', os.getcwd())
  111. return os.path.abspath(relative_chutney_path)
  112. def get_absolute_net_path():
  113. # use the chutney path as the default
  114. absolute_chutney_path = get_absolute_chutney_path()
  115. relative_net_path = os.environ.get('CHUTNEY_DATA_DIR', 'net')
  116. # but what is it relative to?
  117. # let's check if it's in CHUTNEY_PATH first, to preserve
  118. # backwards-compatible behaviour
  119. chutney_net_path = os.path.join(absolute_chutney_path, relative_net_path)
  120. if os.path.isdir(chutney_net_path):
  121. return chutney_net_path
  122. # ok, it's relative to the current directory, whatever that is
  123. return os.path.abspath(relative_net_path)
  124. def get_absolute_nodes_path():
  125. # there's no way to customise this: we really don't need more options
  126. return os.path.join(get_absolute_net_path(), 'nodes')
  127. def get_new_absolute_nodes_path(now=time.time()):
  128. # automatically chosen to prevent path collisions, and result in an ordered
  129. # series of directory path names
  130. # should only be called by 'chutney configure', all other chutney commands
  131. # should use get_absolute_nodes_path()
  132. nodesdir = get_absolute_nodes_path()
  133. newdir = newdirbase = "%s.%d" % (nodesdir, now)
  134. # if the time is the same, fall back to a simple integer count
  135. # (this is very unlikely to happen unless the clock changes: it's not
  136. # possible to run multiple chutney networks at the same time)
  137. i = 0
  138. while os.path.exists(newdir):
  139. i += 1
  140. newdir = "%s.%d" % (newdirbase, i)
  141. return newdir
  142. def _warnMissingTor(tor_path, cmdline, tor_name="tor"):
  143. """Log a warning that the binary tor_name can't be found at tor_path
  144. while running cmdline.
  145. """
  146. help_msg_fmt = "Set the '{}' environment variable to the directory containing '{}'."
  147. if tor_name == "tor":
  148. help_msg = help_msg_fmt.format("CHUTNEY_TOR", tor_name)
  149. elif tor_name == "tor-gencert":
  150. help_msg = help_msg_fmt.format("CHUTNEY_TOR_GENCERT", tor_name)
  151. else:
  152. help_msg = ""
  153. print(("Cannot find the {} binary at '{}' for the command line '{}'. {}")
  154. .format(tor_name, tor_path, " ".join(cmdline), help_msg))
  155. def run_tor(cmdline, exit_on_missing=True):
  156. """Run the tor command line cmdline, which must start with the path or
  157. name of a tor binary.
  158. Returns the combined stdout and stderr of the process.
  159. If exit_on_missing is true, warn and exit if the tor binary is missing.
  160. Otherwise, raise a MissingBinaryException.
  161. """
  162. if not debug_flag:
  163. cmdline.append("--quiet")
  164. try:
  165. stdouterr = subprocess.check_output(cmdline,
  166. stderr=subprocess.STDOUT,
  167. universal_newlines=True,
  168. bufsize=-1)
  169. debug(stdouterr)
  170. except OSError as e:
  171. # only catch file not found error
  172. if e.errno == errno.ENOENT:
  173. if exit_on_missing:
  174. _warnMissingTor(cmdline[0], cmdline)
  175. sys.exit(1)
  176. else:
  177. raise MissingBinaryException()
  178. else:
  179. raise
  180. except subprocess.CalledProcessError as e:
  181. # only catch file not found error
  182. if e.returncode == 127:
  183. if exit_on_missing:
  184. _warnMissingTor(cmdline[0], cmdline)
  185. sys.exit(1)
  186. else:
  187. raise MissingBinaryException()
  188. else:
  189. raise
  190. return stdouterr
  191. def launch_process(cmdline, tor_name="tor", stdin=None, exit_on_missing=True, add_environ_vars=None):
  192. """Launch the command line cmdline, which must start with the path or
  193. name of a binary. Use tor_name as the canonical name of the binary.
  194. Pass stdin to the Popen constructor.
  195. Returns the Popen object for the launched process.
  196. """
  197. custom_environ = os.environ.copy()
  198. if add_environ_vars is not None:
  199. custom_environ.update(add_environ_vars)
  200. if tor_name == "tor" and not debug_flag:
  201. cmdline.append("--quiet")
  202. elif tor_name == "tor-gencert" and debug_flag:
  203. cmdline.append("-v")
  204. try:
  205. p = subprocess.Popen(cmdline,
  206. stdin=stdin,
  207. stdout=subprocess.PIPE,
  208. stderr=subprocess.STDOUT,
  209. universal_newlines=True,
  210. bufsize=-1,
  211. env=custom_environ)
  212. except OSError as e:
  213. # only catch file not found error
  214. if e.errno == errno.ENOENT:
  215. if exit_on_missing:
  216. _warnMissingTor(cmdline[0], cmdline, tor_name=tor_name)
  217. sys.exit(1)
  218. else:
  219. raise MissingBinaryException()
  220. else:
  221. raise
  222. return p
  223. def run_tor_gencert(cmdline, passphrase):
  224. """Run the tor-gencert command line cmdline, which must start with the
  225. path or name of a tor-gencert binary.
  226. Then send passphrase to the stdin of the process.
  227. Returns the combined stdout and stderr of the process.
  228. """
  229. p = launch_process(cmdline,
  230. tor_name="tor-gencert",
  231. stdin=subprocess.PIPE)
  232. (stdouterr, empty_stderr) = p.communicate(passphrase + "\n")
  233. print(stdouterr)
  234. assert p.returncode == 0 # XXXX BAD!
  235. assert empty_stderr is None
  236. return stdouterr
  237. @chutney.Util.memoized
  238. def tor_exists(tor):
  239. """Return true iff this tor binary exists."""
  240. try:
  241. run_tor([tor, "--quiet", "--version"], exit_on_missing=False)
  242. return True
  243. except MissingBinaryException:
  244. return False
  245. @chutney.Util.memoized
  246. def tor_gencert_exists(gencert):
  247. """Return true iff this tor-gencert binary exists."""
  248. try:
  249. p = launch_process([gencert, "--help"], exit_on_missing=False)
  250. p.wait()
  251. return True
  252. except MissingBinaryException:
  253. return False
  254. @chutney.Util.memoized
  255. def get_tor_version(tor, remote_hostname=None):
  256. """Return the version of the tor binary.
  257. Versions are cached for each unique tor path.
  258. """
  259. cmdline = []
  260. if remote_hostname != None:
  261. cmdline.extend(['ssh', remote_hostname])
  262. cmdline.extend([
  263. tor,
  264. "--version",
  265. ])
  266. tor_version = run_tor(cmdline)
  267. # clean it up a bit
  268. tor_version = tor_version.strip()
  269. tor_version = tor_version.replace("version ", "")
  270. tor_version = tor_version.replace(").", ")")
  271. # check we received a tor version, and nothing else
  272. assert re.match(r'^[-+.() A-Za-z0-9]+$', tor_version)
  273. return tor_version
  274. @chutney.Util.memoized
  275. def get_torrc_options(tor, remote_hostname=None):
  276. """Return the torrc options supported by the tor binary.
  277. Options are cached for each unique tor path.
  278. """
  279. cmdline = []
  280. if remote_hostname != None:
  281. cmdline.extend(['ssh', remote_hostname])
  282. cmdline.extend([
  283. tor,
  284. "--list-torrc-options",
  285. ])
  286. opts = run_tor(cmdline)
  287. # check we received a list of options, and nothing else
  288. assert re.match(r'(^\w+$)+', opts, flags=re.MULTILINE)
  289. torrc_opts = opts.split()
  290. return torrc_opts
  291. @chutney.Util.memoized
  292. def get_tor_modules(tor):
  293. """Check the list of compile-time modules advertised by the given
  294. 'tor' binary, and return a map from module name to a boolean
  295. describing whether it is supported.
  296. Unlisted modules are ones that Tor did not treat as compile-time
  297. optional modules.
  298. """
  299. cmdline = [
  300. tor,
  301. "--list-modules",
  302. "--quiet"
  303. ]
  304. try:
  305. mods = run_tor(cmdline)
  306. except subprocess.CalledProcessError as e:
  307. # Tor doesn't support --list-modules; act as if it said nothing.
  308. mods = ""
  309. supported = {}
  310. for line in mods.split("\n"):
  311. m = re.match(r'^(\S+): (yes|no)', line)
  312. if not m:
  313. continue
  314. supported[m.group(1)] = (m.group(2) == "yes")
  315. return supported
  316. def tor_has_module(tor, modname, default=True):
  317. """Return true iff the given tor binary supports a given compile-time
  318. module. If the module is not listed, return 'default'.
  319. """
  320. return get_tor_modules(tor).get(modname, default)
  321. class Node(object):
  322. """A Node represents a Tor node or a set of Tor nodes. It's created
  323. in a network configuration file.
  324. This class is responsible for holding the user's selected node
  325. configuration, and figuring out how the node needs to be
  326. configured and launched.
  327. """
  328. # Fields:
  329. # _parent
  330. # _env
  331. # _builder
  332. # _controller
  333. ########
  334. # Users are expected to call these:
  335. def __init__(self, parent=None, **kwargs):
  336. self._parent = parent
  337. self._env = self._createEnviron(parent, kwargs)
  338. self._builder = None
  339. self._controller = None
  340. def getN(self, N):
  341. return [Node(self) for _ in range(N)]
  342. def specialize(self, **kwargs):
  343. return Node(parent=self, **kwargs)
  344. def set_runtime(self, key, fn):
  345. """Specify a runtime function that gets invoked to find the
  346. runtime value of a key. It should take a single argument, which
  347. will be an environment.
  348. """
  349. setattr(self._env, "_get_"+key, fn)
  350. ######
  351. # Chutney uses these:
  352. def getBuilder(self):
  353. """Return a NodeBuilder instance to set up this node (that is, to
  354. write all the files that need to be in place so that this
  355. node can be run by a NodeController).
  356. """
  357. if self._builder is None:
  358. if self._env['remote_hostname'] != None:
  359. self._builder = RemoteNodeBuilder(self._env)
  360. else:
  361. self._builder = LocalNodeBuilder(self._env)
  362. return self._builder
  363. def getController(self):
  364. """Return a NodeController instance to control this node (that is,
  365. to start it, stop it, see if it's running, etc.)
  366. """
  367. if self._controller is None:
  368. if self._env['remote_hostname'] != None:
  369. self._controller = RemoteNodeController(self._env)
  370. else:
  371. self._controller = LocalNodeController(self._env)
  372. return self._controller
  373. def setNodenum(self, num):
  374. """Assign a value to the 'nodenum' element of this node. Each node
  375. in a network gets its own nodenum.
  376. """
  377. self._env['nodenum'] = num
  378. #####
  379. # These are internal:
  380. def _createEnviron(self, parent, argdict):
  381. """Return an Environ that delegates to the parent node's Environ (if
  382. there is a parent node), or to the default environment.
  383. """
  384. if parent:
  385. parentenv = parent._env
  386. else:
  387. parentenv = self._getDefaultEnviron()
  388. return TorEnviron(parentenv, **argdict)
  389. def _getDefaultEnviron(self):
  390. """Return the default environment. Any variables that we can't find
  391. set for any particular node, we look for here.
  392. """
  393. return _BASE_ENVIRON
  394. class _NodeCommon(object):
  395. """Internal helper class for functionality shared by some NodeBuilders
  396. and some NodeControllers."""
  397. # XXXX maybe this should turn into a mixin.
  398. def __init__(self, env):
  399. self._env = env
  400. def expand(self, pat, includePath=(".",)):
  401. return chutney.Templating.Template(pat, includePath).format(self._env)
  402. def _getTorrcFname(self):
  403. """Return the name of the file where we'll be writing torrc"""
  404. return self.expand("${torrc_fname}")
  405. class NodeBuilder(_NodeCommon):
  406. """Abstract base class. A NodeBuilder is responsible for doing all the
  407. one-time prep needed to set up a node in a network.
  408. """
  409. def __init__(self, env):
  410. _NodeCommon.__init__(self, env)
  411. def checkConfig(self, net):
  412. """Try to format our torrc; raise an exception if we can't.
  413. """
  414. def preConfig(self, net):
  415. """Called on all nodes before any nodes configure: generates keys as
  416. needed.
  417. """
  418. def config(self, net):
  419. """Called to configure a node: creates a torrc file for it."""
  420. def postConfig(self, net):
  421. """Called on each nodes after all nodes configure."""
  422. def isSupported(self, net):
  423. """Return true if this node appears to have everything it needs;
  424. false otherwise."""
  425. class NodeController(_NodeCommon):
  426. """Abstract base class. A NodeController is responsible for running a
  427. node on the network.
  428. """
  429. def __init__(self, env):
  430. _NodeCommon.__init__(self, env)
  431. def check(self, listRunning=True, listNonRunning=False):
  432. """See if this node is running, stopped, or crashed. If it's running
  433. and listRunning is set, print a short statement. If it's
  434. stopped and listNonRunning is set, then print a short statement.
  435. If it's crashed, print a statement. Return True if the
  436. node is running, false otherwise.
  437. """
  438. def start(self):
  439. """Try to start this node; return True if we succeeded or it was
  440. already running, False if we failed."""
  441. def stop(self, sig=signal.SIGINT):
  442. """Try to stop this node by sending it the signal 'sig'."""
  443. class LocalNodeBuilder(NodeBuilder):
  444. # Environment members used:
  445. # torrc -- which torrc file to use
  446. # torrc_template_path -- path to search for torrc files and include files
  447. # authority -- bool -- are we an authority?
  448. # bridgeauthority -- bool -- are we a bridge authority?
  449. # relay -- bool -- are we a relay?
  450. # bridge -- bool -- are we a bridge?
  451. # hs -- bool -- are we a hidden service?
  452. # nodenum -- int -- set by chutney -- which unique node index is this?
  453. # dir -- path -- set by chutney -- data directory for this tor
  454. # tor_gencert -- path to tor_gencert binary
  455. # tor -- path to tor binary
  456. # auth_cert_lifetime -- lifetime of authority certs, in months.
  457. # ip -- primary IP address (usually IPv4) to listen on
  458. # ipv6_addr -- secondary IP address (usually IPv6) to listen on
  459. # orport, dirport -- used on authorities, relays, and bridges. The orport
  460. # is used for both IPv4 and IPv6, if present
  461. # fingerprint -- used only if authority
  462. # dirserver_flags -- used only if authority
  463. # nick -- nickname of this router
  464. # Environment members set
  465. # fingerprint -- hex router key fingerprint
  466. # nodenum -- int -- set by chutney -- which unique node index is this?
  467. def __init__(self, env):
  468. NodeBuilder.__init__(self, env)
  469. self._env = env
  470. def _createTorrcFile(self, checkOnly=False):
  471. """Write the torrc file for this node, disabling any options
  472. that are not supported by env's tor binary using comments.
  473. If checkOnly, just make sure that the formatting is indeed
  474. possible.
  475. """
  476. global torrc_option_warn_count
  477. fn_out = self._getTorrcFname()
  478. torrc_template = self._getTorrcTemplate()
  479. output = torrc_template.format(self._env)
  480. if checkOnly:
  481. # XXXX Is it time-consuming to format? If so, cache here.
  482. return
  483. # now filter the options we're about to write, commenting out
  484. # the options that the current tor binary doesn't support
  485. tor = self._env['tor']
  486. tor_version = get_tor_version(tor)
  487. torrc_opts = get_torrc_options(tor)
  488. # check if each option is supported before writing it
  489. # Unsupported option values may need special handling.
  490. with open(fn_out, 'w') as f:
  491. # we need to do case-insensitive option comparison
  492. lower_opts = [opt.lower() for opt in torrc_opts]
  493. # keep ends when splitting lines, so we can write them out
  494. # using writelines() without messing around with "\n"s
  495. for line in output.splitlines(True):
  496. # check if the first word on the line is a supported option,
  497. # preserving empty lines and comment lines
  498. sline = line.strip()
  499. if (len(sline) == 0 or
  500. sline[0] == '#' or
  501. sline.split()[0].lower() in lower_opts):
  502. pass
  503. else:
  504. warn_msg = (("The tor binary at {} does not support " +
  505. "the option in the torrc line:\n{}")
  506. .format(tor, line.strip()))
  507. if torrc_option_warn_count < TORRC_OPTION_WARN_LIMIT:
  508. print(warn_msg)
  509. torrc_option_warn_count += 1
  510. else:
  511. debug(warn_msg)
  512. # always dump the full output to the torrc file
  513. line = ("# {} version {} does not support: {}"
  514. .format(tor, tor_version, line))
  515. f.writelines([line])
  516. def _getTorrcTemplate(self):
  517. """Return the template used to write the torrc for this node."""
  518. template_path = self._env['torrc_template_path']
  519. return chutney.Templating.Template("$${include:$torrc}",
  520. includePath=template_path)
  521. def _getFreeVars(self):
  522. """Return a set of the free variables in the torrc template for this
  523. node.
  524. """
  525. template = self._getTorrcTemplate()
  526. return template.freevars(self._env)
  527. def checkConfig(self, net):
  528. """Try to format our torrc; raise an exception if we can't.
  529. """
  530. self._createTorrcFile(checkOnly=True)
  531. def preConfig(self, net):
  532. """Called on all nodes before any nodes configure: generates keys and
  533. hidden service directories as needed.
  534. """
  535. self._makeDataDir()
  536. if self._env['authority']:
  537. self._genAuthorityKey()
  538. if self._env['relay']:
  539. self._genRouterKey()
  540. if self._env['hs']:
  541. self._makeHiddenServiceDir()
  542. def config(self, net):
  543. """Called to configure a node: creates a torrc file for it."""
  544. self._createTorrcFile()
  545. # self._createScripts()
  546. def postConfig(self, net):
  547. """Called on each nodes after all nodes configure."""
  548. # self.net.addNode(self)
  549. pass
  550. def isSupported(self, net):
  551. """Return true if this node appears to have everything it needs;
  552. false otherwise."""
  553. if not tor_exists(self._env['tor']):
  554. print("No binary found for %r"%self._env['tor'])
  555. return False
  556. if self._env['authority']:
  557. if not tor_has_module(self._env['tor'], "dirauth"):
  558. print("No dirauth support in %r"%self._env['tor'])
  559. return False
  560. if not tor_gencert_exists(self._env['tor-gencert']):
  561. print("No binary found for tor-gencert %r"%self._env['tor-gencrrt'])
  562. def _makeDataDir(self):
  563. """Create the data directory (with keys subdirectory) for this node.
  564. """
  565. datadir = self._env['dir']
  566. make_datadir_subdirectory(datadir, "keys")
  567. def _makeHiddenServiceDir(self):
  568. """Create the hidden service subdirectory for this node.
  569. The directory name is stored under the 'hs_directory' environment
  570. key. It is combined with the 'dir' data directory key to yield the
  571. path to the hidden service directory.
  572. """
  573. datadir = self._env['dir']
  574. make_datadir_subdirectory(datadir, self._env['hs_directory'])
  575. def _genAuthorityKey(self):
  576. """Generate an authority identity and signing key for this authority,
  577. if they do not already exist."""
  578. datadir = self._env['dir']
  579. tor_gencert = self._env['tor_gencert']
  580. lifetime = self._env['auth_cert_lifetime']
  581. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  582. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  583. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  584. addr = self.expand("${ip}:${dirport}")
  585. passphrase = self._env['auth_passphrase']
  586. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  587. return
  588. cmdline = [
  589. tor_gencert,
  590. '--create-identity-key',
  591. '--passphrase-fd', '0',
  592. '-i', idfile,
  593. '-s', skfile,
  594. '-c', certfile,
  595. '-m', str(lifetime),
  596. '-a', addr,
  597. ]
  598. # nicknames are testNNNaa[OLD], but we want them to look tidy
  599. print("Creating identity key for {:12} with {}"
  600. .format(self._env['nick'], cmdline[0]))
  601. debug("Identity key path '{}', command '{}'"
  602. .format(idfile, " ".join(cmdline)))
  603. run_tor_gencert(cmdline, passphrase)
  604. def _genRouterKey(self):
  605. """Generate an identity key for this router, unless we already have,
  606. and set up the 'fingerprint' entry in the Environ.
  607. """
  608. datadir = self._env['dir']
  609. tor = self._env['tor']
  610. torrc = self._getTorrcFname()
  611. cmdline = [
  612. tor,
  613. "--ignore-missing-torrc",
  614. "-f", torrc,
  615. "--list-fingerprint",
  616. "--orport", "1",
  617. "--datadirectory", datadir,
  618. ]
  619. stdouterr = run_tor(cmdline)
  620. fingerprint = "".join((stdouterr.rstrip().split('\n')[-1]).split()[1:])
  621. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  622. print("Error when getting fingerprint using '%r'. It output '%r'."
  623. .format(" ".join(cmdline), stdouterr))
  624. sys.exit(1)
  625. self._env['fingerprint'] = fingerprint
  626. def _getAltAuthLines(self, hasbridgeauth=False):
  627. """Return a combination of AlternateDirAuthority,
  628. and AlternateBridgeAuthority lines for
  629. this Node, appropriately. Non-authorities return ""."""
  630. if not self._env['authority']:
  631. return ""
  632. datadir = self._env['dir']
  633. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  634. v3id = None
  635. with open(certfile, 'r') as f:
  636. for line in f:
  637. if line.startswith("fingerprint"):
  638. v3id = line.split()[1].strip()
  639. break
  640. assert v3id is not None
  641. if self._env['bridgeauthority']:
  642. # Bridge authorities return AlternateBridgeAuthority with
  643. # the 'bridge' flag set.
  644. options = ("AlternateBridgeAuthority",)
  645. self._env['dirserver_flags'] += " bridge"
  646. else:
  647. # Directory authorities return AlternateDirAuthority with
  648. # the 'v3ident' flag set.
  649. # XXXX This next line is needed for 'bridges' but breaks
  650. # 'basic'
  651. if hasbridgeauth:
  652. options = ("AlternateDirAuthority",)
  653. else:
  654. options = ("DirAuthority",)
  655. self._env['dirserver_flags'] += " v3ident=%s" % v3id
  656. authlines = ""
  657. for authopt in options:
  658. authlines += "%s %s orport=%s" % (
  659. authopt, self._env['nick'], self._env['orport'])
  660. # It's ok to give an authority's IPv6 address to an IPv4-only
  661. # client or relay: it will and must ignore it
  662. # and yes, the orport is the same on IPv4 and IPv6
  663. if self._env['ipv6_addr'] is not None:
  664. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  665. self._env['orport'])
  666. authlines += " %s %s:%s %s\n" % (
  667. self._env['dirserver_flags'], self._env['ip'],
  668. self._env['dirport'], self._env['fingerprint'])
  669. return authlines
  670. def _getBridgeLines(self):
  671. """Return potential Bridge line for this Node. Non-bridge
  672. relays return "".
  673. """
  674. if not self._env['bridge']:
  675. return ""
  676. if self._env['pt_bridge']:
  677. port = self._env['ptport']
  678. transport = self._env['pt_transport']
  679. extra = self._env['pt_extra']
  680. else:
  681. # the orport is the same on IPv4 and IPv6
  682. port = self._env['orport']
  683. transport = ""
  684. extra = ""
  685. BRIDGE_LINE_TEMPLATE = "Bridge %s %s:%s %s %s\n"
  686. bridgelines = BRIDGE_LINE_TEMPLATE % (transport,
  687. self._env['ip'],
  688. port,
  689. self._env['fingerprint'],
  690. extra)
  691. if self._env['ipv6_addr'] is not None:
  692. bridgelines += BRIDGE_LINE_TEMPLATE % (transport,
  693. self._env['ipv6_addr'],
  694. port,
  695. self._env['fingerprint'],
  696. extra)
  697. return bridgelines
  698. def scp_file(abs_filepath, host):
  699. if not os.path.isabs(abs_filepath) or abs_filepath[0:5] != '/tmp/':
  700. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  701. # myself in the foot
  702. raise Exception('SCP path must be absolute and must be in /tmp')
  703. assert(':' not in host)
  704. assert(':' not in abs_filepath)
  705. remote_filepath = os.path.dirname(abs_filepath)
  706. cmd = ['scp', abs_filepath, ':'.join([host, remote_filepath])]
  707. print('Transferring file: {}'.format(cmd))
  708. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  709. def scp_dir(abs_dirpath, host):
  710. if not os.path.isabs(abs_dirpath) or abs_dirpath[0:5] != '/tmp/':
  711. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  712. # myself in the foot
  713. raise Exception('SCP path must be absolute and must be in /tmp')
  714. assert(':' not in host)
  715. assert(':' not in abs_dirpath)
  716. remote_dirpath = os.path.dirname(abs_dirpath)
  717. cmd = ['scp', '-r', abs_dirpath, ':'.join([host, remote_dirpath])]
  718. print('Transferring files: {}'.format(cmd))
  719. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  720. def scp_dir_backwards(abs_dirpath, host):
  721. if not os.path.isabs(abs_dirpath) or abs_dirpath[0:5] != '/tmp/':
  722. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  723. # myself in the foot
  724. raise Exception('SCP path must be absolute and must be in /tmp')
  725. assert(':' not in host)
  726. assert(':' not in abs_dirpath)
  727. remote_dirpath = os.path.dirname(abs_dirpath)
  728. cmd = ['scp', '-r', ':'.join([host, abs_dirpath]), remote_dirpath]
  729. print('Transferring files backwards: {}'.format(cmd))
  730. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  731. def ssh_mkdir_p(abs_dirpath, remote_hostname):
  732. if not os.path.isabs(abs_dirpath) or abs_dirpath[0:5] != '/tmp/':
  733. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  734. # myself in the foot
  735. raise Exception('Path must be absolute and must be in /tmp')
  736. cmd = ['ssh', remote_hostname, 'mkdir', '-p', abs_dirpath]
  737. print('Making directory: {}'.format(cmd))
  738. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  739. def ssh_rm_if_exists(abs_dirpath, remote_hostname):
  740. if not os.path.isabs(abs_dirpath) or abs_dirpath[0:5] != '/tmp/':
  741. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  742. # myself in the foot
  743. raise Exception('Path must be absolute and must be in /tmp')
  744. cmd = ['ssh', remote_hostname, 'rm', '-f', abs_dirpath]
  745. print('Removing: {}'.format(cmd))
  746. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  747. def ssh_file_exists(abs_filepath, remote_hostname):
  748. if not os.path.isabs(abs_filepath) or abs_filepath[0:5] != '/tmp/':
  749. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  750. # myself in the foot
  751. raise Exception('Path must be absolute and must be in /tmp')
  752. assert('"' not in abs_filepath)
  753. assert('$' not in abs_filepath)
  754. assert('\\' not in abs_filepath)
  755. cmd = ['ssh', remote_hostname, '[ -f "{}" ] && exit 0 || exit 99'.format(abs_filepath)]
  756. print('Checking file existence: {}'.format(cmd))
  757. try:
  758. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  759. except subprocess.CalledProcessError as e:
  760. if e.returncode == 99:
  761. return False
  762. raise
  763. return True
  764. def ssh_symlink(abs_dirpath, abs_linkpath, remote_hostname):
  765. if not os.path.isabs(abs_dirpath) or abs_dirpath[0:5] != '/tmp/':
  766. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  767. # myself in the foot
  768. raise Exception('Path must be absolute and must be in /tmp')
  769. if not os.path.isabs(abs_linkpath) or abs_linkpath[0:5] != '/tmp/':
  770. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  771. # myself in the foot
  772. raise Exception('Link must be absolute and must be in /tmp')
  773. cmd = ['ssh', remote_hostname, 'ln', '-s', abs_dirpath, abs_linkpath]
  774. print('Making link: {}'.format(cmd))
  775. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  776. def ssh_read_file(abs_filepath, remote_hostname):
  777. if not os.path.isabs(abs_filepath) or abs_filepath[0:5] != '/tmp/':
  778. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  779. # myself in the foot
  780. raise Exception('Path must be absolute and must be in /tmp')
  781. if not ssh_file_exists(abs_filepath, remote_hostname):
  782. return None
  783. cmd = ['ssh', remote_hostname, 'cat', abs_filepath]
  784. print('Reading file: {}'.format(cmd))
  785. try:
  786. return subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  787. except subprocess.CalledProcessError as e:
  788. # although something else may have gone wrong, we'll assume the file doesn't exist
  789. print('File existed, but now returns an error; assuming it no longer exists')
  790. return None
  791. def ssh_kill(pid, code, remote_hostname):
  792. assert pid > 1
  793. cmd = ['ssh', remote_hostname, 'kill', '-s', str(code), str(pid)]
  794. print('Sending signal: {}'.format(cmd))
  795. try:
  796. subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  797. except subprocess.CalledProcessError as e:
  798. if e.returncode != 1:
  799. # the process might not exist
  800. return False
  801. return True
  802. def ssh_grep(pattern, abs_filepath, remote_hostname):
  803. if not os.path.isabs(abs_filepath) or abs_filepath[0:5] != '/tmp/':
  804. # this check for '/tmp' is in no way secure, but helps prevent me from shooting
  805. # myself in the foot
  806. raise Exception('Path must be absolute and must be in /tmp')
  807. cmd = ['ssh', remote_hostname, 'egrep', '"{}"'.format(pattern), abs_filepath]
  808. #print('Text search: {}'.format(cmd))
  809. try:
  810. return subprocess.check_output(cmd, stderr=subprocess.STDOUT).decode('utf-8')
  811. except subprocess.CalledProcessError as e:
  812. if e.returncode == 1:
  813. # egrep will exit with 1 if it doesn't find anything
  814. return ''
  815. class RemoteNodeBuilder(NodeBuilder):
  816. # Environment members used:
  817. # torrc -- which torrc file to use
  818. # torrc_template_path -- path to search for torrc files and include files
  819. # authority -- bool -- are we an authority?
  820. # bridgeauthority -- bool -- are we a bridge authority?
  821. # relay -- bool -- are we a relay?
  822. # bridge -- bool -- are we a bridge?
  823. # hs -- bool -- are we a hidden service?
  824. # nodenum -- int -- set by chutney -- which unique node index is this?
  825. # dir -- path -- set by chutney -- data directory for this tor
  826. # tor_gencert -- path to tor_gencert binary
  827. # tor -- path to tor binary
  828. # auth_cert_lifetime -- lifetime of authority certs, in months.
  829. # ip -- primary IP address (usually IPv4) to listen on
  830. # ipv6_addr -- secondary IP address (usually IPv6) to listen on
  831. # orport, dirport -- used on authorities, relays, and bridges. The orport
  832. # is used for both IPv4 and IPv6, if present
  833. # fingerprint -- used only if authority
  834. # dirserver_flags -- used only if authority
  835. # nick -- nickname of this router
  836. # Environment members set
  837. # fingerprint -- hex router key fingerprint
  838. # nodenum -- int -- set by chutney -- which unique node index is this?
  839. def __init__(self, env):
  840. NodeBuilder.__init__(self, env)
  841. self._env = env
  842. def _createTorrcFile(self, checkOnly=False):
  843. """Write the torrc file for this node, disabling any options
  844. that are not supported by env's tor binary using comments.
  845. If checkOnly, just make sure that the formatting is indeed
  846. possible.
  847. """
  848. global torrc_option_warn_count
  849. fn_out = self._getTorrcFname()
  850. torrc_template = self._getTorrcTemplate()
  851. output = torrc_template.format(self._env)
  852. if checkOnly:
  853. # XXXX Is it time-consuming to format? If so, cache here.
  854. return
  855. # now filter the options we're about to write, commenting out
  856. # the options that the current tor binary doesn't support
  857. tor = self._env['tor']
  858. tor_version = get_tor_version(tor, remote_hostname=self._env['remote_hostname'])
  859. torrc_opts = get_torrc_options(tor, remote_hostname=self._env['remote_hostname'])
  860. # check if each option is supported before writing it
  861. # Unsupported option values may need special handling.
  862. with open(fn_out, 'w') as f:
  863. # we need to do case-insensitive option comparison
  864. lower_opts = [opt.lower() for opt in torrc_opts]
  865. # keep ends when splitting lines, so we can write them out
  866. # using writelines() without messing around with "\n"s
  867. for line in output.splitlines(True):
  868. # check if the first word on the line is a supported option,
  869. # preserving empty lines and comment lines
  870. sline = line.strip()
  871. if (len(sline) == 0 or
  872. sline[0] == '#' or
  873. sline.split()[0].lower() in lower_opts):
  874. pass
  875. else:
  876. warn_msg = (("The tor binary at {} does not support " +
  877. "the option in the torrc line:\n{}")
  878. .format(tor, line.strip()))
  879. if torrc_option_warn_count < TORRC_OPTION_WARN_LIMIT:
  880. print(warn_msg)
  881. torrc_option_warn_count += 1
  882. else:
  883. debug(warn_msg)
  884. # always dump the full output to the torrc file
  885. line = ("# {} version {} does not support: {}"
  886. .format(tor, tor_version, line))
  887. f.writelines([line])
  888. def _getTorrcTemplate(self):
  889. """Return the template used to write the torrc for this node."""
  890. template_path = self._env['torrc_template_path']
  891. return chutney.Templating.Template("$${include:$torrc}",
  892. includePath=template_path)
  893. def _getFreeVars(self):
  894. """Return a set of the free variables in the torrc template for this
  895. node.
  896. """
  897. template = self._getTorrcTemplate()
  898. return template.freevars(self._env)
  899. def checkConfig(self, net):
  900. """Try to format our torrc; raise an exception if we can't.
  901. """
  902. self._createTorrcFile(checkOnly=True)
  903. def preConfig(self, net):
  904. """Called on all nodes before any nodes configure: generates keys and
  905. hidden service directories as needed.
  906. """
  907. self._makeDataDir()
  908. if self._env['authority']:
  909. self._genAuthorityKey()
  910. if self._env['relay']:
  911. self._genRouterKey()
  912. if self._env['hs']:
  913. self._makeHiddenServiceDir()
  914. def config(self, net):
  915. """Called to configure a node: creates a torrc file for it."""
  916. self._createTorrcFile()
  917. # self._createScripts()
  918. def postConfig(self, net):
  919. """Called on each nodes after all nodes configure."""
  920. # self.net.addNode(self)
  921. scp_dir(os.path.abspath(self._env['dir']), self._env['remote_hostname'])
  922. shutil.rmtree(self._env['dir'])
  923. def isSupported(self, net):
  924. """Return true if this node appears to have everything it needs;
  925. false otherwise."""
  926. if not tor_exists(self._env['tor']):
  927. print("No binary found for %r"%self._env['tor'])
  928. return False
  929. if self._env['authority']:
  930. if not tor_has_module(self._env['tor'], "dirauth"):
  931. print("No dirauth support in %r"%self._env['tor'])
  932. return False
  933. if not tor_gencert_exists(self._env['tor-gencert']):
  934. print("No binary found for tor-gencert %r"%self._env['tor-gencrrt'])
  935. def _makeDataDir(self):
  936. """Create the data directory (with keys subdirectory) for this node.
  937. """
  938. datadir = self._env['dir']
  939. make_datadir_subdirectory(datadir, "keys")
  940. def _makeHiddenServiceDir(self):
  941. """Create the hidden service subdirectory for this node.
  942. The directory name is stored under the 'hs_directory' environment
  943. key. It is combined with the 'dir' data directory key to yield the
  944. path to the hidden service directory.
  945. """
  946. datadir = self._env['dir']
  947. make_datadir_subdirectory(datadir, self._env['hs_directory'])
  948. def _genAuthorityKey(self):
  949. """Generate an authority identity and signing key for this authority,
  950. if they do not already exist."""
  951. datadir = self._env['dir']
  952. tor_gencert = self._env['tor_gencert']
  953. lifetime = self._env['auth_cert_lifetime']
  954. idfile = os.path.join(datadir, 'keys', "authority_identity_key")
  955. skfile = os.path.join(datadir, 'keys', "authority_signing_key")
  956. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  957. addr = self.expand("${ip}:${dirport}")
  958. passphrase = self._env['auth_passphrase']
  959. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  960. return
  961. cmdline = [
  962. tor_gencert,
  963. '--create-identity-key',
  964. '--passphrase-fd', '0',
  965. '-i', idfile,
  966. '-s', skfile,
  967. '-c', certfile,
  968. '-m', str(lifetime),
  969. '-a', addr,
  970. ]
  971. # nicknames are testNNNaa[OLD], but we want them to look tidy
  972. print("Creating identity key for {:12} with {}"
  973. .format(self._env['nick'], cmdline[0]))
  974. debug("Identity key path '{}', command '{}'"
  975. .format(idfile, " ".join(cmdline)))
  976. run_tor_gencert(cmdline, passphrase)
  977. def _genRouterKey(self):
  978. """Generate an identity key for this router, unless we already have,
  979. and set up the 'fingerprint' entry in the Environ.
  980. """
  981. datadir = self._env['dir']
  982. tor = self._env['tor']
  983. torrc = self._getTorrcFname()
  984. cmdline = [
  985. tor,
  986. "--ignore-missing-torrc",
  987. "-f", torrc,
  988. "--list-fingerprint",
  989. "--orport", "1",
  990. "--datadirectory", datadir,
  991. ]
  992. stdouterr = run_tor(cmdline)
  993. fingerprint = "".join((stdouterr.rstrip().split('\n')[-1]).split()[1:])
  994. if not re.match(r'^[A-F0-9]{40}$', fingerprint):
  995. print("Error when getting fingerprint using '%r'. It output '%r'."
  996. .format(" ".join(cmdline), stdouterr))
  997. sys.exit(1)
  998. self._env['fingerprint'] = fingerprint
  999. def _getAltAuthLines(self, hasbridgeauth=False):
  1000. """Return a combination of AlternateDirAuthority,
  1001. and AlternateBridgeAuthority lines for
  1002. this Node, appropriately. Non-authorities return ""."""
  1003. if not self._env['authority']:
  1004. return ""
  1005. datadir = self._env['dir']
  1006. certfile = os.path.join(datadir, 'keys', "authority_certificate")
  1007. v3id = None
  1008. with open(certfile, 'r') as f:
  1009. for line in f:
  1010. if line.startswith("fingerprint"):
  1011. v3id = line.split()[1].strip()
  1012. break
  1013. assert v3id is not None
  1014. if self._env['bridgeauthority']:
  1015. # Bridge authorities return AlternateBridgeAuthority with
  1016. # the 'bridge' flag set.
  1017. options = ("AlternateBridgeAuthority",)
  1018. self._env['dirserver_flags'] += " bridge"
  1019. else:
  1020. # Directory authorities return AlternateDirAuthority with
  1021. # the 'v3ident' flag set.
  1022. # XXXX This next line is needed for 'bridges' but breaks
  1023. # 'basic'
  1024. if hasbridgeauth:
  1025. options = ("AlternateDirAuthority",)
  1026. else:
  1027. options = ("DirAuthority",)
  1028. self._env['dirserver_flags'] += " v3ident=%s" % v3id
  1029. authlines = ""
  1030. for authopt in options:
  1031. authlines += "%s %s orport=%s" % (
  1032. authopt, self._env['nick'], self._env['orport'])
  1033. # It's ok to give an authority's IPv6 address to an IPv4-only
  1034. # client or relay: it will and must ignore it
  1035. # and yes, the orport is the same on IPv4 and IPv6
  1036. if self._env['ipv6_addr'] is not None:
  1037. authlines += " ipv6=%s:%s" % (self._env['ipv6_addr'],
  1038. self._env['orport'])
  1039. authlines += " %s %s:%s %s\n" % (
  1040. self._env['dirserver_flags'], self._env['ip'],
  1041. self._env['dirport'], self._env['fingerprint'])
  1042. return authlines
  1043. def _getBridgeLines(self):
  1044. """Return potential Bridge line for this Node. Non-bridge
  1045. relays return "".
  1046. """
  1047. if not self._env['bridge']:
  1048. return ""
  1049. if self._env['pt_bridge']:
  1050. port = self._env['ptport']
  1051. transport = self._env['pt_transport']
  1052. extra = self._env['pt_extra']
  1053. else:
  1054. # the orport is the same on IPv4 and IPv6
  1055. port = self._env['orport']
  1056. transport = ""
  1057. extra = ""
  1058. BRIDGE_LINE_TEMPLATE = "Bridge %s %s:%s %s %s\n"
  1059. bridgelines = BRIDGE_LINE_TEMPLATE % (transport,
  1060. self._env['ip'],
  1061. port,
  1062. self._env['fingerprint'],
  1063. extra)
  1064. if self._env['ipv6_addr'] is not None:
  1065. bridgelines += BRIDGE_LINE_TEMPLATE % (transport,
  1066. self._env['ipv6_addr'],
  1067. port,
  1068. self._env['fingerprint'],
  1069. extra)
  1070. return bridgelines
  1071. class LocalNodeController(NodeController):
  1072. def __init__(self, env):
  1073. NodeController.__init__(self, env)
  1074. self._env = env
  1075. def getNick(self):
  1076. """Return the nickname for this node."""
  1077. return self._env['nick']
  1078. def getPid(self):
  1079. """Assuming that this node has its pidfile in ${dir}/pid, return
  1080. the pid of the running process, or None if there is no pid in the
  1081. file.
  1082. """
  1083. pidfile = os.path.join(self._env['dir'], 'pid')
  1084. if not os.path.exists(pidfile):
  1085. return None
  1086. with open(pidfile, 'r') as f:
  1087. try:
  1088. return int(f.read())
  1089. except ValueError:
  1090. return None
  1091. def isRunning(self, pid=None):
  1092. """Return true iff this node is running. (If 'pid' is provided, we
  1093. assume that the pid provided is the one of this node. Otherwise
  1094. we call getPid().
  1095. """
  1096. if pid is None:
  1097. pid = self.getPid()
  1098. if pid is None:
  1099. return False
  1100. try:
  1101. os.kill(pid, 0) # "kill 0" == "are you there?"
  1102. except OSError as e:
  1103. if e.errno == errno.ESRCH:
  1104. return False
  1105. raise
  1106. # okay, so the process exists. Say "True" for now.
  1107. # XXXX check if this is really tor!
  1108. return True
  1109. def check(self, listRunning=True, listNonRunning=False):
  1110. """See if this node is running, stopped, or crashed. If it's running
  1111. and listRunning is set, print a short statement. If it's
  1112. stopped and listNonRunning is set, then print a short statement.
  1113. If it's crashed, print a statement. Return True if the
  1114. node is running, false otherwise.
  1115. """
  1116. # XXX Split this into "check" and "print" parts.
  1117. pid = self.getPid()
  1118. nick = self._env['nick']
  1119. datadir = self._env['dir']
  1120. corefile = "core.%s" % pid
  1121. tor_version = get_tor_version(self._env['tor'])
  1122. if self.isRunning(pid):
  1123. if listRunning:
  1124. # PIDs are typically 65535 or less
  1125. print("{:12} is running with PID {:5}: {}"
  1126. .format(nick, pid, tor_version))
  1127. return True
  1128. elif os.path.exists(os.path.join(datadir, corefile)):
  1129. if listNonRunning:
  1130. print("{:12} seems to have crashed, and left core file {}: {}"
  1131. .format(nick, corefile, tor_version))
  1132. return False
  1133. else:
  1134. if listNonRunning:
  1135. print("{:12} is stopped: {}"
  1136. .format(nick, tor_version))
  1137. return False
  1138. def hup(self):
  1139. """Send a SIGHUP to this node, if it's running."""
  1140. pid = self.getPid()
  1141. nick = self._env['nick']
  1142. if self.isRunning(pid):
  1143. print("Sending sighup to {}".format(nick))
  1144. os.kill(pid, signal.SIGHUP)
  1145. return True
  1146. else:
  1147. print("{:12} is not running".format(nick))
  1148. return False
  1149. def start(self):
  1150. """Try to start this node; return True if we succeeded or it was
  1151. already running, False if we failed."""
  1152. if self.isRunning():
  1153. print("{:12} is already running".format(self._env['nick']))
  1154. return True
  1155. tor_path = self._env['tor']
  1156. torrc = self._getTorrcFname()
  1157. cmdline = []
  1158. if self._env['numa_settings'] is not None:
  1159. (numa_node, processors) = self._env['numa_settings']
  1160. cmdline.extend([
  1161. 'numactl',
  1162. '--membind={}'.format(numa_node),
  1163. '--physcpubind={}'.format(','.join(map(str, processors))),
  1164. ])
  1165. #
  1166. if self._env['valgrind_settings'] is not None:
  1167. cmdline.append('valgrind')
  1168. cmdline.extend(self._env['valgrind_settings'])
  1169. cmdline.append('--log-file={}'.format(self._env['valgrind_log']))
  1170. #
  1171. add_environ_vars = self._env['add_environ_vars']
  1172. if add_environ_vars is not None:
  1173. add_environ_vars = add_environ_vars.copy()
  1174. #
  1175. if self._env['google_cpu_profiler'] is True:
  1176. if add_environ_vars is None:
  1177. add_environ_vars = {}
  1178. add_environ_vars['CPUPROFILE'] = os.path.join(self._env['dir'], 'cpu-prof.out')
  1179. #
  1180. cmdline.extend([
  1181. tor_path,
  1182. "-f", torrc,
  1183. ])
  1184. p = launch_process(cmdline, add_environ_vars=add_environ_vars)
  1185. if self.waitOnLaunch():
  1186. # this requires that RunAsDaemon is set
  1187. (stdouterr, empty_stderr) = p.communicate()
  1188. debug(stdouterr)
  1189. assert empty_stderr is None
  1190. else:
  1191. # this does not require RunAsDaemon to be set, but is slower.
  1192. #
  1193. # poll() only catches failures before the call itself
  1194. # so let's sleep a little first
  1195. # this does, of course, slow down process launch
  1196. # which can require an adjustment to the voting interval
  1197. #
  1198. # avoid writing a newline or space when polling
  1199. # so output comes out neatly
  1200. sys.stdout.write('.')
  1201. sys.stdout.flush()
  1202. time.sleep(self._env['poll_launch_time'])
  1203. p.poll()
  1204. if p.returncode is not None and p.returncode != 0:
  1205. if self._env['poll_launch_time'] is None:
  1206. print(("Couldn't launch {:12} command '{}': " +
  1207. "exit {}, output '{}'")
  1208. .format(self._env['nick'],
  1209. " ".join(cmdline),
  1210. p.returncode,
  1211. stdouterr))
  1212. else:
  1213. print(("Couldn't poll {:12} command '{}' " +
  1214. "after waiting {} seconds for launch: " +
  1215. "exit {}").format(self._env['nick'],
  1216. " ".join(cmdline),
  1217. self._env['poll_launch_time'],
  1218. p.returncode))
  1219. return False
  1220. return True
  1221. def stop(self, sig=signal.SIGINT):
  1222. """Try to stop this node by sending it the signal 'sig'."""
  1223. pid = self.getPid()
  1224. if not self.isRunning(pid):
  1225. print("{:12} is not running".format(self._env['nick']))
  1226. return
  1227. os.kill(pid, sig)
  1228. def cleanup_lockfile(self):
  1229. lf = self._env['lockfile']
  1230. if not self.isRunning() and os.path.exists(lf):
  1231. debug("Removing stale lock file for {} ..."
  1232. .format(self._env['nick']))
  1233. os.remove(lf)
  1234. def waitOnLaunch(self):
  1235. """Check whether we can wait() for the tor process to launch"""
  1236. # TODO: is this the best place for this code?
  1237. # RunAsDaemon default is 0
  1238. runAsDaemon = False
  1239. with open(self._getTorrcFname(), 'r') as f:
  1240. for line in f.readlines():
  1241. stline = line.strip()
  1242. # if the line isn't all whitespace or blank
  1243. if len(stline) > 0:
  1244. splline = stline.split()
  1245. # if the line has at least two tokens on it
  1246. if (len(splline) > 0 and
  1247. splline[0].lower() == "RunAsDaemon".lower() and
  1248. splline[1] == "1"):
  1249. # use the RunAsDaemon value from the torrc
  1250. # TODO: multiple values?
  1251. runAsDaemon = True
  1252. if runAsDaemon:
  1253. # we must use wait() instead of poll()
  1254. self._env['poll_launch_time'] = None
  1255. return True
  1256. else:
  1257. # we must use poll() instead of wait()
  1258. if self._env['poll_launch_time'] is None:
  1259. self._env['poll_launch_time'] = \
  1260. self._env['poll_launch_time_default']
  1261. return False
  1262. def getLogfile(self, info=False):
  1263. """Return the expected path to the logfile for this instance."""
  1264. datadir = self._env['dir']
  1265. if info:
  1266. logname = "info.log"
  1267. else:
  1268. logname = "notice.log"
  1269. return os.path.join(datadir, logname)
  1270. def getLastBootstrapStatus(self):
  1271. """Look through the logs and return the last bootstrap message
  1272. received as a 3-tuple of percentage complete, keyword
  1273. (optional), and message.
  1274. """
  1275. logfname = self.getLogfile()
  1276. if not os.path.exists(logfname):
  1277. return (-200, "no_logfile", "There is no logfile yet.")
  1278. percent,keyword,message=-100,"no_message","No bootstrap messages yet."
  1279. with open(logfname, 'r') as f:
  1280. for line in f:
  1281. m = re.search(r'Bootstrapped (\d+)%(?: \(([^\)]*)\))?: (.*)',
  1282. line)
  1283. if m:
  1284. percent, keyword, message = m.groups()
  1285. percent = int(percent)
  1286. return (percent, keyword, message)
  1287. def isBootstrapped(self):
  1288. """Return true iff the logfile says that this instance is
  1289. bootstrapped."""
  1290. pct, _, _ = self.getLastBootstrapStatus()
  1291. return pct == 100
  1292. def getRemoteFiles(self):
  1293. pass
  1294. class RemoteNodeController(NodeController):
  1295. def __init__(self, env):
  1296. NodeController.__init__(self, env)
  1297. self._env = env
  1298. def getNick(self):
  1299. """Return the nickname for this node."""
  1300. return self._env['nick']
  1301. def getPid(self):
  1302. """Assuming that this node has its pidfile in ${dir}/pid, return
  1303. the pid of the running process, or None if there is no pid in the
  1304. file.
  1305. """
  1306. pidfile = os.path.join(self._env['dir'], 'pid')
  1307. if self._env['remote_hostname'] is None:
  1308. if not os.path.exists(pidfile):
  1309. return None
  1310. with open(pidfile, 'r') as f:
  1311. try:
  1312. return int(f.read())
  1313. except ValueError:
  1314. return None
  1315. else:
  1316. pid = ssh_read_file(pidfile, self._env['remote_hostname'])
  1317. if pid is None:
  1318. return None
  1319. try:
  1320. return int(pid)
  1321. except ValueError:
  1322. return None
  1323. def isRunning(self, pid=None):
  1324. """Return true iff this node is running. (If 'pid' is provided, we
  1325. assume that the pid provided is the one of this node. Otherwise
  1326. we call getPid().
  1327. """
  1328. if pid is None:
  1329. pid = self.getPid()
  1330. if pid is None:
  1331. return False
  1332. if self._env['remote_hostname'] is None:
  1333. try:
  1334. os.kill(pid, 0) # "kill 0" == "are you there?"
  1335. except OSError as e:
  1336. if e.errno == errno.ESRCH:
  1337. return False
  1338. raise
  1339. # okay, so the process exists. Say "True" for now.
  1340. # XXXX check if this is really tor!
  1341. return True
  1342. else:
  1343. return ssh_kill(pid, 0, self._env['remote_hostname'])
  1344. def check(self, listRunning=True, listNonRunning=False):
  1345. """See if this node is running, stopped, or crashed. If it's running
  1346. and listRunning is set, print a short statement. If it's
  1347. stopped and listNonRunning is set, then print a short statement.
  1348. If it's crashed, print a statement. Return True if the
  1349. node is running, false otherwise.
  1350. """
  1351. # XXX Split this into "check" and "print" parts.
  1352. pid = self.getPid()
  1353. nick = self._env['nick']
  1354. datadir = self._env['dir']
  1355. corefile = os.path.join(datadir, "core.%s" % pid)
  1356. tor_version = get_tor_version(self._env['tor'], remote_hostname=self._env['remote_hostname'])
  1357. hostname_help_str = ''
  1358. if self._env['remote_hostname'] is not None:
  1359. hostname_help_str = ' on \'{}\''.format(self._env['remote_hostname'])
  1360. if self._env['remote_hostname'] is None:
  1361. corefile_exists = os.path.exists(corefile)
  1362. else:
  1363. corefile_exists = ssh_file_exists(corefile, self._env['remote_hostname'])
  1364. if self.isRunning(pid):
  1365. if listRunning:
  1366. # PIDs are typically 65535 or less
  1367. print("{:12} is running with PID {:5}{}: {}"
  1368. .format(nick, pid, hostname_help_str, tor_version))
  1369. return True
  1370. elif corefile_exists:
  1371. if listNonRunning:
  1372. print("{:12} seems to have crashed{}, and left core file {}: {}"
  1373. .format(nick, hostname_help_str, corefile, tor_version))
  1374. return False
  1375. else:
  1376. if listNonRunning:
  1377. print("{:12} is stopped{}: {}"
  1378. .format(nick, hostname_help_str, tor_version))
  1379. return False
  1380. def hup(self):
  1381. """Send a SIGHUP to this node, if it's running."""
  1382. pid = self.getPid()
  1383. nick = self._env['nick']
  1384. if self.isRunning(pid):
  1385. print("Sending sighup to {}".format(nick))
  1386. if self._env['remote_hostname'] is None:
  1387. os.kill(pid, signal.SIGHUP)
  1388. else:
  1389. ssh_kill(pid, int(signal.SIGHUP), self._env['remote_hostname'])
  1390. return True
  1391. else:
  1392. print("{:12} is not running".format(nick))
  1393. return False
  1394. def start(self):
  1395. """Try to start this node; return True if we succeeded or it was
  1396. already running, False if we failed."""
  1397. if self.isRunning():
  1398. print("{:12} is already running".format(self._env['nick']))
  1399. return True
  1400. tor_path = self._env['tor']
  1401. torrc = self._getTorrcFname()
  1402. #
  1403. add_environ_vars = self._env['add_environ_vars']
  1404. if add_environ_vars is not None:
  1405. add_environ_vars = add_environ_vars.copy()
  1406. #
  1407. if self._env['google_cpu_profiler'] is True:
  1408. if add_environ_vars is None:
  1409. add_environ_vars = {}
  1410. add_environ_vars['CPUPROFILE'] = os.path.join(self._env['dir'], 'cpu-prof.out')
  1411. #
  1412. cmdline = []
  1413. if self._env['remote_hostname'] is not None:
  1414. cmdline.extend(['ssh', self._env['remote_hostname']])
  1415. if add_environ_vars is not None:
  1416. for x in add_environ_vars:
  1417. cmdline.extend(['{}={}'.format(x, add_environ_vars[x])])
  1418. #
  1419. #
  1420. #
  1421. if self._env['numa_settings'] is not None:
  1422. (numa_node, processors) = self._env['numa_settings']
  1423. cmdline.extend([
  1424. 'numactl',
  1425. '--membind={}'.format(numa_node),
  1426. '--physcpubind={}'.format(','.join(map(str, processors))),
  1427. ])
  1428. #
  1429. if self._env['valgrind_settings'] is not None:
  1430. cmdline.append('valgrind')
  1431. cmdline.extend(self._env['valgrind_settings'])
  1432. cmdline.append('--log-file={}'.format(self._env['valgrind_log']))
  1433. #
  1434. cmdline.extend([
  1435. tor_path,
  1436. "-f", torrc,
  1437. ])
  1438. if self._env['remote_hostname'] is not None:
  1439. print('Starting tor with: {}'.format(cmdline))
  1440. p = launch_process(cmdline, add_environ_vars=add_environ_vars)
  1441. if self.waitOnLaunch():
  1442. # this requires that RunAsDaemon is set
  1443. (stdouterr, empty_stderr) = p.communicate()
  1444. debug(stdouterr)
  1445. assert empty_stderr is None
  1446. else:
  1447. # this does not require RunAsDaemon to be set, but is slower.
  1448. #
  1449. # poll() only catches failures before the call itself
  1450. # so let's sleep a little first
  1451. # this does, of course, slow down process launch
  1452. # which can require an adjustment to the voting interval
  1453. #
  1454. # avoid writing a newline or space when polling
  1455. # so output comes out neatly
  1456. sys.stdout.write('.')
  1457. sys.stdout.flush()
  1458. time.sleep(self._env['poll_launch_time'])
  1459. p.poll()
  1460. if p.returncode is not None and p.returncode != 0:
  1461. if self._env['poll_launch_time'] is None:
  1462. print(("Couldn't launch {:12} command '{}': " +
  1463. "exit {}, output '{}'")
  1464. .format(self._env['nick'],
  1465. " ".join(cmdline),
  1466. p.returncode,
  1467. stdouterr))
  1468. else:
  1469. print(("Couldn't poll {:12} command '{}' " +
  1470. "after waiting {} seconds for launch: " +
  1471. "exit {}").format(self._env['nick'],
  1472. " ".join(cmdline),
  1473. self._env['poll_launch_time'],
  1474. p.returncode))
  1475. return False
  1476. return True
  1477. def stop(self, sig=signal.SIGINT):
  1478. """Try to stop this node by sending it the signal 'sig'."""
  1479. pid = self.getPid()
  1480. if not self.isRunning(pid):
  1481. print("{:12} is not running".format(self._env['nick']))
  1482. return
  1483. if self._env['remote_hostname'] is None:
  1484. os.kill(pid, sig)
  1485. else:
  1486. ssh_kill(pid, int(sig), self._env['remote_hostname'])
  1487. def cleanup_lockfile(self):
  1488. lf = self._env['lockfile']
  1489. if not self.isRunning() and os.path.exists(lf):
  1490. debug("Removing stale lock file for {} ..."
  1491. .format(self._env['nick']))
  1492. os.remove(lf)
  1493. def waitOnLaunch(self):
  1494. """Check whether we can wait() for the tor process to launch"""
  1495. # TODO: is this the best place for this code?
  1496. # RunAsDaemon default is 0
  1497. runAsDaemon = self._env['daemon']
  1498. '''
  1499. with open(self._getTorrcFname(), 'r') as f:
  1500. for line in f.readlines():
  1501. stline = line.strip()
  1502. # if the line isn't all whitespace or blank
  1503. if len(stline) > 0:
  1504. splline = stline.split()
  1505. # if the line has at least two tokens on it
  1506. if (len(splline) > 0 and
  1507. splline[0].lower() == "RunAsDaemon".lower() and
  1508. splline[1] == "1"):
  1509. # use the RunAsDaemon value from the torrc
  1510. # TODO: multiple values?
  1511. runAsDaemon = True
  1512. '''
  1513. if runAsDaemon:
  1514. # we must use wait() instead of poll()
  1515. self._env['poll_launch_time'] = None
  1516. return True
  1517. else:
  1518. # we must use poll() instead of wait()
  1519. if self._env['poll_launch_time'] is None:
  1520. self._env['poll_launch_time'] = \
  1521. self._env['poll_launch_time_default']
  1522. return False
  1523. def getLogfile(self, info=False):
  1524. """Return the expected path to the logfile for this instance."""
  1525. datadir = self._env['dir']
  1526. if info:
  1527. logname = "info.log"
  1528. else:
  1529. logname = "notice.log"
  1530. return os.path.join(datadir, logname)
  1531. def getLastBootstrapStatus(self):
  1532. """Look through the logs and return the last bootstrap message
  1533. received as a 3-tuple of percentage complete, keyword
  1534. (optional), and message.
  1535. """
  1536. logfname = self.getLogfile()
  1537. def find_bootstrap_messages(lines):
  1538. percent, keyword, message = -100, "no_message", "No bootstrap messages yet."
  1539. for line in lines:
  1540. m = re.search(r'Bootstrapped (\d+)%(?: \(([^\)]*)\))?: (.*)',
  1541. line)
  1542. if m:
  1543. percent, keyword, message = m.groups()
  1544. percent = int(percent)
  1545. return (percent, keyword, message)
  1546. if self._env['remote_hostname'] is None:
  1547. if not os.path.exists(logfname):
  1548. return (-200, "no_logfile", "There is no logfile yet.")
  1549. with open(logfname, 'r') as f:
  1550. return find_bootstrap_messages(f)
  1551. else:
  1552. messages = ssh_grep("Bootstrapped [0-9]+%", logfname, self._env['remote_hostname']).split('\n')
  1553. if messages is None:
  1554. return (-200, "no_logfile", "There is no logfile yet.")
  1555. return find_bootstrap_messages(messages)
  1556. def isBootstrapped(self):
  1557. """Return true iff the logfile says that this instance is
  1558. bootstrapped."""
  1559. pct, _, _ = self.getLastBootstrapStatus()
  1560. return pct == 100
  1561. def getRemoteFiles(self):
  1562. if self._env['remote_hostname'] is not None:
  1563. path = os.path.abspath(self._env['dir'])
  1564. ssh_rm_if_exists(os.path.join(path, 'control'), self._env['remote_hostname'])
  1565. scp_dir_backwards(path, self._env['remote_hostname'])
  1566. # XXX: document these options
  1567. DEFAULTS = {
  1568. 'authority': False,
  1569. 'bridgeauthority': False,
  1570. 'hasbridgeauth': False,
  1571. 'client': False,
  1572. 'relay': False,
  1573. 'bridge': False,
  1574. 'pt_bridge': False,
  1575. 'pt_transport' : "",
  1576. 'pt_extra' : "",
  1577. 'hs': False,
  1578. 'hs_directory': 'hidden_service',
  1579. 'hs-hostname': None,
  1580. 'daemon': True,
  1581. 'connlimit': 60,
  1582. 'net_base_dir': get_absolute_net_path(),
  1583. 'tor': os.environ.get('CHUTNEY_TOR', 'tor'),
  1584. 'tor-gencert': os.environ.get('CHUTNEY_TOR_GENCERT', None),
  1585. 'auth_cert_lifetime': 12,
  1586. 'ip': os.environ.get('CHUTNEY_LISTEN_ADDRESS', '127.0.0.1'),
  1587. # we default to ipv6_addr None to support IPv4-only systems
  1588. 'ipv6_addr': os.environ.get('CHUTNEY_LISTEN_ADDRESS_V6', None),
  1589. 'dirserver_flags': 'no-v2',
  1590. 'chutney_dir': get_absolute_chutney_path(),
  1591. 'torrc_fname': '${dir}/torrc',
  1592. 'orport_base': 5000,
  1593. 'dirport_base': 7000,
  1594. 'controlport_base': 8000,
  1595. 'socksport_base': 9000,
  1596. 'extorport_base' : 9500,
  1597. 'ptport_base' : 9900,
  1598. 'authorities': "AlternateDirAuthority bleargh bad torrc file!",
  1599. 'bridges': "Bridge bleargh bad torrc file!",
  1600. 'core': True,
  1601. # poll_launch_time: None means wait on launch (requires RunAsDaemon),
  1602. # otherwise, poll after that many seconds (can be fractional/decimal)
  1603. 'poll_launch_time': None,
  1604. # Used when poll_launch_time is None, but RunAsDaemon is not set
  1605. # Set low so that we don't interfere with the voting interval
  1606. 'poll_launch_time_default': 0.1,
  1607. # the number of bytes of random data we send on each connection
  1608. 'data_bytes': getenv_int('CHUTNEY_DATA_BYTES', 10 * 1024),
  1609. # the number of times each client will connect
  1610. 'connection_count': getenv_int('CHUTNEY_CONNECTIONS', 1),
  1611. # Do we want every client to connect to every HS, or one client
  1612. # to connect to each HS?
  1613. # (Clients choose an exit at random, so this doesn't apply to exits.)
  1614. 'hs_multi_client': getenv_int('CHUTNEY_HS_MULTI_CLIENT', 0),
  1615. # How long should verify (and similar commands) wait for a successful
  1616. # outcome? (seconds)
  1617. # We check BOOTSTRAP_TIME for compatibility with old versions of
  1618. # test-network.sh
  1619. 'bootstrap_time': getenv_int('CHUTNEY_BOOTSTRAP_TIME',
  1620. getenv_int('BOOTSTRAP_TIME',
  1621. 60)),
  1622. # the PID of the controlling script (for __OwningControllerProcess)
  1623. 'controlling_pid': getenv_int('CHUTNEY_CONTROLLING_PID', 0),
  1624. # a DNS config file (for ServerDNSResolvConfFile)
  1625. 'dns_conf': (os.environ.get('CHUTNEY_DNS_CONF', '/etc/resolv.conf')
  1626. if 'CHUTNEY_DNS_CONF' in os.environ
  1627. else None),
  1628. # The phase at which this instance needs to be
  1629. # configured/launched, if we're doing multiphase
  1630. # configuration/launch.
  1631. 'config_phase' : 1,
  1632. 'launch_phase' : 1,
  1633. 'CUR_CONFIG_PHASE': getenv_int('CHUTNEY_CONFIG_PHASE', 1),
  1634. 'CUR_LAUNCH_PHASE': getenv_int('CHUTNEY_LAUNCH_PHASE', 1),
  1635. # the Sandbox torrc option value
  1636. # defaults to 1 on Linux, and 0 otherwise
  1637. 'sandbox': int(getenv_bool('CHUTNEY_TOR_SANDBOX',
  1638. platform.system() == 'Linux')),
  1639. 'num_cpus': None,
  1640. 'numa_settings': None,
  1641. 'measureme_log_dir': '${dir}',
  1642. 'nick_base': 'test',
  1643. 'valgrind_settings': None,
  1644. 'add_environ_vars': None,
  1645. 'log_files': ['notice', 'info', 'debug'],
  1646. 'google_cpu_profiler': False,
  1647. 'remote_hostname': None,
  1648. 'num_additional_eventloops': None,
  1649. 'log_throughput': False,
  1650. }
  1651. class TorEnviron(chutney.Templating.Environ):
  1652. """Subclass of chutney.Templating.Environ to implement commonly-used
  1653. substitutions.
  1654. Environment fields provided:
  1655. orport, controlport, socksport, dirport: *Port torrc option
  1656. dir: DataDirectory torrc option
  1657. nick: Nickname torrc option
  1658. tor_gencert: name or path of the tor-gencert binary
  1659. auth_passphrase: obsoleted by CookieAuthentication
  1660. torrc_template_path: path to chutney torrc_templates directory
  1661. hs_hostname: the hostname of the key generated by a hidden service
  1662. owning_controller_process: the __OwningControllerProcess torrc line,
  1663. disabled if tor should continue after the script exits
  1664. server_dns_resolv_conf: the ServerDNSResolvConfFile torrc line,
  1665. disabled if tor should use the default DNS conf.
  1666. If the dns_conf file is missing, this option is also disabled:
  1667. otherwise, exits would not work due to tor bug #21900.
  1668. sandbox: Sets Sandbox to the value of CHUTNEY_TOR_SANDBOX.
  1669. The default is 1 on Linux, and 0 on other platforms.
  1670. Chutney users can disable the sandbox using:
  1671. export CHUTNEY_TOR_SANDBOX=0
  1672. if it doesn't work on their version of glibc.
  1673. Environment fields used:
  1674. nodenum: chutney's internal node number for the node
  1675. tag: a short text string that represents the type of node
  1676. orport_base, controlport_base, socksport_base, dirport_base: the
  1677. initial port numbers used by nodenum 0. Each additional node adds
  1678. 1 to the port numbers.
  1679. tor-gencert (note hyphen): name or path of the tor-gencert binary (if
  1680. present)
  1681. chutney_dir: directory of the chutney source code
  1682. tor: name or path of the tor binary
  1683. net_base_dir: path to the chutney net directory
  1684. hs_directory: name of the hidden service directory
  1685. nick: Nickname torrc option (debugging only)
  1686. hs-hostname (note hyphen): cached hidden service hostname value
  1687. controlling_pid: the PID of the controlling process. After this
  1688. process exits, the child tor processes will exit
  1689. dns_conf: the path to a DNS config file for Tor Exits. If this file
  1690. is empty or unreadable, Tor will try 127.0.0.1:53.
  1691. """
  1692. def __init__(self, parent=None, **kwargs):
  1693. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  1694. def _get_log_file_lines(self, my):
  1695. lines = []
  1696. for log_type in self['log_files']:
  1697. path = os.path.join(self['dir'], log_type) + '.log'
  1698. lines.append('Log {0} file {1}'.format(log_type, path))
  1699. return '\n'.join(lines)
  1700. def _get_orport(self, my):
  1701. return my['orport_base'] + my['nodenum']
  1702. def _get_controlport(self, my):
  1703. return my['controlport_base'] + my['nodenum']
  1704. def _get_socksport(self, my):
  1705. return my['socksport_base'] + my['nodenum']
  1706. def _get_dirport(self, my):
  1707. return my['dirport_base'] + my['nodenum']
  1708. def _get_extorport(self, my):
  1709. return my['extorport_base'] + my['nodenum']
  1710. def _get_ptport(self, my):
  1711. return my['ptport_base'] + my['nodenum']
  1712. def _get_dir(self, my):
  1713. return os.path.abspath(os.path.join(my['net_base_dir'],
  1714. "nodes",
  1715. "%03d%s" % (
  1716. my['nodenum'], my['tag'])))
  1717. def _get_nick(self, my):
  1718. return "%s%03d%s" % (my['nick_base'], my['nodenum'], my['tag'])
  1719. def _get_tor_gencert(self, my):
  1720. return my['tor-gencert'] or '{0}-gencert'.format(my['tor'])
  1721. def _get_auth_passphrase(self, my):
  1722. return self['nick'] # OMG TEH SECURE!
  1723. def _get_torrc_template_path(self, my):
  1724. return [os.path.join(my['chutney_dir'], 'torrc_templates')]
  1725. def _get_lockfile(self, my):
  1726. return os.path.join(self['dir'], 'lock')
  1727. def _get_valgrind_log(self, my):
  1728. return os.path.join(self['dir'], 'valgrind.log')
  1729. def _get_daemon_int(self, my):
  1730. return 1 if self['daemon'] else 0
  1731. # A hs generates its key on first run,
  1732. # so check for it at the last possible moment,
  1733. # but cache it in memory to avoid repeatedly reading the file
  1734. # XXXX - this is not like the other functions in this class,
  1735. # as it reads from a file created by the hidden service
  1736. def _get_hs_hostname(self, my):
  1737. if my['hs-hostname'] is None:
  1738. datadir = my['dir']
  1739. # a file containing a single line with the hs' .onion address
  1740. hs_hostname_file = os.path.join(datadir, my['hs_directory'],
  1741. 'hostname')
  1742. try:
  1743. with open(hs_hostname_file, 'r') as hostnamefp:
  1744. hostname = hostnamefp.read()
  1745. # the hostname file ends with a newline
  1746. hostname = hostname.strip()
  1747. my['hs-hostname'] = hostname
  1748. except IOError as e:
  1749. print("Error: hs %r error %d: %r opening hostname file '%r'" %
  1750. (my['nick'], e.errno, e.strerror, hs_hostname_file))
  1751. return my['hs-hostname']
  1752. def _get_num_cpus_line(self, my):
  1753. num_cpus = my['num_cpus']
  1754. num_cpus_line = 'NumCPUs {}'.format(num_cpus)
  1755. if num_cpus is None:
  1756. num_cpus_line = '#' + num_cpus_line
  1757. return num_cpus_line
  1758. def _get_num_additional_eventloops_line(self, my):
  1759. num = my['num_additional_eventloops']
  1760. line = 'NumAdditionalEventloops {}'.format(num)
  1761. if num is None:
  1762. line = '#' + line
  1763. return line
  1764. def _get_throughput_log_file_line(self, my):
  1765. line = 'ThroughputLogFile {}'.format(os.path.join(self['dir'],
  1766. 'relay_throughput.log'))
  1767. if not my['log_throughput']:
  1768. line = '#' + line
  1769. return line
  1770. def _get_owning_controller_process(self, my):
  1771. cpid = my['controlling_pid']
  1772. ocp_line = ('__OwningControllerProcess %d' % (cpid))
  1773. # if we want to leave the network running, or controlling_pid is 1
  1774. # (or invalid)
  1775. if cpid <= 1:
  1776. return '#' + ocp_line
  1777. else:
  1778. return ocp_line
  1779. # the default resolv.conf path is set at compile time
  1780. # there's no easy way to get it out of tor, so we use the typical value
  1781. DEFAULT_DNS_RESOLV_CONF = "/etc/resolv.conf"
  1782. # if we can't find the specified file, use this one as a substitute
  1783. OFFLINE_DNS_RESOLV_CONF = "/dev/null"
  1784. def _get_server_dns_resolv_conf(self, my):
  1785. if my['dns_conf'] == "":
  1786. # if the user asked for tor's default
  1787. return "#ServerDNSResolvConfFile using tor's compile-time default"
  1788. elif my['dns_conf'] is None:
  1789. # if there is no DNS conf file set
  1790. debug("CHUTNEY_DNS_CONF not specified, using '{}'."
  1791. .format(TorEnviron.DEFAULT_DNS_RESOLV_CONF))
  1792. dns_conf = TorEnviron.DEFAULT_DNS_RESOLV_CONF
  1793. else:
  1794. dns_conf = my['dns_conf']
  1795. dns_conf = os.path.abspath(dns_conf)
  1796. # work around Tor bug #21900, where exits fail when the DNS conf
  1797. # file does not exist, or is a broken symlink
  1798. # (os.path.exists returns False for broken symbolic links)
  1799. if not os.path.exists(dns_conf):
  1800. # Issue a warning so the user notices
  1801. print("CHUTNEY_DNS_CONF '{}' does not exist, using '{}'."
  1802. .format(dns_conf, TorEnviron.OFFLINE_DNS_RESOLV_CONF))
  1803. dns_conf = TorEnviron.OFFLINE_DNS_RESOLV_CONF
  1804. return "ServerDNSResolvConfFile %s" % (dns_conf)
  1805. KNOWN_REQUIREMENTS = {
  1806. "IPV6": chutney.Host.is_ipv6_supported
  1807. }
  1808. class Network(object):
  1809. """A network of Tor nodes, plus functions to manipulate them
  1810. """
  1811. def __init__(self, defaultEnviron):
  1812. self._nodes = []
  1813. self._requirements = []
  1814. self._dfltEnv = defaultEnviron
  1815. self._nextnodenum = 0
  1816. def _addNode(self, n):
  1817. n.setNodenum(self._nextnodenum)
  1818. self._nextnodenum += 1
  1819. self._nodes.append(n)
  1820. def _addRequirement(self, requirement):
  1821. requirement = requirement.upper()
  1822. if requirement not in KNOWN_REQUIREMENTS:
  1823. raise RuntimemeError(("Unrecognized requirement %r"%requirement))
  1824. self._requirements.append(requirement)
  1825. def move_aside_nodes_dir(self):
  1826. """Move aside the nodes directory, if it exists and is not a link.
  1827. Used for backwards-compatibility only: nodes is created as a link to
  1828. a new directory with a unique name in the current implementation.
  1829. """
  1830. nodesdir = get_absolute_nodes_path()
  1831. # only move the directory if it exists
  1832. if not os.path.exists(nodesdir):
  1833. return
  1834. # and if it's not a link
  1835. if os.path.islink(nodesdir):
  1836. return
  1837. # subtract 1 second to avoid collisions and get the correct ordering
  1838. newdir = get_new_absolute_nodes_path(time.time() - 1)
  1839. print("NOTE: renaming %r to %r" % (nodesdir, newdir))
  1840. os.rename(nodesdir, newdir)
  1841. def create_new_nodes_dir(self):
  1842. """Create a new directory with a unique name, and symlink it to nodes
  1843. """
  1844. # for backwards compatibility, move aside the old nodes directory
  1845. # (if it's not a link)
  1846. self.move_aside_nodes_dir()
  1847. # the unique directory we'll create
  1848. newnodesdir = get_new_absolute_nodes_path()
  1849. # the canonical name we'll link it to
  1850. nodeslink = get_absolute_nodes_path()
  1851. # this path should be unique and should not exist
  1852. if os.path.exists(newnodesdir):
  1853. raise RuntimeError(
  1854. 'get_new_absolute_nodes_path returned a path that exists')
  1855. # if this path exists, it must be a link
  1856. if os.path.exists(nodeslink) and not os.path.islink(nodeslink):
  1857. raise RuntimeError(
  1858. 'get_absolute_nodes_path returned a path that exists and is not a link')
  1859. # create the new, uniquely named directory, and link it to nodes
  1860. print("NOTE: creating %r, linking to %r" % (newnodesdir, nodeslink))
  1861. # this gets created with mode 0700, that's probably ok
  1862. mkdir_p(newnodesdir)
  1863. remote_hostnames = list(set([x._env['remote_hostname'] for x in self._nodes if x._env['remote_hostname'] is not None]))
  1864. if len(remote_hostnames) != 0:
  1865. for x in remote_hostnames:
  1866. ssh_mkdir_p(newnodesdir, x)
  1867. try:
  1868. os.unlink(nodeslink)
  1869. except OSError as e:
  1870. # it's ok if the link doesn't exist, we're just about to make it
  1871. if e.errno == errno.ENOENT:
  1872. pass
  1873. else:
  1874. raise
  1875. if len(remote_hostnames) != 0:
  1876. for x in remote_hostnames:
  1877. ssh_rm_if_exists(nodeslink, x)
  1878. os.symlink(newnodesdir, nodeslink)
  1879. if len(remote_hostnames) != 0:
  1880. for x in remote_hostnames:
  1881. ssh_symlink(newnodesdir, nodeslink, x)
  1882. def _checkConfig(self):
  1883. for n in self._nodes:
  1884. n.getBuilder().checkConfig(self)
  1885. def supported(self):
  1886. """Check whether this network is supported by the set of binaries
  1887. and host information we have.
  1888. """
  1889. missing_any = False
  1890. for r in self._requirements:
  1891. if not KNOWN_REQUIREMENTS[r]():
  1892. print(("Can't run this network: %s is missing."))
  1893. missing_any = True
  1894. for n in self._nodes:
  1895. if not n.getBuilder().isSupported(self):
  1896. missing_any = False
  1897. if missing_any:
  1898. sys.exit(1)
  1899. def configure(self):
  1900. phase = self._dfltEnv['CUR_CONFIG_PHASE']
  1901. if phase == 1:
  1902. self.create_new_nodes_dir()
  1903. network = self
  1904. altauthlines = []
  1905. bridgelines = []
  1906. all_builders = [ n.getBuilder() for n in self._nodes ]
  1907. builders = [ b for b in all_builders
  1908. if b._env['config_phase'] == phase ]
  1909. self._checkConfig()
  1910. # XXX don't change node names or types or count if anything is
  1911. # XXX running!
  1912. for b in all_builders:
  1913. b.preConfig(network)
  1914. altauthlines.append(b._getAltAuthLines(
  1915. self._dfltEnv['hasbridgeauth']))
  1916. bridgelines.append(b._getBridgeLines())
  1917. self._dfltEnv['authorities'] = "".join(altauthlines)
  1918. self._dfltEnv['bridges'] = "".join(bridgelines)
  1919. for b in builders:
  1920. b.config(network)
  1921. for b in builders:
  1922. b.postConfig(network)
  1923. def status(self):
  1924. statuses = [n.getController().check(listNonRunning=True)
  1925. for n in self._nodes]
  1926. n_ok = len([x for x in statuses if x])
  1927. print("%d/%d nodes are running" % (n_ok, len(self._nodes)))
  1928. return n_ok == len(self._nodes)
  1929. def restart(self):
  1930. self.stop()
  1931. self.start()
  1932. def start(self):
  1933. # format polling correctly - avoid printing a newline
  1934. sys.stdout.write("Starting nodes")
  1935. sys.stdout.flush()
  1936. rv = all([n.getController().start() for n in self._nodes
  1937. if n._env['launch_phase'] ==
  1938. self._dfltEnv['CUR_LAUNCH_PHASE']])
  1939. # now print a newline unconditionally - this stops poll()ing
  1940. # output from being squashed together, at the cost of a blank
  1941. # line in wait()ing output
  1942. print("")
  1943. return rv
  1944. def hup(self):
  1945. print("Sending SIGHUP to nodes")
  1946. return all([n.getController().hup() for n in self._nodes])
  1947. def wait_for_bootstrap(self):
  1948. print("Waiting for nodes to bootstrap...")
  1949. limit = getenv_int("CHUTNEY_START_TIME", 60)
  1950. delay = 0.5
  1951. controllers = [n.getController() for n in self._nodes]
  1952. elapsed = 0.0
  1953. most_recent_status = [ None ] * len(controllers)
  1954. while True:
  1955. all_bootstrapped = True
  1956. most_recent_status = [ ]
  1957. for c in controllers:
  1958. pct, kwd, msg = c.getLastBootstrapStatus()
  1959. most_recent_status.append((pct, kwd, msg))
  1960. if pct != 100:
  1961. all_bootstrapped = False
  1962. if all_bootstrapped:
  1963. print("Everything bootstrapped after %s sec"%elapsed)
  1964. return True
  1965. if elapsed >= limit:
  1966. break
  1967. time.sleep(delay)
  1968. elapsed += delay
  1969. print("Bootstrap failed. Node status:")
  1970. for c, status in zip(controllers,most_recent_status):
  1971. c.check(listRunning=False, listNonRunning=True)
  1972. print("{}: {}".format(c.getNick(), status))
  1973. return False
  1974. def stop(self):
  1975. controllers = [n.getController() for n in self._nodes]
  1976. for sig, desc in [(signal.SIGINT, "SIGINT"),
  1977. (signal.SIGINT, "another SIGINT"),
  1978. (signal.SIGKILL, "SIGKILL")]:
  1979. print("Sending %s to nodes" % desc)
  1980. for c in controllers:
  1981. if c.isRunning():
  1982. c.stop(sig=sig)
  1983. print("Waiting for nodes to finish.")
  1984. wrote_dot = False
  1985. for n in range(15):
  1986. time.sleep(1)
  1987. if all(not c.isRunning() for c in controllers):
  1988. # make the output clearer by adding a newline
  1989. if wrote_dot:
  1990. sys.stdout.write("\n")
  1991. sys.stdout.flush()
  1992. # check for stale lock file when Tor crashes
  1993. for c in controllers:
  1994. c.cleanup_lockfile()
  1995. return
  1996. sys.stdout.write(".")
  1997. wrote_dot = True
  1998. sys.stdout.flush()
  1999. for c in controllers:
  2000. c.check(listNonRunning=False)
  2001. # make the output clearer by adding a newline
  2002. if wrote_dot:
  2003. sys.stdout.write("\n")
  2004. sys.stdout.flush()
  2005. def get_remote_files(self):
  2006. controllers = [n.getController() for n in self._nodes]
  2007. for c in controllers:
  2008. c.getRemoteFiles()
  2009. def Require(feature):
  2010. network = _THE_NETWORK
  2011. network._addRequirement(feature)
  2012. def ConfigureNodes(nodelist):
  2013. network = _THE_NETWORK
  2014. for n in nodelist:
  2015. network._addNode(n)
  2016. if n._env['bridgeauthority']:
  2017. network._dfltEnv['hasbridgeauth'] = True
  2018. def getTests():
  2019. tests = []
  2020. chutney_path = get_absolute_chutney_path()
  2021. if len(chutney_path) > 0 and chutney_path[-1] != '/':
  2022. chutney_path += "/"
  2023. for x in os.listdir(chutney_path + "scripts/chutney_tests/"):
  2024. if not x.startswith("_") and os.path.splitext(x)[1] == ".py":
  2025. tests.append(os.path.splitext(x)[0])
  2026. return tests
  2027. def usage(network):
  2028. return "\n".join(["Usage: chutney {command/test} {networkfile}",
  2029. "Known commands are: %s" % (
  2030. " ".join(x for x in dir(network)
  2031. if not x.startswith("_"))),
  2032. "Known tests are: %s" % (
  2033. " ".join(getTests()))
  2034. ])
  2035. def exit_on_error(err_msg):
  2036. print("Error: {0}\n".format(err_msg))
  2037. print(usage(_THE_NETWORK))
  2038. sys.exit(1)
  2039. def runConfigFile(verb, data):
  2040. _GLOBALS = dict(_BASE_ENVIRON=_BASE_ENVIRON,
  2041. Node=Node,
  2042. Require=Require,
  2043. ConfigureNodes=ConfigureNodes,
  2044. _THE_NETWORK=_THE_NETWORK,
  2045. torrc_option_warn_count=0,
  2046. TORRC_OPTION_WARN_LIMIT=10)
  2047. exec(data, _GLOBALS)
  2048. network = _GLOBALS['_THE_NETWORK']
  2049. # let's check if the verb is a valid test and run it
  2050. if verb in getTests():
  2051. test_module = importlib.import_module("chutney_tests.{}".format(verb))
  2052. try:
  2053. run_test = test_module.run_test
  2054. except AttributeError as e:
  2055. print("Error running test {!r}: {}".format(verb, e))
  2056. return False
  2057. return run_test(network)
  2058. # tell the user we don't know what their verb meant
  2059. if not hasattr(network, verb):
  2060. print(usage(network))
  2061. print("Error: I don't know how to %s." % verb)
  2062. return
  2063. return getattr(network, verb)()
  2064. def parseArgs():
  2065. if len(sys.argv) < 3:
  2066. exit_on_error("Not enough arguments given.")
  2067. if not os.path.isfile(sys.argv[2]):
  2068. exit_on_error("Cannot find networkfile: {0}.".format(sys.argv[2]))
  2069. return {'network_cfg': sys.argv[2], 'action': sys.argv[1]}
  2070. def main():
  2071. global _BASE_ENVIRON
  2072. global _THE_NETWORK
  2073. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  2074. _THE_NETWORK = Network(_BASE_ENVIRON)
  2075. args = parseArgs()
  2076. f = open(args['network_cfg'])
  2077. result = runConfigFile(args['action'], f.read())
  2078. if result is False:
  2079. return -1
  2080. return 0
  2081. if __name__ == '__main__':
  2082. sys.exit(main())