Traffic.py 10 KB

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