From 1f6635c1fc5ebc9a629a4b5b572aef73e749bae1 Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Mon, 28 May 2018 15:19:59 +0200 Subject: [PATCH] fix shutdown on Windows This fixes #3133. --- mitmproxy/master.py | 10 +++++++++- mitmproxy/tools/main.py | 12 +++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/mitmproxy/master.py b/mitmproxy/master.py index 20ac6acd5..ecb8090bb 100644 --- a/mitmproxy/master.py +++ b/mitmproxy/master.py @@ -119,7 +119,15 @@ class Master: """ if not self.should_exit.is_set(): self.should_exit.set() - asyncio.run_coroutine_threadsafe(self._shutdown(), loop = self.channel.loop) + ret = asyncio.run_coroutine_threadsafe(self._shutdown(), loop=self.channel.loop) + # Weird band-aid to make sure that self._shutdown() is actually executed, + # which otherwise hangs the process as the proxy server is threaded. + # This all needs to be simplified when the proxy server runs on asyncio as well. + if not self.channel.loop.is_running(): # pragma: no cover + try: + self.channel.loop.run_until_complete(asyncio.wrap_future(ret)) + except RuntimeError: + pass # Event loop stopped before Future completed. def _change_reverse_host(self, f): """ diff --git a/mitmproxy/tools/main.py b/mitmproxy/tools/main.py index 789bef636..acae9ee33 100644 --- a/mitmproxy/tools/main.py +++ b/mitmproxy/tools/main.py @@ -119,9 +119,6 @@ def run( if extra: opts.update(**extra(args)) - def cleankill(*args, **kwargs): - master.shutdown() - signal.signal(signal.SIGTERM, cleankill) loop = asyncio.get_event_loop() for signame in ('SIGINT', 'SIGTERM'): try: @@ -129,6 +126,15 @@ def run( except NotImplementedError: # Not supported on Windows pass + + # Make sure that we catch KeyboardInterrupts on Windows. + # https://stackoverflow.com/a/36925722/934719 + if os.name == "nt": + async def wakeup(): + while True: + await asyncio.sleep(0.2) + asyncio.ensure_future(wakeup()) + master.run() except exceptions.OptionsError as e: print("%s: %s" % (sys.argv[0], e), file=sys.stderr)