#!/usr/bin/env python """ Microproxy This code is based on http://pastebin.com/mdsAjhdQ based on code based on microproxy.py written by ubershmekel in 2006. Microproxy is a very small HTTP proxy. It relays all bytes from the client to the server at a socket send and recv level. It looks at the Host: header to recognise where to connect to. """ import re import socket import signal import sys import threading def sigint_received(signum, frame): sys.exit(0) signal.signal(signal.SIGINT, sigint_received) PORT = 8080 regexHost = re.compile(r'Host: ([^\s]*)', re.IGNORECASE) regexUri = re.compile(r'((?:GET|POST) [^\s]*)') class ConnectionThread(threading.Thread): def __init__(self, (conn,addr)): self.conn = conn self.addr = addr threading.Thread.__init__(self) def run(self): data = self.conn.recv(1024*1024) host = regexHost.search(data).groups()[0] uri = regexUri.search(data).groups()[0] print '%s, %s' % (host, uri) request = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #request.settimeout(6) request.connect((host, 80)) request.send(data) while 1: temp = request.recv(1024) if not temp: break self.conn.send(temp) self.conn.close() class ProxyThread(threading.Thread): def __init__(self, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.bind(('0.0.0.0', port)) threading.Thread.__init__(self) def run(self): self.sock.listen(10) while 1: temp = ConnectionThread(self.sock.accept()) temp.daemon = True temp.start() if __name__ == "__main__": proxy = ProxyThread(PORT) proxy.daemon = True proxy.start() print "Started a proxy on port", PORT while 1: pass