aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/master.py
blob: b41e2a8d68b38f2ed89757013399728a7dd2d85f (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import threading
import contextlib
import queue

from mitmproxy import addonmanager
from mitmproxy import options
from mitmproxy import controller
from mitmproxy import eventsequence
from mitmproxy import exceptions
from mitmproxy import command
from mitmproxy import http
from mitmproxy import log
from mitmproxy.net import server_spec
from mitmproxy.proxy.protocol import http_replay
from mitmproxy.types import basethread

from . import ctx as mitmproxy_ctx


class ServerThread(basethread.BaseThread):
    def __init__(self, server):
        self.server = server
        address = getattr(self.server, "address", None)
        super().__init__(
            "ServerThread ({})".format(repr(address))
        )

    def run(self):
        self.server.serve_forever()


class Master:
    """
        The master handles mitmproxy's main event loop.
    """
    def __init__(self, opts):
        self.options = opts or options.Options()  # type: options.Options
        self.commands = command.CommandManager(self)
        self.addons = addonmanager.AddonManager(self)
        self.event_queue = queue.Queue()
        self.should_exit = threading.Event()
        self._server = None
        self.first_tick = True

    @property
    def server(self):
        return self._server

    @server.setter
    def server(self, server):
        server.set_channel(
            controller.Channel(self.event_queue, self.should_exit)
        )
        self._server = server

    @contextlib.contextmanager
    def handlecontext(self):
        # Handlecontexts also have to nest - leave cleanup to the outermost
        if mitmproxy_ctx.master:
            yield
            return
        mitmproxy_ctx.master = self
        mitmproxy_ctx.log = log.Log(self)
        mitmproxy_ctx.options = self.options
        try:
            yield
        finally:
            mitmproxy_ctx.master = None
            mitmproxy_ctx.log = None
            mitmproxy_ctx.options = None

    def tell(self, mtype, m):
        m.reply = controller.DummyReply()
        self.event_queue.put((mtype, m))

    def add_log(self, e, level):
        """
            level: debug, info, warn, error
        """
        self.addons.trigger("log", log.LogEntry(e, level))

    def start(self):
        self.should_exit.clear()
        if self.server:
            ServerThread(self.server).start()

    def run(self):
        self.start()
        try:
            while not self.should_exit.is_set():
                self.tick(0.1)
        finally:
            self.shutdown()

    def tick(self, timeout):
        if self.first_tick:
            self.first_tick = False
            self.addons.trigger("running")
        self.addons.trigger("tick")
        changed = False
        try:
            mtype, obj = self.event_queue.get(timeout=timeout)
            if mtype not in eventsequence.Events:
                raise exceptions.ControlException(
                    "Unknown event %s" % repr(mtype)
                )
            self.addons.handle_lifecycle(mtype, obj)
            self.event_queue.task_done()
            changed = True
        except queue.Empty:
            pass
        return changed

    def shutdown(self):
        if self.server:
            self.server.shutdown()
        self.should_exit.set()
        self.addons.trigger("done")

    def load_flow(self, f):
        """
        Loads a flow
        """
        if isinstance(f, http.HTTPFlow):
            if self.options.mode.startswith("reverse:"):
                _, upstream_spec = server_spec.parse_with_mode(self.options.mode)
                f.request.host, f.request.port = upstream_spec.address
                f.request.scheme = upstream_spec.scheme
        f.reply = controller.DummyReply()
        for e, o in eventsequence.iterate(f):
            self.addons.handle_lifecycle(e, o)

    def replay_request(
            self,
            f: http.HTTPFlow,
            block: bool=False
    ) -> http_replay.RequestReplayThread:
        """
        Replay a HTTP request to receive a new response from the server.

        Args:
            f: The flow to replay.
            block: If True, this function will wait for the replay to finish.
                This causes a deadlock if activated in the main thread.

        Returns:
            The thread object doing the replay.

        Raises:
            exceptions.ReplayException, if the flow is in a state
            where it is ineligible for replay.
        """

        if f.live:
            raise exceptions.ReplayException(
                "Can't replay live flow."
            )
        if f.intercepted:
            raise exceptions.ReplayException(
                "Can't replay intercepted flow."
            )
        if not f.request:
            raise exceptions.ReplayException(
                "Can't replay flow with missing request."
            )
        if f.request.raw_content is None:
            raise exceptions.ReplayException(
                "Can't replay flow with missing content."
            )

        f.backup()
        f.request.is_replay = True

        f.response = None
        f.error = None

        if f.request.http_version == "HTTP/2.0":  # https://github.com/mitmproxy/mitmproxy/issues/2197
            f.request.http_version = "HTTP/1.1"
            host = f.request.headers.pop(":authority")
            f.request.headers.insert(0, "host", host)

        rt = http_replay.RequestReplayThread(
            self.options,
            f,
            self.event_queue,
            self.should_exit
        )
        rt.start()  # pragma: no cover
        if block:
            rt.join()
        return rt