Skip to content Skip to sidebar Skip to footer

How To Safely Read Readerstream From Asyncio Without Breaking The Stream

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

Solution 1:

Fixed the issue by refeeding the client_reader (ReaderStream)

Thanks to Vincent for comments to point out the request tampering situation and reconstructing the request back to its native form

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)

    # -------- Edited --------

    # perform operations based on data and obtain remote_address, remote_port

    (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:

    # Write the data to remote
    remote_writer.write(data)
    await remote_writer.drain()

    # Pipe the streams
    asyncio.ensure_future(proxy_data(client_reader, remote_writer))
    asyncio.ensure_future(proxy_data(remote_reader, client_writer))

Post a Comment for "How To Safely Read Readerstream From Asyncio Without Breaking The Stream"