Traffic.py 15 KB

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