Traffic.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. handler = Sink(newsock, self.tt)
  108. self.tt.add(handler)
  109. def fileno(self):
  110. return self.socket.fileno()
  111. class Sink(asynchat.async_chat):
  112. "A data sink, reading from its peer and verifying the data."
  113. def __init__(self, sock, tt):
  114. asynchat.async_chat.__init__(self, sock)
  115. self.inbuf = b""
  116. self.set_terminator(None)
  117. self.tt = tt
  118. self.repetitions = tt.repetitions
  119. self.testname = "recv-data%s"%id(self)
  120. def get_test_names(self):
  121. return [ self.testname ]
  122. def collect_incoming_data(self, inp):
  123. # shortcut read when we don't ever expect any data
  124. self.inbuf += inp
  125. data = self.tt.data
  126. debug("successfully received (bytes=%d)" % len(self.inbuf))
  127. while len(self.inbuf) >= len(data):
  128. assert(len(self.inbuf) <= len(data) or self.repetitions > 1)
  129. if self.inbuf[:len(data)] != data:
  130. debug("receive comparison failed (bytes=%d)" % len(data))
  131. self.tt.failure(self.testname)
  132. self.close()
  133. # if we're not debugging, print a dot every dot_repetitions reps
  134. elif (not debug_flag and self.tt.dot_repetitions > 0 and
  135. self.repetitions % self.tt.dot_repetitions == 0):
  136. sys.stdout.write('.')
  137. sys.stdout.flush()
  138. # repeatedly check data against self.inbuf if required
  139. debug("receive comparison success (bytes=%d)" % len(data))
  140. self.inbuf = self.inbuf[len(data):]
  141. debug("receive leftover bytes (bytes=%d)" % len(self.inbuf))
  142. self.repetitions -= 1
  143. debug("receive remaining repetitions (reps=%d)" % self.repetitions)
  144. if self.repetitions == 0 and len(self.inbuf) == 0:
  145. debug("successful verification")
  146. self.close()
  147. self.tt.success(self.testname)
  148. # calculate the actual length of data remaining, including reps
  149. debug("receive remaining bytes (bytes=%d)"
  150. % (self.repetitions*len(data) - len(self.inbuf)))
  151. def fileno(self):
  152. return self.socket.fileno()
  153. class CloseSourceProducer:
  154. """Helper: when this producer is returned, a source is successful."""
  155. def __init__(self, source):
  156. self.source = source
  157. def more(self):
  158. self.source.sent_ok()
  159. return b""
  160. class Source(asynchat.async_chat):
  161. """A data source, connecting to a TCP server, optionally over a
  162. SOCKS proxy, sending data."""
  163. CONNECTING = 1
  164. CONNECTING_THROUGH_PROXY = 2
  165. CONNECTED = 5
  166. def __init__(self, tt, server, buf, proxy=None, repetitions=1):
  167. asynchat.async_chat.__init__(self)
  168. self.data = buf
  169. self.outbuf = b''
  170. self.inbuf = b''
  171. self.proxy = proxy
  172. self.server = server
  173. self.repetitions = repetitions
  174. self._sent_no_bytes = 0
  175. self.tt = tt
  176. self.testname = "send-data%s"%id(self)
  177. # sanity checks
  178. if len(self.data) == 0:
  179. self.repetitions = 0
  180. if self.repetitions == 0:
  181. self.data = b""
  182. self.set_terminator(None)
  183. dest = (self.proxy or self.server)
  184. self.create_socket(addr_to_family(dest[0]), socket.SOCK_STREAM)
  185. debug("socket %d connecting to %r..."%(self.fileno(),dest))
  186. self.state = self.CONNECTING
  187. self.connect(dest)
  188. def get_test_names(self):
  189. return [ self.testname ]
  190. def sent_ok(self):
  191. self.tt.success(self.testname)
  192. def handle_connect(self):
  193. if self.proxy:
  194. self.state = self.CONNECTING_THROUGH_PROXY
  195. self.push(socks_cmd(self.server))
  196. else:
  197. self.state = self.CONNECTED
  198. self.push_output()
  199. def collect_incoming_data(self, data):
  200. self.inbuf += data
  201. if self.state == self.CONNECTING_THROUGH_PROXY:
  202. if len(self.inbuf) >= 8:
  203. if self.inbuf[:2] == b'\x00\x5a':
  204. debug("proxy handshake successful (fd=%d)" % self.fileno())
  205. self.state = self.CONNECTED
  206. debug("successfully connected (fd=%d)" % self.fileno())
  207. self.inbuf = self.inbuf[8:]
  208. self.push_output()
  209. else:
  210. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  211. (ord(self.inbuf[1]), self.fileno()))
  212. self.state = self.NOT_CONNECTED
  213. self.close()
  214. def push_output(self):
  215. for _ in range(self.repetitions):
  216. self.push_with_producer(asynchat.simple_producer(self.data))
  217. self.push_with_producer(CloseSourceProducer(self))
  218. self.close_when_done()
  219. def fileno(self):
  220. return self.socket.fileno()
  221. class TrafficTester(object):
  222. """
  223. Hang on select.select() and dispatch to Sources and Sinks.
  224. Time out after self.timeout seconds.
  225. Keep track of successful and failed data verification using a
  226. TestSuite.
  227. Return True if all tests succeed, else False.
  228. """
  229. def __init__(self,
  230. endpoint,
  231. data=b"",
  232. timeout=3,
  233. repetitions=1,
  234. dot_repetitions=0):
  235. self.listener = Listener(self, endpoint)
  236. self.pending_close = []
  237. self.timeout = timeout
  238. self.tests = TestSuite()
  239. self.data = data
  240. self.repetitions = repetitions
  241. # sanity checks
  242. if len(self.data) == 0:
  243. self.repetitions = 0
  244. if self.repetitions == 0:
  245. self.data = b""
  246. self.dot_repetitions = dot_repetitions
  247. debug("listener fd=%d" % self.listener.fileno())
  248. def add(self, item):
  249. """Register a single item."""
  250. # We used to hold on to these items for their fds, but now
  251. # asyncore manages them for us.
  252. if hasattr(item, "get_test_names"):
  253. for name in item.get_test_names():
  254. self.tests.add(name)
  255. def success(self, name):
  256. """Declare that a single test has passed."""
  257. self.tests.success(name)
  258. def failure(self, name):
  259. """Declare that a single test has failed."""
  260. self.tests.failure(name)
  261. def run(self):
  262. start = now = time.time()
  263. end = time.time() + self.timeout
  264. while now < end and not self.tests.all_done():
  265. # run only one iteration at a time, with a nice short timeout, so we
  266. # can actually detect completion and timeouts.
  267. asyncore.loop(0.2, False, None, 1)
  268. now = time.time()
  269. debug("Test status: %s"%self.tests.status())
  270. if not debug_flag:
  271. sys.stdout.write('\n')
  272. sys.stdout.flush()
  273. debug("Done with run(); all_done == %s and failure_count == %s"
  274. %(self.tests.all_done(), self.tests.failure_count()))
  275. self.listener.close()
  276. return self.tests.all_done() and self.tests.failure_count() == 0
  277. def main():
  278. """Test the TrafficTester by sending and receiving some data."""
  279. DATA = b"a foo is a bar" * 1000
  280. bind_to = ('localhost', int(sys.argv[1]))
  281. tt = TrafficTester(bind_to, DATA)
  282. # Don't use a proxy for self-testing, so that we avoid tor entirely
  283. tt.add(Source(tt, bind_to, DATA))
  284. success = tt.run()
  285. if success:
  286. return 0
  287. return 255
  288. if __name__ == '__main__':
  289. sys.exit(main())