Traffic.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. debug("Socks 4a request to %s:%d" % (host, port))
  51. return struct.pack('!BBH', ver, cmd, port) + addr + user + dnsname
  52. class TestSuite(object):
  53. """Keep a tab on how many tests are pending, how many have failed
  54. and how many have succeeded."""
  55. def __init__(self):
  56. self.not_done = 0
  57. self.successes = 0
  58. self.failures = 0
  59. def add(self):
  60. self.not_done += 1
  61. def success(self):
  62. self.not_done -= 1
  63. self.successes += 1
  64. def failure(self):
  65. self.not_done -= 1
  66. self.failures += 1
  67. def failure_count(self):
  68. return self.failures
  69. def all_done(self):
  70. return self.not_done == 0
  71. def status(self):
  72. return('%d/%d/%d' % (self.not_done, self.successes, self.failures))
  73. class Peer(object):
  74. "Base class for Listener, Source and Sink."
  75. LISTENER = 1
  76. SOURCE = 2
  77. SINK = 3
  78. def __init__(self, ptype, tt, s=None):
  79. self.type = ptype
  80. self.tt = tt # TrafficTester
  81. if s is not None:
  82. self.s = s
  83. else:
  84. self.s = socket.socket()
  85. self.s.setblocking(False)
  86. def fd(self):
  87. return self.s.fileno()
  88. def is_source(self):
  89. return self.type == self.SOURCE
  90. def is_sink(self):
  91. return self.type == self.SINK
  92. class Listener(Peer):
  93. "A TCP listener, binding, listening and accepting new connections."
  94. def __init__(self, tt, endpoint):
  95. super(Listener, self).__init__(Peer.LISTENER, tt)
  96. self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  97. self.s.bind(endpoint)
  98. self.s.listen(0)
  99. def accept(self):
  100. newsock, endpoint = self.s.accept()
  101. debug("new client from %s:%s (fd=%d)" %
  102. (endpoint[0], endpoint[1], newsock.fileno()))
  103. self.tt.add(Sink(self.tt, newsock))
  104. class Sink(Peer):
  105. "A data sink, reading from its peer and verifying the data."
  106. def __init__(self, tt, s):
  107. super(Sink, self).__init__(Peer.SINK, tt, s)
  108. self.inbuf = ''
  109. self.repetitions = self.tt.repetitions
  110. def on_readable(self):
  111. """Invoked when the socket becomes readable.
  112. Return 0 on finished, successful verification.
  113. -1 on failed verification
  114. >0 if more data needs to be read
  115. """
  116. return self.verify(self.tt.data)
  117. def verify(self, data):
  118. # shortcut read when we don't ever expect any data
  119. if self.repetitions == 0 or len(self.tt.data) == 0:
  120. debug("no verification required - no data")
  121. return 0;
  122. self.inbuf += self.s.recv(len(data) - len(self.inbuf))
  123. debug("successfully received (bytes=%d)" % len(self.inbuf))
  124. while len(self.inbuf) >= len(data):
  125. assert(len(self.inbuf) <= len(data) or self.repetitions > 1)
  126. if self.inbuf[:len(data)] != data:
  127. debug("receive comparison failed (bytes=%d)" % len(data))
  128. return -1 # Failed verification.
  129. # if we're not debugging, print a dot every dot_repetitions reps
  130. elif (not debug_flag
  131. and self.tt.dot_repetitions > 0
  132. and self.repetitions % self.tt.dot_repetitions == 0):
  133. sys.stdout.write('.')
  134. sys.stdout.flush()
  135. # repeatedly check data against self.inbuf if required
  136. debug("receive comparison success (bytes=%d)" % len(data))
  137. self.inbuf = self.inbuf[len(data):]
  138. debug("receive leftover bytes (bytes=%d)" % len(self.inbuf))
  139. self.repetitions -= 1
  140. debug("receive remaining repetitions (reps=%d)" % self.repetitions)
  141. if self.repetitions == 0 and len(self.inbuf) == 0:
  142. debug("successful verification")
  143. # calculate the actual length of data remaining, including reps
  144. debug("receive remaining bytes (bytes=%d)"
  145. % (self.repetitions*len(data) - len(self.inbuf)))
  146. return self.repetitions*len(data) - len(self.inbuf)
  147. class Source(Peer):
  148. """A data source, connecting to a TCP server, optionally over a
  149. SOCKS proxy, sending data."""
  150. NOT_CONNECTED = 0
  151. CONNECTING = 1
  152. CONNECTING_THROUGH_PROXY = 2
  153. CONNECTED = 5
  154. def __init__(self, tt, server, buf, proxy=None, repetitions=1):
  155. super(Source, self).__init__(Peer.SOURCE, tt)
  156. self.state = self.NOT_CONNECTED
  157. self.data = buf
  158. self.outbuf = ''
  159. self.inbuf = ''
  160. self.proxy = proxy
  161. self.repetitions = repetitions
  162. # sanity checks
  163. if len(self.data) == 0:
  164. self.repetitions = 0
  165. if self.repetitions == 0:
  166. self.data = {}
  167. self.connect(server)
  168. def connect(self, endpoint):
  169. self.dest = endpoint
  170. self.state = self.CONNECTING
  171. dest = self.proxy or self.dest
  172. try:
  173. self.s.connect(dest)
  174. except socket.error as e:
  175. if e[0] != errno.EINPROGRESS:
  176. raise
  177. def on_readable(self):
  178. """Invoked when the socket becomes readable.
  179. Return -1 on failure
  180. >0 if more data needs to be read or written
  181. """
  182. if self.state == self.CONNECTING_THROUGH_PROXY:
  183. self.inbuf += self.s.recv(8 - len(self.inbuf))
  184. if len(self.inbuf) == 8:
  185. if ord(self.inbuf[0]) == 0 and ord(self.inbuf[1]) == 0x5a:
  186. debug("proxy handshake successful (fd=%d)" % self.fd())
  187. self.state = self.CONNECTED
  188. self.inbuf = ''
  189. debug("successfully connected (fd=%d)" % self.fd())
  190. # if we have no reps or no data, skip sending actual data
  191. if self.want_to_write():
  192. return 1 # Keep us around for writing.
  193. else:
  194. # shortcut write when we don't ever expect any data
  195. debug("no connection required - no data")
  196. return 0
  197. else:
  198. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  199. (ord(self.inbuf[1]), self.fd()))
  200. self.state = self.NOT_CONNECTED
  201. return -1
  202. assert(8 - len(self.inbuf) > 0)
  203. return 8 - len(self.inbuf)
  204. return self.want_to_write() # Keep us around for writing if needed
  205. def want_to_write(self):
  206. return (self.state == self.CONNECTING or len(self.outbuf) > 0
  207. or (self.repetitions > 0 and len(self.data) > 0))
  208. def on_writable(self):
  209. """Invoked when the socket becomes writable.
  210. Return 0 when done writing
  211. -1 on failure (like connection refused)
  212. >0 if more data needs to be written
  213. """
  214. if self.state == self.CONNECTING:
  215. if self.proxy is None:
  216. self.state = self.CONNECTED
  217. debug("successfully connected (fd=%d)" % self.fd())
  218. else:
  219. self.state = self.CONNECTING_THROUGH_PROXY
  220. self.outbuf = socks_cmd(self.dest)
  221. # we write socks_cmd() to the proxy, then read the response
  222. # if we get the correct response, we're CONNECTED
  223. if self.state == self.CONNECTED:
  224. # repeat self.data into self.outbuf if required
  225. if (len(self.outbuf) < len(self.data) and self.repetitions > 0):
  226. self.outbuf += self.data
  227. self.repetitions -= 1
  228. debug("adding more data to send (bytes=%d)" % len(self.data))
  229. debug("now have data to send (bytes=%d)" % len(self.outbuf))
  230. debug("send repetitions remaining (reps=%d)"
  231. % self.repetitions)
  232. try:
  233. n = self.s.send(self.outbuf)
  234. except socket.error as e:
  235. if e[0] == errno.ECONNREFUSED:
  236. debug("connection refused (fd=%d)" % self.fd())
  237. return -1
  238. raise
  239. # sometimes, this debug statement prints 0
  240. # it should print length of the data sent
  241. # but the code works regardless of this error
  242. debug("successfully sent (bytes=%d)" % n)
  243. self.outbuf = self.outbuf[n:]
  244. if self.state == self.CONNECTING_THROUGH_PROXY:
  245. return 1 # Keep us around.
  246. debug("bytes remaining on outbuf (bytes=%d)" % len(self.outbuf))
  247. # calculate the actual length of data remaining, including reps
  248. # When 0, we're being removed.
  249. debug("bytes remaining overall (bytes=%d)"
  250. % (self.repetitions*len(self.data) + len(self.outbuf)))
  251. return self.repetitions*len(self.data) + len(self.outbuf)
  252. class TrafficTester():
  253. """
  254. Hang on select.select() and dispatch to Sources and Sinks.
  255. Time out after self.timeout seconds.
  256. Keep track of successful and failed data verification using a
  257. TestSuite.
  258. Return True if all tests succeed, else False.
  259. """
  260. def __init__(self,
  261. endpoint,
  262. data={},
  263. timeout=3,
  264. repetitions=1,
  265. dot_repetitions=0):
  266. self.listener = Listener(self, endpoint)
  267. self.pending_close = []
  268. self.timeout = timeout
  269. self.tests = TestSuite()
  270. self.data = data
  271. self.repetitions = repetitions
  272. # sanity checks
  273. if len(self.data) == 0:
  274. self.repetitions = 0
  275. if self.repetitions == 0:
  276. self.data = {}
  277. self.dot_repetitions = dot_repetitions
  278. debug("listener fd=%d" % self.listener.fd())
  279. self.peers = {} # fd:Peer
  280. def sinks(self):
  281. return self.get_by_ptype(Peer.SINK)
  282. def sources(self):
  283. return self.get_by_ptype(Peer.SOURCE)
  284. def get_by_ptype(self, ptype):
  285. return filter(lambda p: p.type == ptype, self.peers.itervalues())
  286. def add(self, peer):
  287. self.peers[peer.fd()] = peer
  288. if peer.is_source():
  289. self.tests.add()
  290. def remove(self, peer):
  291. self.peers.pop(peer.fd())
  292. self.pending_close.append(peer.s)
  293. def run(self):
  294. while not self.tests.all_done() and self.timeout > 0:
  295. rset = [self.listener.fd()] + list(self.peers)
  296. wset = [p.fd() for p in
  297. filter(lambda x: x.want_to_write(), self.sources())]
  298. # debug("rset %s wset %s" % (rset, wset))
  299. sets = select.select(rset, wset, [], 1)
  300. if all(len(s) == 0 for s in sets):
  301. self.timeout -= 1
  302. continue
  303. for fd in sets[0]: # readable fd's
  304. if fd == self.listener.fd():
  305. self.listener.accept()
  306. continue
  307. p = self.peers[fd]
  308. n = p.on_readable()
  309. if n > 0:
  310. # debug("need %d more octets from fd %d" % (n, fd))
  311. pass
  312. elif n == 0: # Success.
  313. self.tests.success()
  314. self.remove(p)
  315. else: # Failure.
  316. self.tests.failure()
  317. if p.is_sink():
  318. print("verification failed!")
  319. self.remove(p)
  320. for fd in sets[1]: # writable fd's
  321. p = self.peers.get(fd)
  322. if p is not None: # Might have been removed above.
  323. n = p.on_writable()
  324. if n == 0:
  325. self.remove(p)
  326. elif n < 0:
  327. self.tests.failure()
  328. self.remove(p)
  329. for fd in self.peers:
  330. peer = self.peers[fd]
  331. debug("peer fd=%d never pending close, never read or wrote" % fd)
  332. self.pending_close.append(peer.s)
  333. self.listener.s.close()
  334. for s in self.pending_close:
  335. s.close()
  336. if not debug_flag:
  337. sys.stdout.write('\n')
  338. sys.stdout.flush()
  339. return self.tests.all_done() and self.tests.failure_count() == 0
  340. def main():
  341. """Test the TrafficTester by sending and receiving some data."""
  342. DATA = "a foo is a bar" * 1000
  343. proxy = ('localhost', 9008)
  344. bind_to = ('localhost', int(sys.argv[1]))
  345. tt = TrafficTester(bind_to, DATA)
  346. tt.add(Source(tt, bind_to, DATA, proxy))
  347. success = tt.run()
  348. if success:
  349. return 0
  350. return 255
  351. if __name__ == '__main__':
  352. sys.exit(main())