mitmproxy/mitmproxy/eventsequence.py

97 lines
2.1 KiB
Python
Raw Normal View History

2017-07-15 10:22:46 +00:00
import typing
from mitmproxy import controller
from mitmproxy import flow
2017-07-20 14:27:13 +00:00
from mitmproxy import http
from mitmproxy import tcp
2016-11-13 16:50:51 +00:00
from mitmproxy import websocket
Events = frozenset([
"clientconnect",
"clientdisconnect",
"serverconnect",
"serverdisconnect",
# TCP
"tcp_start",
"tcp_message",
"tcp_error",
"tcp_end",
# HTTP
"http_connect",
"request",
"requestheaders",
"response",
"responseheaders",
"error",
# WebSocket
"websocket_handshake",
2016-11-13 16:50:51 +00:00
"websocket_start",
"websocket_message",
"websocket_error",
"websocket_end",
# misc
"next_layer",
"configure",
"done",
"log",
2017-03-23 21:15:41 +00:00
"load",
"running",
"tick",
"update",
])
2017-07-20 14:27:13 +00:00
TEventGenerator = typing.Iterator[typing.Tuple[str, typing.Any]]
2017-07-20 14:27:13 +00:00
def _iterate_http(f: http.HTTPFlow) -> TEventGenerator:
2017-07-15 10:22:46 +00:00
if f.request:
yield "requestheaders", f
yield "request", f
if f.response:
yield "responseheaders", f
yield "response", f
if f.error:
yield "error", f
2017-07-20 14:27:13 +00:00
def _iterate_websocket(f: websocket.WebSocketFlow) -> TEventGenerator:
2017-07-15 10:22:46 +00:00
messages = f.messages
f.messages = []
f.reply = controller.DummyReply()
yield "websocket_start", f
while messages:
f.messages.append(messages.pop(0))
yield "websocket_message", f
if f.error:
yield "websocket_error", f
yield "websocket_end", f
2017-07-20 14:27:13 +00:00
def _iterate_tcp(f: tcp.TCPFlow) -> TEventGenerator:
2017-07-15 10:22:46 +00:00
messages = f.messages
f.messages = []
f.reply = controller.DummyReply()
yield "tcp_start", f
while messages:
f.messages.append(messages.pop(0))
yield "tcp_message", f
if f.error:
yield "tcp_error", f
yield "tcp_end", f
_iterate_map = {
2017-07-15 10:22:46 +00:00
http.HTTPFlow: _iterate_http,
websocket.WebSocketFlow: _iterate_websocket,
2017-07-20 14:27:13 +00:00
tcp.TCPFlow: _iterate_tcp,
} # type: typing.Dict[typing.Type[flow.Flow], typing.Callable[[typing.Any], TEventGenerator]]
2017-07-15 10:22:46 +00:00
def iterate(f: flow.Flow) -> TEventGenerator:
try:
e = _iterate_map[type(f)]
2017-07-20 14:27:13 +00:00
except KeyError as err:
raise TypeError("Unknown flow type: {}".format(f)) from err
else:
2017-07-15 10:22:46 +00:00
yield from e(f)