Traffic.py 11 KB

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