Traffic.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. self._sent_no_bytes = 0
  163. # sanity checks
  164. if len(self.data) == 0:
  165. self.repetitions = 0
  166. if self.repetitions == 0:
  167. self.data = {}
  168. self.connect(server)
  169. def connect(self, endpoint):
  170. self.dest = endpoint
  171. self.state = self.CONNECTING
  172. dest = self.proxy or self.dest
  173. try:
  174. self.s.connect(dest)
  175. except socket.error as e:
  176. if e[0] != errno.EINPROGRESS:
  177. raise
  178. def on_readable(self):
  179. """Invoked when the socket becomes readable.
  180. Return -1 on failure
  181. >0 if more data needs to be read or written
  182. """
  183. if self.state == self.CONNECTING_THROUGH_PROXY:
  184. self.inbuf += self.s.recv(8 - len(self.inbuf))
  185. if len(self.inbuf) == 8:
  186. if ord(self.inbuf[0]) == 0 and ord(self.inbuf[1]) == 0x5a:
  187. debug("proxy handshake successful (fd=%d)" % self.fd())
  188. self.state = self.CONNECTED
  189. self.inbuf = ''
  190. debug("successfully connected (fd=%d)" % self.fd())
  191. # if we have no reps or no data, skip sending actual data
  192. if self.want_to_write():
  193. return 1 # Keep us around for writing.
  194. else:
  195. # shortcut write when we don't ever expect any data
  196. debug("no connection required - no data")
  197. return 0
  198. else:
  199. debug("proxy handshake failed (0x%x)! (fd=%d)" %
  200. (ord(self.inbuf[1]), self.fd()))
  201. self.state = self.NOT_CONNECTED
  202. return -1
  203. assert(8 - len(self.inbuf) > 0)
  204. return 8 - len(self.inbuf)
  205. return self.want_to_write() # Keep us around for writing if needed
  206. def want_to_write(self):
  207. return (self.state == self.CONNECTING or len(self.outbuf) > 0
  208. or (self.repetitions > 0 and len(self.data) > 0))
  209. def on_writable(self):
  210. """Invoked when the socket becomes writable.
  211. Return 0 when done writing
  212. -1 on failure (like connection refused)
  213. >0 if more data needs to be written
  214. """
  215. if self.state == self.CONNECTING:
  216. if self.proxy is None:
  217. self.state = self.CONNECTED
  218. debug("successfully connected (fd=%d)" % self.fd())
  219. else:
  220. self.state = self.CONNECTING_THROUGH_PROXY
  221. self.outbuf = socks_cmd(self.dest)
  222. # we write socks_cmd() to the proxy, then read the response
  223. # if we get the correct response, we're CONNECTED
  224. if self.state == self.CONNECTED:
  225. # repeat self.data into self.outbuf if required
  226. if (len(self.outbuf) < len(self.data) and self.repetitions > 0):
  227. self.outbuf += self.data
  228. self.repetitions -= 1
  229. debug("adding more data to send (bytes=%d)" % len(self.data))
  230. debug("now have data to send (bytes=%d)" % len(self.outbuf))
  231. debug("send repetitions remaining (reps=%d)"
  232. % self.repetitions)
  233. try:
  234. n = self.s.send(self.outbuf)
  235. except socket.error as e:
  236. if e[0] == errno.ECONNREFUSED:
  237. debug("connection refused (fd=%d)" % self.fd())
  238. return -1
  239. raise
  240. # sometimes, this debug statement prints 0
  241. # it should print length of the data sent
  242. # but the code works as long as this doesn't keep on happening
  243. if n > 0:
  244. debug("successfully sent (bytes=%d)" % n)
  245. self._sent_no_bytes = 0
  246. else:
  247. debug("BUG: sent no bytes")
  248. self._sent_no_bytes += 1
  249. if self._sent_no_bytes >= 10000:
  250. print("Send no data %d times. Stalled." % (self._sent_no_bytes))
  251. sys.exit(-1)
  252. self.outbuf = self.outbuf[n:]
  253. if self.state == self.CONNECTING_THROUGH_PROXY:
  254. return 1 # Keep us around.
  255. debug("bytes remaining on outbuf (bytes=%d)" % len(self.outbuf))
  256. # calculate the actual length of data remaining, including reps
  257. # When 0, we're being removed.
  258. debug("bytes remaining overall (bytes=%d)"
  259. % (self.repetitions*len(self.data) + len(self.outbuf)))
  260. return self.repetitions*len(self.data) + len(self.outbuf)
  261. class TrafficTester():
  262. """
  263. Hang on select.select() and dispatch to Sources and Sinks.
  264. Time out after self.timeout seconds.
  265. Keep track of successful and failed data verification using a
  266. TestSuite.
  267. Return True if all tests succeed, else False.
  268. """
  269. def __init__(self,
  270. endpoint,
  271. data={},
  272. timeout=3,
  273. repetitions=1,
  274. dot_repetitions=0):
  275. self.listener = Listener(self, endpoint)
  276. self.pending_close = []
  277. self.timeout = timeout
  278. self.tests = TestSuite()
  279. self.data = data
  280. self.repetitions = repetitions
  281. # sanity checks
  282. if len(self.data) == 0:
  283. self.repetitions = 0
  284. if self.repetitions == 0:
  285. self.data = {}
  286. self.dot_repetitions = dot_repetitions
  287. debug("listener fd=%d" % self.listener.fd())
  288. self.peers = {} # fd:Peer
  289. def sinks(self):
  290. return self.get_by_ptype(Peer.SINK)
  291. def sources(self):
  292. return self.get_by_ptype(Peer.SOURCE)
  293. def get_by_ptype(self, ptype):
  294. return filter(lambda p: p.type == ptype, self.peers.itervalues())
  295. def add(self, peer):
  296. self.peers[peer.fd()] = peer
  297. if peer.is_source():
  298. self.tests.add()
  299. def remove(self, peer):
  300. self.peers.pop(peer.fd())
  301. self.pending_close.append(peer.s)
  302. def run(self):
  303. while not self.tests.all_done() and self.timeout > 0:
  304. rset = [self.listener.fd()] + list(self.peers)
  305. wset = [p.fd() for p in
  306. filter(lambda x: x.want_to_write(), self.sources())]
  307. # debug("rset %s wset %s" % (rset, wset))
  308. sets = select.select(rset, wset, [], 1)
  309. if all(len(s) == 0 for s in sets):
  310. self.timeout -= 1
  311. continue
  312. for fd in sets[0]: # readable fd's
  313. if fd == self.listener.fd():
  314. self.listener.accept()
  315. continue
  316. p = self.peers[fd]
  317. n = p.on_readable()
  318. if n > 0:
  319. # debug("need %d more octets from fd %d" % (n, fd))
  320. pass
  321. elif n == 0: # Success.
  322. self.tests.success()
  323. self.remove(p)
  324. else: # Failure.
  325. self.tests.failure()
  326. if p.is_sink():
  327. print("verification failed!")
  328. self.remove(p)
  329. for fd in sets[1]: # writable fd's
  330. p = self.peers.get(fd)
  331. if p is not None: # Might have been removed above.
  332. n = p.on_writable()
  333. if n == 0:
  334. self.remove(p)
  335. elif n < 0:
  336. self.tests.failure()
  337. self.remove(p)
  338. for fd in self.peers:
  339. peer = self.peers[fd]
  340. debug("peer fd=%d never pending close, never read or wrote" % fd)
  341. self.pending_close.append(peer.s)
  342. self.listener.s.close()
  343. for s in self.pending_close:
  344. s.close()
  345. if not debug_flag:
  346. sys.stdout.write('\n')
  347. sys.stdout.flush()
  348. return self.tests.all_done() and self.tests.failure_count() == 0
  349. def main():
  350. """Test the TrafficTester by sending and receiving some data."""
  351. DATA = "a foo is a bar" * 1000
  352. proxy = ('localhost', 9008)
  353. bind_to = ('localhost', int(sys.argv[1]))
  354. tt = TrafficTester(bind_to, DATA)
  355. tt.add(Source(tt, bind_to, DATA, proxy))
  356. success = tt.run()
  357. if success:
  358. return 0
  359. return 255
  360. if __name__ == '__main__':
  361. sys.exit(main())