re-add WebSocket injection example

This commit is contained in:
Maximilian Hils 2021-03-14 00:48:39 +01:00
parent c842abff2d
commit 6c07dba752
2 changed files with 32 additions and 0 deletions

View File

@ -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))

View File

@ -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)