Skip to content

Instantly share code, notes, and snippets.

@dracos
Created December 18, 2016 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dracos/2538ae57d5d1732571bacf6168da4b0b to your computer and use it in GitHub Desktop.
Save dracos/2538ae57d5d1732571bacf6168da4b0b to your computer and use it in GitHub Desktop.
A very small python HTTP proxy
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment