Traffic.py 10 KB

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