aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/addons/wsgiapp.py
blob: 549d8c87edcf1dff405a99b7bdf279e2038e2403 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from mitmproxy import ctx
from mitmproxy import exceptions

from mitmproxy.net import wsgi
from mitmproxy import version


class WSGIApp:
    """
        An addon that hosts a WSGI app within mitproxy, at a specified
        hostname and port.
    """
    def __init__(self, app, host, port):
        self.app, self.host, self.port = app, host, port

    @property
    def name(self):
        return "wsgiapp:%s:%s" % (self.host, self.port)

    def serve(self, app, flow):
        """
            Serves app on flow, and prevents further handling of the flow.
        """
        app = wsgi.WSGIAdaptor(
            app,
            flow.request.pretty_host,
            flow.request.port,
            version.MITMPROXY
        )
        err = app.serve(
            flow,
            flow.client_conn.wfile,
            **{"mitmproxy.master": ctx.master}
        )
        if err:
            ctx.log.error("Error in wsgi app. %s" % err)
            raise exceptions.AddonHalt()
        flow.reply.kill()

    def request(self, f):
        if (f.request.pretty_host, f.request.port) == (self.host, self.port):
            self.serve(self.app, f)