From 6c07dba752ffa1899ddc9e0ee0ede401f1c7f13a Mon Sep 17 00:00:00 2001 From: Maximilian Hils Date: Sun, 14 Mar 2021 00:48:39 +0100 Subject: [PATCH] re-add WebSocket injection example --- examples/addons/websocket-inject-message.py | 31 +++++++++++++++++++++ mitmproxy/addons/proxyserver.py | 1 + 2 files changed, 32 insertions(+) create mode 100644 examples/addons/websocket-inject-message.py diff --git a/examples/addons/websocket-inject-message.py b/examples/addons/websocket-inject-message.py new file mode 100644 index 000000000..012d4b27e --- /dev/null +++ b/examples/addons/websocket-inject-message.py @@ -0,0 +1,31 @@ +""" +Inject a WebSocket message into a running connection. + +This example shows how to inject a WebSocket message into a running connection. +""" +import asyncio + +from mitmproxy import ctx, http + + +# Simple example: Inject a message as a response to an event + +def websocket_message(flow): + last_message = flow.websocket.messages[-1] + if b"secret" in last_message.content: + last_message.kill() + ctx.master.commands.call("inject", [flow], not last_message.from_client, "ssssssh") + + +# Complex example: Schedule a periodic timer + +async def inject_async(flow: http.HTTPFlow): + msg = "hello from mitmproxy! " + while flow.server_conn.connected: + ctx.master.commands.call("inject", [flow], False, msg) + await asyncio.sleep(1) + msg = msg[1:] + msg[:1] + + +def websocket_start(flow: http.HTTPFlow): + asyncio.create_task(inject_async(flow)) diff --git a/mitmproxy/addons/proxyserver.py b/mitmproxy/addons/proxyserver.py index 3922c4826..9ec1c176a 100644 --- a/mitmproxy/addons/proxyserver.py +++ b/mitmproxy/addons/proxyserver.py @@ -168,6 +168,7 @@ class Proxyserver: event = TcpMessageInjected(f, tcp.TCPMessage(from_client, message_bytes)) else: # pragma: no cover ctx.log.warn(f"Cannot inject message into {f.__class__.__name__}, skipping.") + continue try: self.inject_event(f, event)