Repository navigation
Description
Problem Description
I have noticed that web browsers sometimes stall loading images or pages. I get it both on an iPad with Safari and a Fedora with Firefox. It especially happens with pass-through connections but also without.
I think I have tracked down the bug to mitmproxy/proxy/server.py where in ConnectionHandler.handle_connection() there is the following loop:
while True:
try:
data = await reader.read(65535)
if not data:
raise OSError("Connection closed by peer.")
except OSError:
break
except asyncio.CancelledError as e:
cancelled = e
break
else:
self.server_event(events.DataReceived(connection, data))
for transport in self.transports.values():
if transport.writer is not None:
await transport.writer.drain()
The final drain() can actually throw and if it does all the connection management following the loop is not properly done, leaving the connection in a strange state. My suggested fix that made it work without further hick-ups for me is this:
reader = self.transports[connection].reader
writer = self.transports[connection].writer
assert reader
assert writer
while True:
...
else:
self.server_event(events.DataReceived(connection, data))
for transport in self.transports.values():
if transport.writer is not None:
try:
await transport.writer.drain()
except OSError as e:
if transport.writer == writer:
cancelled = e
break
else:
continue
break
Steps to reproduce the behavior:
- Start mitmdump as transparent proxy with '--ignore-hosts .com'
- Go to apple.com
- Quickly click on links, attempt to abort a page load with a re-load of the same page
System Information
Mitmproxy: 8.0.0.dev (+200, commit ef8c88d)
Python: 3.9.7
OpenSSL: OpenSSL 1.1.1m 14 Dec 2021
Platform: Linux-4.18.0-348.2.1.el8_5.x86_64-x86_64-with-glibc2.28
Activity
mhils commentedon Jan 6, 2022
Honestly I was dreading to even open this issue after reading "Client sometimes ..." in the title, but turns out there is a positive surprise in here. 😁 This is super super interesting, thank you very much! 🍰
.drain()to raise on my system, but that might be OS-specific. Out of interest, would you mind posting the full OSErrorrepr()here?EndUser509 commentedon Jan 6, 2022
Thanks for looking into this! Apart from this issue the new sansio design rocks! I can even scroll around in Google Maps and the CPU usage of the proxy machine remains in the one digit range. With V4 this was laggy with >100% load. Cool.
When I log a
repr(e)when drain() raises an exception then the log entry reads:ConnectionResetError('Connection lost')Out of curiosity I also added an
except asyncio.CancelledError as e:afterdrain()and that also sometimes catches an exception (meaning my fix wasn't complete...):CancelledError('client disconnected')I wonder what it takes to reproduce this on your side. I run mitmdump in transparent mode (easy for me to add and remove my machines), from the git repo directly on a CentOS 8 Stream on a laptop. Basically it provides a gateway from my WIFI network to the ADSL router.
The hard way, with tcpdump/wireshark,
--set proxy_debug=trueand puttingself.log()all over the place in server.py. With tcpdump I noticed that when a page load stalled that I could still tap on links and that the browser then still sent data to the proxy after that transport has been closed (HTTP/2 does that) so it had to be the stream management at a low level. I also noticed that for the connection that stalled, the log entryclient disconnectinConnectionHandler()afterwatch.cancel()was missing for that connection. After narrowing down this far I started insertingself.log()until I found that the one afterdrain()sometimes was not logging.What also helped me on the way was to add this to my script:
I just tried this variant a bit. It made it worse for pass-through connections (apple.com on my iPad). After the first or second click already the connection stalls consistently. I guess the approach is too aggressive.
For normal HTTP/2 connections it worked OK but I did get a 502 Bad Gateway when reading heise.de after a few pages. The
error()in my script logged:I do not fully understand the code in server.py, for instance, why there is a need to drain all writers, not just the one from this connection. I am not strongly advocating my solution, so far it is just the most solid for me, even if I apparently missed the
CancelErrors. If you have more suggestions then I will try them out, this is dead easy for me to reproduce. Which still worries me, apparenly nobody else had this issue so far... :)mhils commentedon Jan 6, 2022
Excellent. Very happy to hear that. 😃
That's helpful, thanks. My main driver is a Windows machine in regular mode, so that's quite a different stack.
Very impressive! I'm actually somewhat puzzled which part silently swallows the OSError here, I definitely need to figure out why exceptions are ignored and correct that. But let's focus on the initial issue here.
This confused me for a bit, but I think I have a working theory now: When a coroutine/task is cancelled, it continues to run normally until the next
awaitstatement, which throws aCancelledError. What's may be happening here is that we first cancel our very own connection handler task we're currently in, and after that thendrain()another transport. As we have already cancelled our own coroutine thisawait drain()immediately throws aCancelledError, which as you correctly pointed out both of us did not catch before! The problem just happens to be much more visible in my patch.We do that to create backpressure. Assume you have a very fast connection to your laptop, a slower connection upstream, and you want to upload a large file. mitmproxy would very quickly read everything from your local device and then have an immense send buffer for the upstream connection. So while mitmproxy is slowly shoveling bits upstream, your client is done uploading for minutes already, hits a timeout, and aborts the connection1.
Draining the upstream connection aftere each read means we wait for space in the upstream send buffer to be available before we continue reading from the downstream socket again. In other words, while we drain the upstream send buffer, our own downstream receive buffer fills up and the OS' TCP implementation signals to downstream that they need to slow down. Does that make sense?
Here's a revised patch that does catch the CancelledError. Could you test that and see how it works?
Footnotes
I'm assuming a streamed request body (or plain TCP) here. If mitmproxy is told not to stream this issue still exists. ↩
EndUser509 commentedon Jan 7, 2022
I'll reply in full and run extensive tests in the evening. One question though on the new patch that you may be able to answer before that:
That last break, it will only exit the inner loop which does not make sense to me. I would either ignore the exception and continue draining the rest of the writers as well or exit the outer loop with an 'else - continue - break' construct similar to what I used in my patch. Since you set cancelled I guess you want the later.
mhils commentedon Jan 7, 2022
Yes, good catch. Let's break out entirely. :)
mhils commentedon Jan 7, 2022
Here's a revised revised patch that should break out:
EndUser509 commentedon Jan 7, 2022
I have applied this patch and tried various websites, Youtube, Google Maps, etc. and there was not a single delayed load or missing image during my hours of surfing. In the logs I did not see any suspicious server-side errors. So I think the above fix works great.
Thanks for the solution! I keep the patch in my checkout until it is also committed to the main branch. But this issue can be closed I think.
catch cancellation errors when draining writers, fix mitmproxy#5034
Prinzhorn commentedon Jan 8, 2022
@EndUser509 thank you for this excellent detective work 🧐 ! Is there a PayPal or something I can send a coffee to? I want to pavlov high quality contributions 😄
EndUser509 commentedon Jan 9, 2022
Thanks, but it should be the other way round. I am really thankful that this project exists. Helping to fix an issue that I notice is the least I can do. :)
Prinzhorn commentedon Feb 22, 2022
@EndUser509 could you send me an e-mail to the address in my profile?
catch cancellation errors when draining writers, fix mitmproxy#5034 (m…
catch cancellation errors when draining writers, fix mitmproxy#5034 (m…