#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
pyGreedTorrent
This code is based on code based on microproxy.py written by ubershmekel in 2006.
"""
PORT = 8080
UP_MULT = 5.53
DN_MULT = 0
ACTUAL_PROXY_HOST_PORT = ()
# Uncomment and modify line below to use chain proxy
#ACTUAL_PROXY_HOST_PORT = '127.0.0.1', 3128
import re, socket, threading
reUP = re.compile(r"(?<=\Wuploaded=)\d+", re.UNICODE )
reDOWN = re.compile(r"(?<=\Wdownloaded=)\d+", re.UNICODE )
err403 = 'HTTP/1.0 403 Forbidden\r\n' \
+'Server: nginx/0.7.65\r\n' \
+'Date: Tue, 16 Nov 2010 14:20:07 GMT\r\n' \
+'Content-Type: text/html; charset=windows-1251\r\n' \
+'Content-Length: 169\r\n' \
+'Connection: close\r\n' \
+'<html> <head><title>403 Forbidden</title></head>' \
+'<body></body></html>'
regex = re.compile(r'http://(.*?)/', re.IGNORECASE)
def cheat_url( s ):
m = reUP.search( s )
m2 = reDOWN.search( s )
if m and m2 :
up = int( round( UP_MULT * int( m.group() ) ) )
down = int( round( DN_MULT * int( m2.group() ) ) )
return s[:m.start()] + str(up + down) + s[m.end():]
else:
return 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)
#print data
#print 11
host = regex.search(data).groups()[0]
data = cheat_url( data )
request = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#request.settimeout(6)
if ACTUAL_PROXY_HOST_PORT:
host = ACTUAL_PROXY_HOST_PORT
else:
i = host.find(':')
if i >= 0:
host = host[:i], int(host[i+1:])
else:
host = host, 80
try:
request.connect( host )
request.send( data )
reply = ''
while 1:
temp = request.recv(1024)
if ('' == temp):
break
self.conn.send(temp)
except:
self.conn.send( err403 )
self.conn.close()
class ProxyThread(threading.Thread):
def __init__(self, port):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind(('localhost', 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
proxy.run()