Traffic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 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. debug("successful verification")
  120. return len(data) - len(self.inbuf)
  121. class Source(Peer):
  122. """A data source, connecting to a TCP server, optionally over a
  123. SOCKS proxy, sending data."""
  124. NOT_CONNECTED = 0
  125. CONNECTING = 1
  126. CONNECTING_THROUGH_PROXY = 2
  127. CONNECTED = 5
  128. def __init__(self, tt, server, buf, proxy=None):
  129. super(Source, self).__init__(Peer.SOURCE, tt)
  130. self.state = self.NOT_CONNECTED
  131. self.data = buf
  132. self.outbuf = ''
  133. self.inbuf = ''
  134. self.proxy = proxy
  135. self.connect(server)
  136. def connect(self, endpoint):
  137. self.dest = endpoint
  138. self.state = self.CONNECTING
  139. dest = self.proxy or self.dest
  140. try:
  141. self.s.connect(dest)
  142. except socket.error, e:
  143. if e[0] != errno.EINPROGRESS:
  144. raise
  145. def on_readable(self):
  146. """Invoked when the socket becomes readable.
  147. Return -1 on failure
  148. >0 if more data needs to be read or written
  149. """
  150. if self.state == self.CONNECTING_THROUGH_PROXY:
  151. self.inbuf += self.s.recv(8 - len(self.inbuf))
  152. if len(self.inbuf) == 8:
  153. if ord(self.inbuf[0]) == 0 and ord(self.inbuf[1]) == 0x5a:
  154. debug("proxy handshake successful (fd=%d)" % self.fd())
  155. self.state = self.CONNECTED
  156. self.inbuf = ''
  157. self.outbuf = self.data
  158. debug("successfully connected (fd=%d)" % self.fd())
  159. return 1 # Keep us around for writing.
  160. else:
  161. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  162. (ord(self.inbuf[1]), self.fd()))
  163. self.state = self.NOT_CONNECTED
  164. return -1
  165. assert(8 - len(self.inbuf) > 0)
  166. return 8 - len(self.inbuf)
  167. return 1 # Keep us around for writing.
  168. def want_to_write(self):
  169. if self.state == self.CONNECTING:
  170. return True
  171. if len(self.outbuf) > 0:
  172. return True
  173. return False
  174. def on_writable(self):
  175. """Invoked when the socket becomes writable.
  176. Return 0 when done writing
  177. -1 on failure (like connection refused)
  178. >0 if more data needs to be written
  179. """
  180. if self.state == self.CONNECTING:
  181. if self.proxy is None:
  182. self.state = self.CONNECTED
  183. self.outbuf = self.data
  184. debug("successfully connected (fd=%d)" % self.fd())
  185. else:
  186. self.state = self.CONNECTING_THROUGH_PROXY
  187. self.outbuf = socks_cmd(self.dest)
  188. try:
  189. n = self.s.send(self.outbuf)
  190. except socket.error, e:
  191. if e[0] == errno.ECONNREFUSED:
  192. debug("connection refused (fd=%d)" % self.fd())
  193. return -1
  194. raise
  195. self.outbuf = self.outbuf[n:]
  196. if self.state == self.CONNECTING_THROUGH_PROXY:
  197. return 1 # Keep us around.
  198. return len(self.outbuf) # When 0, we're being removed.
  199. class TrafficTester():
  200. """
  201. Hang on select.select() and dispatch to Sources and Sinks.
  202. Time out after self.timeout seconds.
  203. Keep track of successful and failed data verification using a
  204. TestSuite.
  205. Return True if all tests succeed, else False.
  206. """
  207. def __init__(self, endpoint, data={}, timeout=3):
  208. self.listener = Listener(self, endpoint)
  209. self.pending_close = []
  210. self.timeout = timeout
  211. self.tests = TestSuite()
  212. self.data = data
  213. debug("listener fd=%d" % self.listener.fd())
  214. self.peers = {} # fd:Peer
  215. def sinks(self):
  216. return self.get_by_ptype(Peer.SINK)
  217. def sources(self):
  218. return self.get_by_ptype(Peer.SOURCE)
  219. def get_by_ptype(self, ptype):
  220. return filter(lambda p: p.type == ptype, self.peers.itervalues())
  221. def add(self, peer):
  222. self.peers[peer.fd()] = peer
  223. if peer.is_source():
  224. self.tests.add()
  225. def remove(self, peer):
  226. self.peers.pop(peer.fd())
  227. self.pending_close.append(peer.s)
  228. def run(self):
  229. while True:
  230. if self.tests.all_done() or self.timeout == 0:
  231. break
  232. rset = [self.listener.fd()] + list(self.peers)
  233. wset = [p.fd() for p in
  234. filter(lambda x: x.want_to_write(), self.sources())]
  235. # debug("rset %s wset %s" % (rset, wset))
  236. sets = select.select(rset, wset, [], 1)
  237. if all(len(s) == 0 for s in sets):
  238. self.timeout -= 1
  239. continue
  240. for fd in sets[0]: # readable fd's
  241. if fd == self.listener.fd():
  242. self.listener.accept()
  243. continue
  244. p = self.peers[fd]
  245. n = p.on_readable()
  246. if n > 0:
  247. # debug("need %d more octets from fd %d" % (n, fd))
  248. pass
  249. elif n == 0: # Success.
  250. self.tests.success()
  251. self.remove(p)
  252. else: # Failure.
  253. self.tests.failure()
  254. if p.is_sink():
  255. print("verification failed!")
  256. self.remove(p)
  257. for fd in sets[1]: # writable fd's
  258. p = self.peers.get(fd)
  259. if p is not None: # Might have been removed above.
  260. n = p.on_writable()
  261. if n == 0:
  262. self.remove(p)
  263. elif n < 0:
  264. self.tests.failure()
  265. self.remove(p)
  266. self.listener.s.close()
  267. for s in self.pending_close:
  268. s.close()
  269. return self.tests.all_done() and self.tests.failure_count() == 0
  270. import sys
  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())