Traffic.py 16 KB

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