Traffic.py 15 KB

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