Traffic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. 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. return 8 - len(self.inbuf)
  169. return 1 # Keep us around for writing.
  170. def want_to_write(self):
  171. if self.state == self.CONNECTING:
  172. return True
  173. if len(self.outbuf) > 0:
  174. return True
  175. return False
  176. def on_writable(self):
  177. """Invoked when the socket becomes writable.
  178. Return 0 when done writing
  179. -1 on failure (like connection refused)
  180. >0 if more data needs to be written
  181. """
  182. if self.state == self.CONNECTING:
  183. if self.proxy is None:
  184. self.state = self.CONNECTED
  185. self.outbuf = self.data
  186. debug("successfully connected (fd=%d)" % self.fd())
  187. else:
  188. self.state = self.CONNECTING_THROUGH_PROXY
  189. self.outbuf = socks_cmd(self.dest)
  190. try:
  191. n = self.s.send(self.outbuf)
  192. except socket.error, e:
  193. if e[0] == errno.ECONNREFUSED:
  194. debug("connection refused (fd=%d)" % self.fd())
  195. return -1
  196. raise
  197. self.outbuf = self.outbuf[n:]
  198. if self.state == self.CONNECTING_THROUGH_PROXY:
  199. return 1 # Keep us around.
  200. return len(self.outbuf) # When 0, we're being removed.
  201. class TrafficTester():
  202. """
  203. Hang on select.select() and dispatch to Sources and Sinks.
  204. Time out after self.timeout seconds.
  205. Keep track of successful and failed data verification using a
  206. TestSuite.
  207. Return True if all tests succeed, else False.
  208. """
  209. def __init__(self, endpoint, data={}, timeout=3):
  210. self.listener = Listener(self, endpoint)
  211. self.pending_close = []
  212. self.timeout = timeout
  213. self.tests = TestSuite()
  214. self.data = data
  215. debug("listener fd=%d" % self.listener.fd())
  216. self.peers = {} # fd:Peer
  217. def sinks(self):
  218. return self.get_by_ptype(Peer.SINK)
  219. def sources(self):
  220. return self.get_by_ptype(Peer.SOURCE)
  221. def get_by_ptype(self, ptype):
  222. return filter(lambda p: p.type == ptype, self.peers.itervalues())
  223. def add(self, peer):
  224. self.peers[peer.fd()] = peer
  225. if peer.is_source():
  226. self.tests.add()
  227. def remove(self, peer):
  228. self.peers.pop(peer.fd())
  229. self.pending_close.append(peer.s)
  230. def run(self):
  231. while True:
  232. if self.tests.all_done() or self.timeout == 0:
  233. break
  234. rset = [self.listener.fd()] + list(self.peers)
  235. wset = [p.fd() for p in
  236. filter(lambda x: x.want_to_write(), self.sources())]
  237. #debug("rset %s wset %s" % (rset, wset))
  238. sets = select.select(rset, wset, [], 1)
  239. if all(len(s)==0 for s in sets):
  240. self.timeout -= 1
  241. continue
  242. for fd in sets[0]: # readable fd's
  243. if fd == self.listener.fd():
  244. self.listener.accept()
  245. continue
  246. p = self.peers[fd]
  247. n = p.on_readable()
  248. if n > 0:
  249. #debug("need %d more octets from fd %d" % (n, fd))
  250. pass
  251. elif n == 0: # Success.
  252. self.tests.success()
  253. self.remove(p)
  254. else: # Failure.
  255. self.tests.failure()
  256. if p.is_sink():
  257. print("verification failed!")
  258. self.remove(p)
  259. for fd in sets[1]: # writable fd's
  260. p = self.peers.get(fd)
  261. if p is not None: # Might have been removed above.
  262. n = p.on_writable()
  263. if n == 0:
  264. self.remove(p)
  265. elif n < 0:
  266. self.tests.failure()
  267. self.remove(p)
  268. self.listener.s.close()
  269. for s in self.pending_close:
  270. s.close()
  271. return self.tests.all_done() and self.tests.failure_count() == 0
  272. import sys
  273. def main():
  274. """Test the TrafficTester by sending and receiving some data."""
  275. DATA = "a foo is a bar" * 1000
  276. DATA_CORRUPT = "a foo is a baz" * 1000
  277. proxy = ('localhost', 9008)
  278. bind_to = ('localhost', int(sys.argv[1]))
  279. tt = TrafficTester(bind_to, DATA)
  280. tt.add(Source(tt, bind_to, DATA, proxy))
  281. success = tt.run()
  282. if success:
  283. return 0
  284. return 255
  285. if __name__ == '__main__':
  286. sys.exit(main())