Simple port mapping (port forward):
import socket
import sys
import thread
def main(setup, error):
sys.stderr = file(error, 'a')
for settings in parse(setup):
thread.start_new_thread(server, settings)
lock = thread.allocate_lock()
lock.acquire()
lock.acquire()
def parse(setup):
settings = list()
for line in file(setup):
parts = line.split()
settings.append((parts[0], int(parts[1]), int(parts[2])))
return settings
def server(*settings):
try:
dock_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dock_socket.bind(('', settings[2]))
dock_socket.listen(5)
while True:
client_socket = dock_socket.accept()[0]
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((settings[0], settings[1]))
thread.start_new_thread(forward, (client_socket, server_socket))
thread.start_new_thread(forward, (server_socket, client_socket))
finally:
thread.start_new_thread(server, settings)
def forward(source, destination):
string = ' '
while string:
string = source.recv(1024)
if string:
destination.sendall(string)
else:
source.shutdown(socket.SHUT_RD)
destination.shutdown(socket.SHUT_WR)
if __name__ == '__main__':
main('proxy.ini', 'error.log')
Very simple proxy server:
'''
microproxy.py
A very low-level, simple-minded proxy that just forwards the data.
You can do whatever you please with this code, knock yourself out.
btw, the comments were erased on purpose.
If you wish to understand the code, google 3 things:
1. python socket example
2. python regular excodessions
3. python thread
'''
import re
import socket
from threading import *
regex = re.compile(r'http://(.*?)/', re.IGNORECASE)
class ConnectionThread(Thread):
def __init__(self, (conn,addr)):
self.conn = conn
self.addr = addr
Thread.__init__(self)
def run(self):
data = self.conn.recv(1024*1024)
host = regex.search(data).groups()[0]
request = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
request.settimeout(6)
request.connect((host,80))
request.send(data)
reply = ''
try:
while 1:
temp = request.recv(1024)
if ('' == temp):
break
reply += temp
except Exception:
pass
self.conn.send(reply)
self.conn.close()
class ProxyThread(Thread):
def __init__(self, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('localhost', port))
Thread.__init__(self)
def run(self):
self.sock.listen(10)
while 1:
temp = ConnectionThread(self.sock.accept())
temp.start()
if __name__ == "__main__":
a = ProxyThread(8000)
a.start()
print "Started a proxy on port 8000"
No comments:
Post a Comment