Traffic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. #!/usr/bin/env python2
  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 select
  25. import struct
  26. import errno
  27. # Set debug_flag=True in order to debug this program or to get hints
  28. # about what's going wrong in your system.
  29. debug_flag = False
  30. def debug(s):
  31. "Print a debug message on stdout if debug_flag is True."
  32. if debug_flag:
  33. print("DEBUG: %s" % s)
  34. def socks_cmd(addr_port):
  35. """
  36. Return a SOCKS command for connecting to addr_port.
  37. SOCKSv4: https://en.wikipedia.org/wiki/SOCKS#Protocol
  38. SOCKSv5: RFC1928, RFC1929
  39. """
  40. ver = 4 # Only SOCKSv4 for now.
  41. cmd = 1 # Stream connection.
  42. user = '\x00'
  43. dnsname = ''
  44. host, port = addr_port
  45. try:
  46. addr = socket.inet_aton(host)
  47. except socket.error:
  48. addr = '\x00\x00\x00\x01'
  49. dnsname = '%s\x00' % host
  50. debug("Socks 4a request to %s:%d" % (host, port))
  51. return struct.pack('!BBH', ver, cmd, port) + addr + user + dnsname
  52. class TestSuite(object):
  53. """Keep a tab on how many tests are pending, how many have failed
  54. and how many have succeeded."""
  55. def __init__(self):
  56. self.not_done = 0
  57. self.successes = 0
  58. self.failures = 0
  59. def add(self):
  60. self.not_done += 1
  61. def success(self):
  62. self.not_done -= 1
  63. self.successes += 1
  64. def failure(self):
  65. self.not_done -= 1
  66. self.failures += 1
  67. def failure_count(self):
  68. return self.failures
  69. def all_done(self):
  70. return self.not_done == 0
  71. def status(self):
  72. return('%d/%d/%d' % (self.not_done, self.successes, self.failures))
  73. class Peer(object):
  74. "Base class for Listener, Source and Sink."
  75. LISTENER = 1
  76. SOURCE = 2
  77. SINK = 3
  78. def __init__(self, ptype, tt, s=None):
  79. self.type = ptype
  80. self.tt = tt # TrafficTester
  81. if s is not None:
  82. self.s = s
  83. else:
  84. self.s = socket.socket()
  85. self.s.setblocking(False)
  86. def fd(self):
  87. return self.s.fileno()
  88. def is_source(self):
  89. return self.type == self.SOURCE
  90. def is_sink(self):
  91. return self.type == self.SINK
  92. class Listener(Peer):
  93. "A TCP listener, binding, listening and accepting new connections."
  94. def __init__(self, tt, endpoint):
  95. super(Listener, self).__init__(Peer.LISTENER, tt)
  96. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  97. self.s.bind(endpoint)
  98. self.s.listen(0)
  99. def accept(self):
  100. newsock, endpoint = self.s.accept()
  101. debug("new client from %s:%s (fd=%d)" %
  102. (endpoint[0], endpoint[1], newsock.fileno()))
  103. self.tt.add(Sink(self.tt, newsock))
  104. class Sink(Peer):
  105. "A data sink, reading from its peer and verifying the data."
  106. def __init__(self, tt, s):
  107. super(Sink, self).__init__(Peer.SINK, tt, s)
  108. self.inbuf = ''
  109. def on_readable(self):
  110. """Invoked when the socket becomes readable.
  111. Return 0 on finished, successful verification.
  112. -1 on failed verification
  113. >0 if more data needs to be read
  114. """
  115. return self.verify(self.tt.data)
  116. def verify(self, data):
  117. self.inbuf += self.s.recv(len(data) - len(self.inbuf))
  118. assert(len(self.inbuf) <= len(data))
  119. if len(self.inbuf) == len(data):
  120. if self.inbuf != data:
  121. return -1 # Failed verification.
  122. debug("successful verification")
  123. return len(data) - len(self.inbuf)
  124. class Source(Peer):
  125. """A data source, connecting to a TCP server, optionally over a
  126. SOCKS proxy, sending data."""
  127. NOT_CONNECTED = 0
  128. CONNECTING = 1
  129. CONNECTING_THROUGH_PROXY = 2
  130. CONNECTED = 5
  131. def __init__(self, tt, server, buf, proxy=None):
  132. super(Source, self).__init__(Peer.SOURCE, tt)
  133. self.state = self.NOT_CONNECTED
  134. self.data = buf
  135. self.outbuf = ''
  136. self.inbuf = ''
  137. self.proxy = proxy
  138. self.connect(server)
  139. def connect(self, endpoint):
  140. self.dest = endpoint
  141. self.state = self.CONNECTING
  142. dest = self.proxy or self.dest
  143. try:
  144. self.s.connect(dest)
  145. except socket.error as e:
  146. if e[0] != errno.EINPROGRESS:
  147. raise
  148. def on_readable(self):
  149. """Invoked when the socket becomes readable.
  150. Return -1 on failure
  151. >0 if more data needs to be read or written
  152. """
  153. if self.state == self.CONNECTING_THROUGH_PROXY:
  154. self.inbuf += self.s.recv(8 - len(self.inbuf))
  155. if len(self.inbuf) == 8:
  156. if ord(self.inbuf[0]) == 0 and ord(self.inbuf[1]) == 0x5a:
  157. debug("proxy handshake successful (fd=%d)" % self.fd())
  158. self.state = self.CONNECTED
  159. self.inbuf = ''
  160. self.outbuf = self.data
  161. debug("successfully connected (fd=%d)" % self.fd())
  162. return 1 # Keep us around for writing.
  163. else:
  164. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  165. (ord(self.inbuf[1]), self.fd()))
  166. self.state = self.NOT_CONNECTED
  167. return -1
  168. assert(8 - len(self.inbuf) > 0)
  169. return 8 - len(self.inbuf)
  170. return 1 # Keep us around for writing.
  171. def want_to_write(self):
  172. return self.state == self.CONNECTING or len(self.outbuf) > 0
  173. def on_writable(self):
  174. """Invoked when the socket becomes writable.
  175. Return 0 when done writing
  176. -1 on failure (like connection refused)
  177. >0 if more data needs to be written
  178. """
  179. if self.state == self.CONNECTING:
  180. if self.proxy is None:
  181. self.state = self.CONNECTED
  182. self.outbuf = self.data
  183. debug("successfully connected (fd=%d)" % self.fd())
  184. else:
  185. self.state = self.CONNECTING_THROUGH_PROXY
  186. self.outbuf = socks_cmd(self.dest)
  187. try:
  188. n = self.s.send(self.outbuf)
  189. except socket.error as e:
  190. if e[0] == errno.ECONNREFUSED:
  191. debug("connection refused (fd=%d)" % self.fd())
  192. return -1
  193. raise
  194. self.outbuf = self.outbuf[n:]
  195. if self.state == self.CONNECTING_THROUGH_PROXY:
  196. return 1 # Keep us around.
  197. return len(self.outbuf) # When 0, we're being removed.
  198. class TrafficTester():
  199. """
  200. Hang on select.select() and dispatch to Sources and Sinks.
  201. Time out after self.timeout seconds.
  202. Keep track of successful and failed data verification using a
  203. TestSuite.
  204. Return True if all tests succeed, else False.
  205. """
  206. def __init__(self, endpoint, data={}, timeout=3):
  207. self.listener = Listener(self, endpoint)
  208. self.pending_close = []
  209. self.timeout = timeout
  210. self.tests = TestSuite()
  211. self.data = data
  212. debug("listener fd=%d" % self.listener.fd())
  213. self.peers = {} # fd:Peer
  214. def sinks(self):
  215. return self.get_by_ptype(Peer.SINK)
  216. def sources(self):
  217. return self.get_by_ptype(Peer.SOURCE)
  218. def get_by_ptype(self, ptype):
  219. return filter(lambda p: p.type == ptype, self.peers.itervalues())
  220. def add(self, peer):
  221. self.peers[peer.fd()] = peer
  222. if peer.is_source():
  223. self.tests.add()
  224. def remove(self, peer):
  225. self.peers.pop(peer.fd())
  226. self.pending_close.append(peer.s)
  227. def run(self):
  228. while not self.tests.all_done() and self.timeout > 0:
  229. rset = [self.listener.fd()] + list(self.peers)
  230. wset = [p.fd() for p in
  231. filter(lambda x: x.want_to_write(), self.sources())]
  232. # debug("rset %s wset %s" % (rset, wset))
  233. sets = select.select(rset, wset, [], 1)
  234. if all(len(s) == 0 for s in sets):
  235. self.timeout -= 1
  236. continue
  237. for fd in sets[0]: # readable fd's
  238. if fd == self.listener.fd():
  239. self.listener.accept()
  240. continue
  241. p = self.peers[fd]
  242. n = p.on_readable()
  243. if n > 0:
  244. # debug("need %d more octets from fd %d" % (n, fd))
  245. pass
  246. elif n == 0: # Success.
  247. self.tests.success()
  248. self.remove(p)
  249. else: # Failure.
  250. self.tests.failure()
  251. if p.is_sink():
  252. print("verification failed!")
  253. self.remove(p)
  254. for fd in sets[1]: # writable fd's
  255. p = self.peers.get(fd)
  256. if p is not None: # Might have been removed above.
  257. n = p.on_writable()
  258. if n == 0:
  259. self.remove(p)
  260. elif n < 0:
  261. self.tests.failure()
  262. self.remove(p)
  263. self.listener.s.close()
  264. for s in self.pending_close:
  265. s.close()
  266. return self.tests.all_done() and self.tests.failure_count() == 0
  267. def main():
  268. """Test the TrafficTester by sending and receiving some data."""
  269. DATA = "a foo is a bar" * 1000
  270. proxy = ('localhost', 9008)
  271. bind_to = ('localhost', int(sys.argv[1]))
  272. tt = TrafficTester(bind_to, DATA)
  273. tt.add(Source(tt, bind_to, DATA, proxy))
  274. success = tt.run()
  275. if success:
  276. return 0
  277. return 255
  278. if __name__ == '__main__':
  279. sys.exit(main())