Traffic.py 15 KB

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