Traffic.py 13 KB

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