Traffic.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2013 The Tor Project
  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. # Do select/read/write for binding to a port, connecting to it and
  9. # write, read what's written and verify it. You can connect over a
  10. # SOCKS proxy (like Tor).
  11. #
  12. # You can create a TrafficTester and give it an IP address/host and
  13. # port to bind to. If a Source is created and added to the
  14. # TrafficTester, it will connect to the address/port it was given at
  15. # instantiation and send its data. A Source can be configured to
  16. # connect over a SOCKS proxy. When everything is set up, you can
  17. # invoke TrafficTester.run() to start running. The TrafficTester will
  18. # accept the incoming connection and read from it, verifying the data.
  19. #
  20. # For example code, see main() below.
  21. from __future__ import print_function
  22. import sys
  23. import socket
  24. import struct
  25. import errno
  26. import time
  27. import os
  28. import asyncore
  29. import asynchat
  30. from chutney.Debug import debug_flag, debug
  31. def addr_to_family(addr):
  32. for family in [socket.AF_INET, socket.AF_INET6]:
  33. try:
  34. socket.inet_pton(family, addr)
  35. return family
  36. except (socket.error, OSError):
  37. pass
  38. return socket.AF_INET
  39. def socks_cmd(addr_port):
  40. """
  41. Return a SOCKS command for connecting to addr_port.
  42. SOCKSv4: https://en.wikipedia.org/wiki/SOCKS#Protocol
  43. SOCKSv5: RFC1928, RFC1929
  44. """
  45. ver = 4 # Only SOCKSv4 for now.
  46. cmd = 1 # Stream connection.
  47. user = b'\x00'
  48. dnsname = ''
  49. host, port = addr_port
  50. try:
  51. addr = socket.inet_aton(host)
  52. except socket.error:
  53. addr = b'\x00\x00\x00\x01'
  54. dnsname = '%s\x00' % host
  55. debug("Socks 4a request to %s:%d" % (host, port))
  56. if type(dnsname) != type(b""):
  57. dnsname = dnsname.encode("ascii")
  58. return struct.pack('!BBH', ver, cmd, port) + addr + user + dnsname
  59. class TestSuite(object):
  60. """Keep a tab on how many tests are pending, how many have failed
  61. and how many have succeeded."""
  62. def __init__(self):
  63. self.tests = {}
  64. self.not_done = 0
  65. self.successes = 0
  66. self.failures = 0
  67. def add(self, name):
  68. if name not in self.tests:
  69. debug("Registering %s"%name)
  70. self.not_done += 1
  71. self.tests[name] = 'not done'
  72. def success(self, name):
  73. if self.tests[name] == 'not done':
  74. debug("Succeeded %s"%name)
  75. self.tests[name] = 'success'
  76. self.not_done -= 1
  77. self.successes += 1
  78. def failure(self, name):
  79. if self.tests[name] == 'not done':
  80. debug("Failed %s"%name)
  81. self.tests[name] = 'failure'
  82. self.not_done -= 1
  83. self.failures += 1
  84. def failure_count(self):
  85. return self.failures
  86. def all_done(self):
  87. return self.not_done == 0
  88. def status(self):
  89. return('%s: %d/%d/%d' % (self.tests, self.not_done, self.successes,
  90. self.failures))
  91. class Listener(asyncore.dispatcher):
  92. "A TCP listener, binding, listening and accepting new connections."
  93. def __init__(self, tt, endpoint):
  94. asyncore.dispatcher.__init__(self)
  95. self.create_socket(addr_to_family(endpoint[0]), socket.SOCK_STREAM)
  96. self.set_reuse_addr()
  97. self.bind(endpoint)
  98. self.listen(0)
  99. self.tt = tt
  100. def handle_accept(self):
  101. # deprecated in python 3.2
  102. pair = self.accept()
  103. if pair is not None:
  104. newsock, endpoint = pair
  105. debug("new client from %s:%s (fd=%d)" %
  106. (endpoint[0], endpoint[1], newsock.fileno()))
  107. self.tt.add_responder(newsock)
  108. def fileno(self):
  109. return self.socket.fileno()
  110. class DataSource(object):
  111. """A data source generates some number of bytes of data, and then
  112. returns None.
  113. For convenience, it conforms to the 'producer' api.
  114. """
  115. def __init__(self, data, repetitions=1):
  116. self.data = data
  117. self.repetitions = repetitions
  118. self.sent_any = False
  119. def copy(self):
  120. assert not self.sent_any
  121. return DataSource(self.data, self.repetitions)
  122. def more(self):
  123. self.sent_any = True
  124. if self.repetitions > 0:
  125. self.repetitions -= 1
  126. return self.data
  127. return None
  128. class DataChecker(object):
  129. """A data checker verifies its input against bytes in a stream."""
  130. def __init__(self, source):
  131. self.source = source
  132. self.pending = b""
  133. self.succeeded = False
  134. self.failed = False
  135. def consume(self, inp):
  136. if self.failed:
  137. return
  138. if self.succeeded and len(inp):
  139. self.succeeded = False
  140. self.failed = True
  141. return
  142. while len(inp):
  143. n = min(len(inp), len(self.pending))
  144. if inp[:n] != self.pending[:n]:
  145. self.failed = True
  146. return
  147. inp = inp[n:]
  148. self.pending = self.pending[n:]
  149. if not self.pending:
  150. self.pending = self.source.more()
  151. if self.pending is None:
  152. if len(inp):
  153. self.failed = True
  154. else:
  155. self.succeeded = True
  156. return
  157. class Sink(asynchat.async_chat):
  158. "A data sink, reading from its peer and verifying the data."
  159. def __init__(self, sock, tt):
  160. asynchat.async_chat.__init__(self, sock)
  161. self.set_terminator(None)
  162. self.tt = tt
  163. self.data_checker = DataChecker(tt.data_source.copy())
  164. self.testname = "recv-data%s"%id(self)
  165. def get_test_names(self):
  166. return [ self.testname ]
  167. def collect_incoming_data(self, inp):
  168. # shortcut read when we don't ever expect any data
  169. debug("successfully received (bytes=%d)" % len(inp))
  170. self.data_checker.consume(inp)
  171. if self.data_checker.succeeded:
  172. debug("successful verification")
  173. self.close()
  174. self.tt.success(self.testname)
  175. elif self.data_checker.failed:
  176. debug("receive comparison failed")
  177. self.tt.failure(self.testname)
  178. self.close()
  179. def fileno(self):
  180. return self.socket.fileno()
  181. class CloseSourceProducer:
  182. """Helper: when this producer is returned, a source is successful."""
  183. def __init__(self, source):
  184. self.source = source
  185. def more(self):
  186. self.source.sent_ok()
  187. return b""
  188. class Source(asynchat.async_chat):
  189. """A data source, connecting to a TCP server, optionally over a
  190. SOCKS proxy, sending data."""
  191. CONNECTING = 1
  192. CONNECTING_THROUGH_PROXY = 2
  193. CONNECTED = 5
  194. def __init__(self, tt, server, proxy=None):
  195. asynchat.async_chat.__init__(self)
  196. self.data_source = tt.data_source.copy()
  197. self.inbuf = b''
  198. self.proxy = proxy
  199. self.server = server
  200. self.tt = tt
  201. self.testname = "send-data%s"%id(self)
  202. self.set_terminator(None)
  203. dest = (self.proxy or self.server)
  204. self.create_socket(addr_to_family(dest[0]), socket.SOCK_STREAM)
  205. debug("socket %d connecting to %r..."%(self.fileno(),dest))
  206. self.state = self.CONNECTING
  207. self.connect(dest)
  208. def get_test_names(self):
  209. return [ self.testname ]
  210. def sent_ok(self):
  211. self.tt.success(self.testname)
  212. def handle_connect(self):
  213. if self.proxy:
  214. self.state = self.CONNECTING_THROUGH_PROXY
  215. self.push(socks_cmd(self.server))
  216. else:
  217. self.state = self.CONNECTED
  218. self.push_output()
  219. def collect_incoming_data(self, data):
  220. self.inbuf += data
  221. if self.state == self.CONNECTING_THROUGH_PROXY:
  222. if len(self.inbuf) >= 8:
  223. if self.inbuf[:2] == b'\x00\x5a':
  224. debug("proxy handshake successful (fd=%d)" % self.fileno())
  225. self.state = self.CONNECTED
  226. debug("successfully connected (fd=%d)" % self.fileno())
  227. self.inbuf = self.inbuf[8:]
  228. self.push_output()
  229. else:
  230. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  231. (ord(self.inbuf[1]), self.fileno()))
  232. self.state = self.NOT_CONNECTED
  233. self.close()
  234. def push_output(self):
  235. self.push_with_producer(self.data_source)
  236. self.push_with_producer(CloseSourceProducer(self))
  237. self.close_when_done()
  238. def fileno(self):
  239. return self.socket.fileno()
  240. class TrafficTester(object):
  241. """
  242. Hang on select.select() and dispatch to Sources and Sinks.
  243. Time out after self.timeout seconds.
  244. Keep track of successful and failed data verification using a
  245. TestSuite.
  246. Return True if all tests succeed, else False.
  247. """
  248. def __init__(self,
  249. endpoint,
  250. data=b"",
  251. timeout=3,
  252. repetitions=1,
  253. dot_repetitions=0):
  254. self.listener = Listener(self, endpoint)
  255. self.pending_close = []
  256. self.timeout = timeout
  257. self.tests = TestSuite()
  258. self.data_source = DataSource(data, repetitions)
  259. # sanity checks
  260. self.dot_repetitions = dot_repetitions
  261. debug("listener fd=%d" % self.listener.fileno())
  262. def add(self, item):
  263. """Register a single item."""
  264. # We used to hold on to these items for their fds, but now
  265. # asyncore manages them for us.
  266. if hasattr(item, "get_test_names"):
  267. for name in item.get_test_names():
  268. self.tests.add(name)
  269. def add_client(self, server, proxy=None):
  270. source = Source(self, server, proxy)
  271. self.add(source)
  272. def add_responder(self, socket):
  273. sink = Sink(socket, self)
  274. self.add(sink)
  275. def success(self, name):
  276. """Declare that a single test has passed."""
  277. self.tests.success(name)
  278. def failure(self, name):
  279. """Declare that a single test has failed."""
  280. self.tests.failure(name)
  281. def run(self):
  282. start = now = time.time()
  283. end = time.time() + self.timeout
  284. while now < end and not self.tests.all_done():
  285. # run only one iteration at a time, with a nice short timeout, so we
  286. # can actually detect completion and timeouts.
  287. asyncore.loop(0.2, False, None, 1)
  288. now = time.time()
  289. debug("Test status: %s"%self.tests.status())
  290. if not debug_flag:
  291. sys.stdout.write('\n')
  292. sys.stdout.flush()
  293. debug("Done with run(); all_done == %s and failure_count == %s"
  294. %(self.tests.all_done(), self.tests.failure_count()))
  295. self.listener.close()
  296. return self.tests.all_done() and self.tests.failure_count() == 0
  297. def main():
  298. """Test the TrafficTester by sending and receiving some data."""
  299. DATA = b"a foo is a bar" * 1000
  300. bind_to = ('localhost', int(sys.argv[1]))
  301. tt = TrafficTester(bind_to, DATA)
  302. # Don't use a proxy for self-testing, so that we avoid tor entirely
  303. tt.add_client(bind_to)
  304. success = tt.run()
  305. if success:
  306. return 0
  307. return 255
  308. if __name__ == '__main__':
  309. sys.exit(main())