Advertisement
Guest User

Untitled

a guest
Feb 25th, 2010
5,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.85 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. Microproxy
  6. This code is based on code based on microproxy.py written by ubershmekel in 2006.
  7.  
  8. Microproxy is the simplest possible http proxy. It simply relays all bytes from the client to the server at a socket send and recv level. The way it recognises the remote server to connect to is by a simple regex, which extracts the URL of the origin server from the byte stream. (This probably doesn't work in all cases).
  9.  
  10. """
  11.  
  12. import re, time, sys
  13. import socket
  14. import threading
  15.  
  16.  
  17. PORT = 8080
  18. regex = re.compile(r'http://(.*?)/', re.IGNORECASE)
  19.  
  20. class ConnectionThread(threading.Thread):
  21.     def __init__(self, (conn,addr)):
  22.         self.conn = conn
  23.         self.addr = addr
  24.         threading.Thread.__init__(self)
  25.    
  26.     def run(self):
  27.  
  28.         data = self.conn.recv(1024*1024)
  29.         host = regex.search(data).groups()[0]
  30.        
  31.         request = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  32.         #request.settimeout(6)
  33.         request.connect((host,80))
  34.         request.send(data)
  35.  
  36.         reply = ''
  37.  
  38.         while 1:
  39.             temp = request.recv(1024)
  40.  
  41.             if ('' == temp):
  42.                 break
  43.                
  44.             self.conn.send(temp)
  45.         self.conn.close()
  46.  
  47. class ProxyThread(threading.Thread):
  48.     def __init__(self, port):
  49.         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  50.         self.sock.bind(('localhost', port))
  51.         threading.Thread.__init__(self)
  52.    
  53.     def run(self):
  54.         self.sock.listen(10)
  55.         while 1:
  56.             temp = ConnectionThread(self.sock.accept())
  57.             temp.daemon = True
  58.             temp.start()
  59.  
  60. if __name__ == "__main__":
  61.     proxy = ProxyThread(PORT)
  62.     proxy.daemon = True
  63.     proxy.start()
  64.     print "Started a proxy on port", PORT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement