Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
02ab78d
Example addon for saving streamed data including a small bug fix to m…
EndUser509 Jan 18, 2022
94367fa
Revert "Example addon for saving streamed data including a small bug …
EndUser509 Jan 18, 2022
adc6402
Merge branch 'mitmproxy:main' into master
EndUser509 Jan 22, 2022
b4df53e
Merge branch 'mitmproxy:main' into master
EndUser509 Jan 26, 2022
192cb80
Add https_ping_threshold option to enable keep-alive for HTTP/2 serve…
EndUser509 Feb 18, 2022
d18344b
Fixed test
EndUser509 Feb 18, 2022
015f2bd
Fix test
EndUser509 Feb 18, 2022
daf94da
Adding pragma
EndUser509 Feb 18, 2022
ced840b
Moved timer logic to _http2.py
EndUser509 Mar 20, 2022
935da9f
Merge branch 'main' into http2_keepalive
EndUser509 Mar 20, 2022
824be48
Small code improvement
EndUser509 Mar 20, 2022
7463718
Merge branch 'http2_keepalive' of github.com:EndUser509/mitmproxy int…
EndUser509 Mar 20, 2022
00491ac
Update mitmproxy/options.py
EndUser509 Mar 22, 2022
d6e4396
Update mitmproxy/options.py
EndUser509 Mar 22, 2022
4af9144
Update mitmproxy/proxy/commands.py
EndUser509 Mar 22, 2022
ac74eb1
Update mitmproxy/proxy/commands.py
EndUser509 Mar 22, 2022
8f8f9ed
Update mitmproxy/proxy/layers/http/_http2.py
EndUser509 Mar 22, 2022
301066c
Sending Wakup back to right client
EndUser509 Apr 8, 2022
7069fc0
Update mitmproxy/proxy/server.py
EndUser509 Apr 10, 2022
c6977c2
Update mitmproxy/proxy/server.py
EndUser509 Apr 10, 2022
b6fde2a
Update mitmproxy/proxy/server.py
EndUser509 Apr 10, 2022
ccdc66c
Incorporated suggested changes
EndUser509 Apr 10, 2022
8683c56
make `Wakeup` a `CommandCompleted` event.
mhils Apr 22, 2022
bece08f
nits
mhils Apr 22, 2022
eebf37b
Merge remote-tracking branch 'origin/main' into pr-5144
mhils Apr 22, 2022
f9e283b
nits nits
mhils Apr 22, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

* Replayed flows retain their current position in the flow list.
([#5227](https://github.com/mitmproxy/mitmproxy/issues/5227), @mhils)
* Periodically send HTTP/2 ping frames to keep connections alive.
([#5046](https://github.com/mitmproxy/mitmproxy/issues/5046), @EndUser509)
* Console Performance Improvements
([#3427](https://github.com/mitmproxy/mitmproxy/issues/3427), @BkPHcgQL3V)
* Warn users if server side event responses are received without streaming.
Expand All @@ -24,7 +26,8 @@
([#4278](https://github.com/mitmproxy/mitmproxy/issues/4278), @kjy00302)
* Fix mitmweb export copy failed in non-secure domain.
([#5264](https://github.com/mitmproxy/mitmproxy/issues/5264), @Pactortester)
* Added example script for manipulating cookies. (@WillahScott)
* Added example script for manipulating cookies.
([#5278](https://github.com/mitmproxy/mitmproxy/issues/5278), @WillahScott)

## 19 March 2022: mitmproxy 8.0.0

Expand Down
8 changes: 8 additions & 0 deletions mitmproxy/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,14 @@ def __init__(self, **kwargs) -> None:
"Enable/disable HTTP/2 support. "
"HTTP/2 support is enabled by default.",
)
self.add_option(
"http2_ping_keepalive", int, 58,
"""
Send a PING frame if an HTTP/2 connection is idle for more than
the specified number of seconds to prevent the remote site from closing it.
Set to 0 to disable this feature.
"""
)
self.add_option(
"websocket", bool, True,
"Enable/disable WebSocket support. "
Expand Down
10 changes: 10 additions & 0 deletions mitmproxy/proxy/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ def __repr__(self):
return f"{type(self).__name__}({repr(x)})"


class RequestWakeup(Command):
"""
Request a `Wakeup` event after the specified amount of seconds.
"""
delay: float

def __init__(self, delay: float):
self.delay = delay


class ConnectionCommand(Command):
"""
Commands involving a specific connection
Expand Down
8 changes: 8 additions & 0 deletions mitmproxy/proxy/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,11 @@ class MessageInjected(Event, typing.Generic[T]):
"""
flow: flow.Flow
message: T


@dataclass
class Wakeup(CommandCompleted):
"""
Event sent to layers that requested a wakeup using RequestWakeup.
"""
command: commands.RequestWakeup
5 changes: 4 additions & 1 deletion mitmproxy/proxy/layers/http/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,9 @@ def _handle_event(self, event: events.Event):
yield from self.event_to_child(self.connections[self.context.client], event)
if self.mode is HTTPMode.upstream:
self.context.server.via = server_spec.parse_with_mode(self.context.options.mode)[1]
elif isinstance(event, events.Wakeup):
stream = self.command_sources.pop(event.command)
yield from self.event_to_child(stream, event)
elif isinstance(event, events.CommandCompleted):
stream = self.command_sources.pop(event.command)
yield from self.event_to_child(stream, event)
Expand Down Expand Up @@ -765,7 +768,7 @@ def event_to_child(
# Streams may yield blocking commands, which ultimately generate CommandCompleted events.
# Those need to be routed back to the correct stream, so we need to keep track of that.

if command.blocking:
if command.blocking or isinstance(command, commands.RequestWakeup):
self.command_sources[command] = child

if isinstance(command, ReceiveHttp):
Expand Down
33 changes: 29 additions & 4 deletions mitmproxy/proxy/layers/http/_http2.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@
ResponseEndOfMessage, ResponseHeaders, RequestTrailers, ResponseTrailers, ResponseProtocolError
from ._base import HttpConnection, HttpEvent, ReceiveHttp, format_error
from ._http_h2 import BufferedH2Connection, H2ConnectionLogger
from ...commands import CloseConnection, Log, SendData
from ...commands import CloseConnection, Log, SendData, RequestWakeup
from ...context import Context
from ...events import ConnectionClosed, DataReceived, Event, Start
from ...events import ConnectionClosed, DataReceived, Event, Start, Wakeup
from ...layer import CommandGenerator
from ...utils import expect

Expand Down Expand Up @@ -252,7 +252,7 @@ def close_connection(self, msg: str) -> CommandGenerator[None]:
self.streams.clear()
self._handle_event = self.done # type: ignore

@expect(DataReceived, HttpEvent, ConnectionClosed)
@expect(DataReceived, HttpEvent, ConnectionClosed, Wakeup)
def done(self, _) -> CommandGenerator[None]:
yield from ()

Expand Down Expand Up @@ -358,6 +358,8 @@ class Http2Client(Http2Connection):
"""Queue of streams that we haven't sent yet because we have reached MAX_CONCURRENT_STREAMS"""
provisional_max_concurrency: Optional[int] = 10
"""A provisional currency limit before we get the server's first settings frame."""
last_activity: float
"""Timestamp of when we've last seen network activity on this connection."""

def __init__(self, context: Context):
super().__init__(context, context.server)
Expand Down Expand Up @@ -407,7 +409,30 @@ def _handle_event(self, event: Event) -> CommandGenerator[None]:
yield from self._handle_event(event)

def _handle_event2(self, event: Event) -> CommandGenerator[None]:
if isinstance(event, RequestHeaders):
if isinstance(event, Wakeup):
send_ping_now = (
# add one second to avoid unnecessary roundtrip, we don't need to be super correct here.
time.time() - self.last_activity + 1 > self.context.options.http2_ping_keepalive
)
if send_ping_now:
# PING frames MUST contain 8 octets of opaque data in the payload.
# A sender can include any value it chooses and use those octets in any fashion.
self.last_activity = time.time()
self.h2_conn.ping(b"0" * 8)
Comment thread
EndUser509 marked this conversation as resolved.
Resolved
data = self.h2_conn.data_to_send()
if data is not None:
yield Log(f"Send HTTP/2 keep-alive PING to {human.format_address(self.conn.peername)}")
yield SendData(self.conn, data)
time_until_next_ping = self.context.options.http2_ping_keepalive - (time.time() - self.last_activity)
yield RequestWakeup(time_until_next_ping)
return

self.last_activity = time.time()
if isinstance(event, Start):
if self.context.options.http2_ping_keepalive > 0:
yield RequestWakeup(self.context.options.http2_ping_keepalive)
yield from super()._handle_event(event)
elif isinstance(event, RequestHeaders):
pseudo_headers = [
(b':method', event.request.data.method),
(b':scheme', event.request.data.scheme),
Expand Down
20 changes: 20 additions & 0 deletions mitmproxy/proxy/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,13 @@ class ConnectionHandler(metaclass=abc.ABCMeta):
client: Client
max_conns: typing.DefaultDict[Address, asyncio.Semaphore]
layer: layer.Layer
wakeup_timer: typing.Set[asyncio.Task]

def __init__(self, context: Context) -> None:
self.client = context.client
self.transports = {}
self.max_conns = collections.defaultdict(lambda: asyncio.Semaphore(5))
self.wakeup_timer = set()

# Ask for the first layer right away.
# In a reverse proxy scenario, this is necessary as we would otherwise hang
Expand Down Expand Up @@ -120,6 +122,9 @@ async def handle_client(self) -> None:
await asyncio.wait([handler])

watch.cancel()
while self.wakeup_timer:
timer = self.wakeup_timer.pop()
timer.cancel()

self.log("client disconnect")
self.client.timestamp_end = time.time()
Expand Down Expand Up @@ -199,6 +204,13 @@ async def open_connection(self, command: commands.OpenConnection) -> None:
command.connection.timestamp_end = time.time()
await self.handle_hook(server_hooks.ServerDisconnectedHook(hook_data))

async def wakeup(self, request: commands.RequestWakeup) -> None:
await asyncio.sleep(request.delay)
task = asyncio.current_task()
assert task is not None
self.wakeup_timer.discard(task)
self.server_event(events.Wakeup(request))

async def handle_connection(self, connection: Connection) -> None:
"""
Handle a connection for its entire lifetime.
Expand Down Expand Up @@ -297,6 +309,14 @@ def server_event(self, event: events.Event) -> None:
client=self.client.peername,
)
self.transports[command.connection] = ConnectionIO(handler=handler)
elif isinstance(command, commands.RequestWakeup):
task = asyncio_utils.create_task(
self.wakeup(command),
name=f"wakeup timer ({command.delay:.1f}s)",
client=self.client.peername
)
assert task is not None
self.wakeup_timer.add(task)
elif isinstance(command, commands.ConnectionCommand) and command.connection not in self.transports:
pass # The connection has already been closed.
elif isinstance(command, commands.SendData):
Expand Down
68 changes: 66 additions & 2 deletions test/mitmproxy/proxy/layers/http/test_http2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
import hpack
import hyperframe.frame
import pytest
import time
from h2.errors import ErrorCodes

from mitmproxy.connection import ConnectionState, Server
from mitmproxy.flow import Error
from mitmproxy.http import HTTPFlow, Headers, Request
from mitmproxy.net.http import status_codes
from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData
from mitmproxy.proxy.commands import CloseConnection, Log, OpenConnection, SendData, RequestWakeup
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.events import ConnectionClosed, DataReceived
from mitmproxy.proxy.layers import http
Expand Down Expand Up @@ -64,8 +65,9 @@ def decode_frames(data: bytes) -> List[hyperframe.frame.Frame]:
return frames


def start_h2_client(tctx: Context) -> Tuple[Playbook, FrameFactory]:
def start_h2_client(tctx: Context, keepalive: int = 0) -> Tuple[Playbook, FrameFactory]:
tctx.client.alpn = b"h2"
tctx.options.http2_ping_keepalive = keepalive
frame_factory = FrameFactory()

playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))
Expand Down Expand Up @@ -679,6 +681,7 @@ def kill(flow: HTTPFlow):

class TestClient:
def test_no_data_on_closed_stream(self, tctx):
tctx.options.http2_ping_keepalive = 0
frame_factory = FrameFactory()
req = Request.make("GET", "http://example.com/")
resp = {
Expand Down Expand Up @@ -780,3 +783,64 @@ def test_request_smuggling_te(tctx):
<< CloseConnection(tctx.client)
)
assert b"Connection-specific header field present" in err()


def test_request_keepalive(tctx, monkeypatch):
playbook, cff = start_h2_client(tctx, 58)
flow = Placeholder(HTTPFlow)
server = Placeholder(Server)
initial = Placeholder(bytes)

def advance_time(_):
t = time.time()
monkeypatch.setattr(time, "time", lambda: t + 60)

assert (
playbook
>> DataReceived(tctx.client,
cff.build_headers_frame(example_request_headers, flags=["END_STREAM"]).serialize())
<< http.HttpRequestHeadersHook(flow)
>> reply()
<< http.HttpRequestHook(flow)
>> reply()
<< OpenConnection(server)
>> reply(None, side_effect=make_h2)
<< RequestWakeup(58)
<< SendData(server, initial)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should emulate a Wakeup event here and make sure that it triggers a PING. :-)

def test_request_keepalive(monkeypatch, tctx):
    ...
    assert (playbook ...)
    t = time.time()
    monkeypatch.setattr(time, "time", lambda: t + 60)
    assert (playbook >> Wakeup() ...)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do this at the very end, when the rest is working. :)

>> reply(to=-2, side_effect=advance_time)
<< SendData(server, b'\x00\x00\x08\x06\x00\x00\x00\x00\x0000000000') # ping frame
<< RequestWakeup(58)
)


def test_keepalive_disconnect(tctx, monkeypatch):
playbook, cff = start_h2_client(tctx, 58)
playbook.hooks = False
sff = FrameFactory()
server = Placeholder(Server)
wakeup_command = RequestWakeup(58)

http_response = (
sff.build_headers_frame(example_response_headers).serialize() +
sff.build_data_frame(b"", flags=["END_STREAM"]).serialize()
)

def advance_time(_):
t = time.time()
monkeypatch.setattr(time, "time", lambda: t + 60)

assert (
playbook
>> DataReceived(tctx.client,
cff.build_headers_frame(example_request_headers, flags=["END_STREAM"]).serialize())
<< OpenConnection(server)
>> reply(None, side_effect=make_h2)
<< wakeup_command
<< SendData(server, Placeholder(bytes))
>> DataReceived(server, http_response)
<< SendData(tctx.client, Placeholder(bytes))
>> ConnectionClosed(server)
<< CloseConnection(server)
>> reply(to=wakeup_command, side_effect=advance_time)
<< None
)
1 change: 1 addition & 0 deletions test/mitmproxy/proxy/layers/http/test_http_fuzz.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ def h2_frames(draw):

def h2_layer(opts):
tctx = context.Context(connection.Client(("client", 1234), ("127.0.0.1", 8080), 1605699329), opts)
tctx.options.http2_ping_keepalive = 0
tctx.client.alpn = b"h2"

layer = http.HttpLayer(tctx, HTTPMode.regular)
Expand Down
2 changes: 2 additions & 0 deletions test/mitmproxy/proxy/layers/http/test_http_version_interop.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def event_types(events):

def h2_client(tctx: Context) -> Tuple[h2.connection.H2Connection, Playbook]:
tctx.client.alpn = b"h2"
tctx.options.http2_ping_keepalive = 0

playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))
conn = h2.connection.H2Connection()
Expand Down Expand Up @@ -89,6 +90,7 @@ def test_h1_to_h2(tctx):
"""Test HTTP/1 -> HTTP/2 request translation"""
server = Placeholder(Server)
flow = Placeholder(HTTPFlow)
tctx.options.http2_ping_keepalive = 0

playbook = Playbook(http.HttpLayer(tctx, HTTPMode.regular))

Expand Down
1 change: 1 addition & 0 deletions test/mitmproxy/proxy/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ def tconn() -> connection.Server:


def test_dataclasses(tconn):
assert repr(commands.RequestWakeup(58))
assert repr(commands.SendData(tconn, b"foo"))
assert repr(commands.OpenConnection(tconn))
assert repr(commands.CloseConnection(tconn))
Expand Down
2 changes: 2 additions & 0 deletions web/src/js/ducks/_options_gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export interface OptionsState {
content_view_lines_cutoff: number
export_preserve_original_ip: boolean
http2: boolean
http2_ping_keepalive: number
ignore_hosts: string[]
intercept: string | undefined
intercept_active: boolean
Expand Down Expand Up @@ -110,6 +111,7 @@ export const defaultState: OptionsState = {
content_view_lines_cutoff: 512,
export_preserve_original_ip: false,
http2: true,
http2_ping_keepalive: 58,
ignore_hosts: [],
intercept: undefined,
intercept_active: false,
Expand Down