Traffic.py 10 KB

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