aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/script/concurrent.py
blob: b81f2ab158e7687560b93ddf78ce9e8547bb01cb (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
"""
This module provides a @concurrent decorator primitive to
offload computations from mitmproxy's main master thread.
"""
from __future__ import absolute_import, print_function, division

from mitmproxy import controller
import threading


class ReplyProxy(object):

    def __init__(self, reply_func, script_thread):
        self.reply_func = reply_func
        self.script_thread = script_thread
        self.master_reply = None

    def send(self, message):
        if self.master_reply is None:
            self.master_reply = message
            self.script_thread.start()
            return
        self.reply_func(message)

    def done(self):
        self.reply_func.send(self.master_reply)

    def __getattr__(self, k):
        return getattr(self.reply_func, k)


def _handle_concurrent_reply(fn, o, *args, **kwargs):
    # Make first call to o.reply a no op and start the script thread.
    # We must not start the script thread before, as this may lead to a nasty race condition
    # where the script thread replies a different response before the normal reply, which then gets swallowed.

    def run():
        fn(*args, **kwargs)
        # If the script did not call .reply(), we have to do it now.
        reply_proxy.done()

    script_thread = ScriptThread(target=run)

    reply_proxy = ReplyProxy(o.reply, script_thread)
    o.reply = reply_proxy


class ScriptThread(threading.Thread):
    name = "ScriptThread"


def concurrent(fn):
    if fn.__name__ not in controller.Events:
        raise NotImplementedError(
            "Concurrent decorator not supported for '%s' method." % fn.__name__
        )

    def _concurrent(ctx, obj):
        _handle_concurrent_reply(fn, obj, ctx, obj)
    return _concurrent