Advertisement
rfmonk

zlib_server_not_secure.py

Jan 30th, 2014
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. #1/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import zlib
  8. import logging
  9. import SocketServer
  10. import binascii
  11.  
  12. BLOCK_SIZE = 64
  13.  
  14.  
  15. class ZlibRequestHandler(SocketServer.BaseRequestHandler):
  16.  
  17.     logger = logging.getLogger('Server')
  18.  
  19.     def handle(self):
  20.         compressor = zlib.compressobj(1)
  21.  
  22.         # Find out what file the client wants
  23.         filename = self.request.recv(1024)
  24.         self.logger.debug('client asked for: "%s"', filename)
  25.  
  26.         # Send chunks of the file as they are compressed
  27.         with open(filename, 'rb') as input:
  28.             while True:
  29.                 block = input.read(BLOCK_SIZE)
  30.                 if not block:
  31.                     break
  32.                 self.logger.debug('RAW "%s"', block)
  33.                 compressed = compressor.compress(block)
  34.                 if compressed:
  35.                     self.logger.debug('SENDING "%s"',
  36.                                       binascii.hexlify(compressed))
  37.                     self.request.send(compressed)
  38.                 else:
  39.                     self.logger.debug('BUFFERING')
  40.  
  41.         # Send any data being buffered by the compressor
  42.         remaining = compressor.flush()
  43.         while remaining:
  44.             to_send = remaining[:BLOCK_SIZE]
  45.             remaining = remaining[BLOCK_SIZE:]
  46.             self.logger.debug('FLUSHING "%s"',
  47.                               binascii.hexlify(to_send))
  48.             self.request.send(to_send)
  49.         return
  50.  
  51. if __name__ == '__main__':
  52.     import socket
  53.     import threading
  54.     from cStringIO import StringIO
  55.  
  56.     logging.basicConfig(level=logging.DEBUG,
  57.                         format='%(name)s: %(message)s',
  58.                         )
  59.     logger = logging.getLogger('Client')
  60.  
  61.     # Set up a server, running in a seperate thread
  62.     address = ('localhost', 0)  # let the kernel assign a port
  63.     server = SocketServer.TCPServer(address, ZlibRequestHandler)
  64.     ip, port = server.server_address  # what port was assigned?
  65.  
  66.     t = threading.Thread(target=server.serve_forever)
  67.     t.setDaemon(True)
  68.     t.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement