# -*- Mode: Python; tab-width: 4 -*-

import sys
import asyncore
import socket
import string

class proxy_server (asyncore.dispatcher):
	
	def __init__ (self, here=('',8110), there=('squirl', 110)):
		asyncore.dispatcher.__init__ (self)
		self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
		self.there = there
		self.bind (here)
		self.listen (5)

	def handle_accept (self):
		proxy_receiver (self, self.accept())

class proxy_sender (asynchat.async_chat):

	def __init__ (self, receiver, address):
		asynchat.async_chat.__init__ (self)
		self.receiver = receiver
		self.set_terminator (None)
		self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
		self.connect (address)

	def handle_connect (self):
		print ('Connected')

	def handle_close (self):
		self.receiver.close()

	def collect_incoming_data (self, data):
		print '==> (%d) %s' % (self.id, repr(data))
		self.receiver.push (data)

class proxy_receiver (asynchat.async_chat):

	channel_counter = counter.counter()

	def __init__ (self, server, (conn, addr)):
		asynchat.async_chat.__init__ (self, conn)
		self.set_terminator (None)
		self.server = server
		self.id = self.channel_counter.increment()
		self.sender = proxy_sender (self, server.there)
		self.sender.id = self.id

	def collect_incoming_data (self, data):
		print '<== (%d) %s' % (self.id, repr(data))
		self.sender.push (data)
		
	def handle_close (self):
		print 'closing'
		self.sender.close()
		self.close()
		del self.sender

if __name__ == '__main__':
	ps = proxy_server()
	asyncore.loop()
