TorNet.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2011 Nick Mathewson, Michael Stone
  4. #
  5. # You may do anything with this work that copyright law would normally
  6. # restrict, so long as you retain the above notice(s) and this license
  7. # in all redistributed copies and derived works. There is no warranty.
  8. from __future__ import with_statement
  9. import os
  10. import signal
  11. import subprocess
  12. import sys
  13. import re
  14. import errno
  15. import time
  16. import chutney.Templating
  17. def mkdir_p(d):
  18. try:
  19. os.makedirs(d)
  20. except OSError, e:
  21. if e.errno == errno.EEXIST:
  22. return
  23. raise
  24. class Node(object):
  25. ########
  26. # Users are expected to call these:
  27. def __init__(self, parent=None, **kwargs):
  28. self._parent = parent
  29. self.env = self._createEnviron(parent, kwargs)
  30. def getN(self, N):
  31. return [ Node(self) for _ in xrange(N) ]
  32. def specialize(self, **kwargs):
  33. return Node(parent=self, **kwargs)
  34. def expand(self, pat, includePath=(".",)):
  35. return chutney.Templating.Template(pat, includePath).format(self.env)
  36. #######
  37. # Users are NOT expected to call these:
  38. def _getTorrcFname(self):
  39. return self.expand("${torrc_fname}")
  40. def _createTorrcFile(self, checkOnly=False):
  41. fn_out = self._getTorrcFname()
  42. torrc_template = self._getTorrcTemplate()
  43. output = torrc_template.format(self.env)
  44. if checkOnly:
  45. return
  46. with open(fn_out, 'w') as f:
  47. f.write(output)
  48. def _getTorrcTemplate(self):
  49. template_path = self.env['torrc_template_path']
  50. return chutney.Templating.Template("$${include:$torrc}",
  51. includePath=template_path)
  52. def _getFreeVars(self):
  53. template = self._getTorrcTemplate()
  54. return template.freevars(self.env)
  55. def _createEnviron(self, parent, argdict):
  56. if parent:
  57. parentenv = parent.env
  58. else:
  59. parentenv = self._getDefaultEnviron()
  60. return TorEnviron(parentenv, **argdict)
  61. def _getDefaultEnviron(self):
  62. return _BASE_ENVIRON
  63. def _checkConfig(self, net):
  64. self._createTorrcFile(checkOnly=True)
  65. def _preConfig(self, net):
  66. self._makeDataDir()
  67. if self.env['authority']:
  68. self._genAuthorityKey()
  69. if self.env['relay']:
  70. self._genRouterKey()
  71. def _config(self, net):
  72. self._createTorrcFile()
  73. #self._createScripts()
  74. def _postConfig(self, net):
  75. #self.net.addNode(self)
  76. pass
  77. def _setnodenum(self, num):
  78. self.env['nodenum'] = num
  79. def _makeDataDir(self):
  80. datadir = self.env['dir']
  81. mkdir_p(os.path.join(datadir, 'keys'))
  82. def _genAuthorityKey(self):
  83. datadir = self.env['dir']
  84. tor_gencert = self.env['tor_gencert']
  85. lifetime = self.env['auth_cert_lifetime']
  86. idfile = os.path.join(datadir,'keys',"authority_identity_key")
  87. skfile = os.path.join(datadir,'keys',"authority_signing_key")
  88. certfile = os.path.join(datadir,'keys',"authority_certificate")
  89. addr = self.expand("${ip}:${dirport}")
  90. passphrase = self.env['auth_passphrase']
  91. if all(os.path.exists(f) for f in [idfile, skfile, certfile]):
  92. return
  93. cmdline = [
  94. tor_gencert,
  95. '--create-identity-key',
  96. '--passphrase-fd', '0',
  97. '-i', idfile,
  98. '-s', skfile,
  99. '-c', certfile,
  100. '-m', str(lifetime),
  101. '-a', addr]
  102. print "Creating identity key %s for %s with %s"%(
  103. idfile,self.env['nick']," ".join(cmdline))
  104. p = subprocess.Popen(cmdline, stdin=subprocess.PIPE)
  105. p.communicate(passphrase+"\n")
  106. assert p.returncode == 0 #XXXX BAD!
  107. def _genRouterKey(self):
  108. datadir = self.env['dir']
  109. tor = self.env['tor']
  110. idfile = os.path.join(datadir,'keys',"identity_key")
  111. cmdline = [
  112. tor,
  113. "--quiet",
  114. "--list-fingerprint",
  115. "--orport", "1",
  116. "--dirserver",
  117. "xyzzy 127.0.0.1:1 ffffffffffffffffffffffffffffffffffffffff",
  118. "--datadirectory", datadir ]
  119. p = subprocess.Popen(cmdline, stdout=subprocess.PIPE)
  120. stdout, stderr = p.communicate()
  121. fingerprint = "".join(stdout.split()[1:])
  122. assert re.match(r'^[A-F0-9]{40}$', fingerprint)
  123. self.env['fingerprint'] = fingerprint
  124. def _getDirServerLine(self):
  125. if not self.env['authority']:
  126. return ""
  127. datadir = self.env['dir']
  128. certfile = os.path.join(datadir,'keys',"authority_certificate")
  129. v3id = None
  130. with open(certfile, 'r') as f:
  131. for line in f:
  132. if line.startswith("fingerprint"):
  133. v3id = line.split()[1].strip()
  134. break
  135. assert v3id is not None
  136. return "DirServer %s v3ident=%s orport=%s %s %s:%s %s\n" %(
  137. self.env['nick'], v3id, self.env['orport'],
  138. self.env['dirserver_flags'], self.env['ip'], self.env['dirport'],
  139. self.env['fingerprint'])
  140. ##### Controlling a node. This should probably get split into its
  141. # own class. XXXX
  142. def getPid(self):
  143. pidfile = os.path.join(self.env['dir'], 'pid')
  144. if not os.path.exists(pidfile):
  145. return None
  146. with open(pidfile, 'r') as f:
  147. return int(f.read())
  148. def isRunning(self, pid=None):
  149. if pid is None:
  150. pid = self.getPid()
  151. if pid is None:
  152. return False
  153. try:
  154. os.kill(pid, 0) # "kill 0" == "are you there?"
  155. except OSError, e:
  156. if e.errno == errno.ESRCH:
  157. return False
  158. raise
  159. # okay, so the process exists. Say "True" for now.
  160. # XXXX check if this is really tor!
  161. return True
  162. def check(self, listRunning=True, listNonRunning=False):
  163. pid = self.getPid()
  164. running = self.isRunning(pid)
  165. nick = self.env['nick']
  166. dir = self.env['dir']
  167. if running:
  168. if listRunning:
  169. print "%s is running with PID %s"%(nick,pid)
  170. return True
  171. elif os.path.exists(os.path.join(dir, "core.%s"%pid)):
  172. if listNonRunning:
  173. print "%s seems to have crashed, and left core file core.%s"%(
  174. nick,pid)
  175. return False
  176. else:
  177. if listNonRunning:
  178. print "%s is stopped"%nick
  179. return False
  180. def hup(self):
  181. pid = self.getPid()
  182. running = self.isRunning()
  183. nick = self.env['nick']
  184. if self.isRunning():
  185. print "Sending sighup to %s"%nick
  186. os.kill(pid, signal.SIGHUP)
  187. return True
  188. else:
  189. print "%s is not running"%nick
  190. return False
  191. def start(self):
  192. if self.isRunning():
  193. print "%s is already running"%self.env['nick']
  194. return
  195. torrc = self._getTorrcFname()
  196. cmdline = [
  197. self.env['tor'],
  198. "--quiet",
  199. "-f", torrc,
  200. ]
  201. p = subprocess.Popen(cmdline)
  202. # XXXX this requires that RunAsDaemon is set.
  203. p.wait()
  204. if p.returncode != 0:
  205. print "Couldn't launch %s (%s): %s"%(self.env['nick'],
  206. " ".join(cmdline),
  207. p.returncode)
  208. return False
  209. return True
  210. def stop(self, sig=signal.SIGINT):
  211. pid = self.getPid()
  212. if not self.isRunning(pid):
  213. print "%s is not running"%self.env['nick']
  214. return
  215. os.kill(pid, sig)
  216. DEFAULTS = {
  217. 'authority' : False,
  218. 'relay' : False,
  219. 'connlimit' : 60,
  220. 'net_base_dir' : 'net',
  221. 'tor' : 'tor',
  222. 'auth_cert_lifetime' : 12,
  223. 'ip' : '127.0.0.1',
  224. 'dirserver_flags' : 'no-v2',
  225. 'privnet_dir' : '.',
  226. 'torrc_fname' : '${dir}/torrc',
  227. 'orport_base' : 6000,
  228. 'dirport_base' : 7000,
  229. 'controlport_base' : 8000,
  230. 'socksport_base' : 9000,
  231. 'dirservers' : "Dirserver bleargh bad torrc file!",
  232. 'core' : True,
  233. }
  234. class TorEnviron(chutney.Templating.Environ):
  235. def __init__(self,parent=None,**kwargs):
  236. chutney.Templating.Environ.__init__(self, parent=parent, **kwargs)
  237. def _get_orport(self, my):
  238. return my['orport_base']+my['nodenum']
  239. def _get_controlport(self, my):
  240. return my['controlport_base']+my['nodenum']
  241. def _get_socksport(self, my):
  242. return my['socksport_base']+my['nodenum']
  243. def _get_dirport(self, my):
  244. return my['dirport_base']+my['nodenum']
  245. def _get_dir(self, my):
  246. return os.path.abspath(os.path.join(my['net_base_dir'],
  247. "nodes",
  248. "%03d%s"%(my['nodenum'], my['tag'])))
  249. def _get_nick(self, my):
  250. return "test%03d%s"%(my['nodenum'], my['tag'])
  251. def _get_tor_gencert(self, my):
  252. return my['tor']+"-gencert"
  253. def _get_auth_passphrase(self, my):
  254. return self['nick'] # OMG TEH SECURE!
  255. def _get_torrc_template_path(self, my):
  256. return [ os.path.join(my['privnet_dir'], 'torrc_templates') ]
  257. class Network(object):
  258. def __init__(self,defaultEnviron):
  259. self._nodes = []
  260. self._dfltEnv = defaultEnviron
  261. self._nextnodenum = 0
  262. def _addNode(self, n):
  263. n._setnodenum(self._nextnodenum)
  264. self._nextnodenum += 1
  265. self._nodes.append(n)
  266. def _checkConfig(self):
  267. for n in self._nodes:
  268. n._checkConfig(self)
  269. def configure(self):
  270. network = self
  271. dirserverlines = []
  272. self._checkConfig()
  273. # XXX don't change node names or types or count if anything is
  274. # XXX running!
  275. for n in self._nodes:
  276. n._preConfig(network)
  277. dirserverlines.append(n._getDirServerLine())
  278. self._dfltEnv['dirservers'] = "".join(dirserverlines)
  279. for n in self._nodes:
  280. n._config(network)
  281. for n in self._nodes:
  282. n._postConfig(network)
  283. def status(self):
  284. statuses = [n.check() for n in self._nodes]
  285. n_ok = len([x for x in statuses if x])
  286. print "%d/%d nodes are running"%(n_ok,len(self._nodes))
  287. def restart(self):
  288. self.stop()
  289. self.start()
  290. def start(self):
  291. print "Starting nodes"
  292. return all([n.start() for n in self._nodes])
  293. def hup(self):
  294. print "Sending SIGHUP to nodes"
  295. return all([n.hup() for n in self._nodes])
  296. def stop(self):
  297. for sig, desc in [(signal.SIGINT, "SIGINT"),
  298. (signal.SIGINT, "another SIGINT"),
  299. (signal.SIGKILL, "SIGKILL")]:
  300. print "Sending %s to nodes"%desc
  301. for n in self._nodes:
  302. if n.isRunning():
  303. n.stop(sig=sig)
  304. print "Waiting for nodes to finish."
  305. for n in xrange(15):
  306. time.sleep(1)
  307. if all(not n.isRunning() for n in self._nodes):
  308. return
  309. sys.stdout.write(".")
  310. sys.stdout.flush()
  311. for n in self._nodes:
  312. n.check(listNonRunning=False)
  313. def ConfigureNodes(nodelist):
  314. network = _THE_NETWORK
  315. for n in nodelist:
  316. network._addNode(n)
  317. def runConfigFile(verb, f):
  318. global _BASE_ENVIRON
  319. global _THE_NETWORK
  320. _BASE_ENVIRON = TorEnviron(chutney.Templating.Environ(**DEFAULTS))
  321. _THE_NETWORK = Network(_BASE_ENVIRON)
  322. _GLOBALS = dict(_BASE_ENVIRON= _BASE_ENVIRON,
  323. Node=Node,
  324. ConfigureNodes=ConfigureNodes,
  325. _THE_NETWORK=_THE_NETWORK)
  326. exec f in _GLOBALS
  327. network = _GLOBALS['_THE_NETWORK']
  328. if not hasattr(network, verb):
  329. print "I don't know how to %s. Known commands are: %s" % (
  330. verb, " ".join(x for x in dir(network) if not x.startswith("_")))
  331. return
  332. getattr(network,verb)()
  333. if __name__ == '__main__':
  334. if len(sys.argv) < 3:
  335. print "Syntax: chutney {command} {networkfile}"
  336. sys.exit(1)
  337. f = open(sys.argv[2])
  338. runConfigFile(sys.argv[1], f)