0

Trying to read headers in twisted middle proxy server.

Here you can see simple twisted server (stolen from stackoverflow, yeah...). It nicely works, but I need to switch proxies based on request headers. Can't understand where I can get headers here. It workd with hard coded proxie server but the idea is to switch proxies based on requests.

Any ideas please? Thanks for your time. Here is the code:

#!/usr/bin/env python

LISTEN_PORT = 8080
SERVER_PORT = 3128
SERVER_ADDR = "89.40.127.96"

from twisted.internet import protocol, reactor

class ServerProtocol(protocol.Protocol):
    def __init__(self):
        self.buffer = None
        self.client = None

    def connectionMade(self):
        factory = protocol.ClientFactory()
        factory.protocol = ClientProtocol
        factory.server = self

        reactor.connectTCP(SERVER_ADDR, SERVER_PORT, factory)

    # Client => Proxy
    def dataReceived(self, data):
        if self.client:
            self.client.write(data)
        else:
            self.buffer = data

    # Proxy => Client
    def write(self, data):
        self.transport.write(data)


class ClientProtocol(protocol.Protocol):
    def connectionMade(self):
        self.factory.server.client = self
        self.write(self.factory.server.buffer)
        self.factory.server.buffer = ''

    # Server => Proxy
    def dataReceived(self, data):
        self.factory.server.write(data)

    # Proxy => Server
    def write(self, data):
        if data:
            self.transport.write(data)


def main():
    factory = protocol.ServerFactory()
    factory.protocol = ServerProtocol

    reactor.listenTCP(LISTEN_PORT, factory)
    print "server"
    reactor.run()

if __name__ == '__main__':
    main()
KaronatoR
  • 2,579
  • 4
  • 21
  • 31
  • What are you looking for in the header? If you need source and destination IPs, use [`Protocol.transport.getPeer()`](https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.ITCPTransport.html#getPeer) or `getHost()` – notorious.no May 04 '18 at 20:31
  • @notorious.no I'm trying to make per-tab proxies for chrome. So I'm trying to add some extra-header to every request and read it in my mitm proxy server. Is it bad idea? – KaronatoR May 04 '18 at 21:58
  • Is this an HTTP proxy? If so then yes this is a bad idea if you want to change the headers. Maybe this https://stackoverflow.com/questions/9465236/python-twisted-proxy-and-modifying-content – notorious.no May 05 '18 at 02:14

0 Answers0