I am trying to build a man-in-middle proxy server that relays the client request to the various proxy services predefined in my app. So, in order to do this, I need to distinguish the client's request for a service.
The code below works as long as I don't uncomment # data = await client_reader.read(2048)
from which I can parse the headers. i.e. If I do perform that code,
Say if am doing this with that line of code uncommmented:
r = requests.get('http://api.ipify.org/', headers = {'Proxy-Type':'custom'}, proxies={'http':'http://127.0.0.1:9911'})
I would get a 408 Request Time-out
from ipify in the r.content
async def proxy_data(reader, writer, connection_string):
try:
while True:
data = await reader.read(2048)
if not data:
break
writer.write(data)
await writer.drain()
except Exception as e:
raise
finally:
writer.close()
async def accept_client(client_reader, client_writer):
try:
# Get proxy service - [Proxy-Type] from header via client_reader
# Set remote_address and remote_port based on it
# data = await client_reader.read(2048)
(remote_reader, remote_writer) = await asyncio.wait_for(
asyncio.open_connection(host = remote_address, port = remote_port),
timeout = 30)
except asyncio.TimeoutError:
client_writer.close()
except Exception as e:
client_writer.close()
else:
# Pipe the streams
asyncio.ensure_future(proxy_data(client_reader, remote_writer))
asyncio.ensure_future(proxy_data(remote_reader, client_writer))
def main():
def handle_client(client_reader, client_writer):
asyncio.ensure_future(
accept_client(
client_reader = client_reader,
client_writer = client_writer
)
)
loop = asyncio.get_event_loop()
try:
server = loop.run_until_complete(
asyncio.start_server(
handle_client, host = '127.0.0.1', port = 9911))
except Exception as e:
logger.error('Bind error: {}'.format(e))
sys.exit(1)
for s in server.sockets:
logger.debug('Proxy broker listening on {}'.format(s.getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
Can anyone point out the issue here or how to open connection conditionally?