TorNet.py 12 KB

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