Close the socket when connection setup fails or is cancelled
MA
12d ago+42+42+01234567890123456789-18-18-01234567890123456789
Summary
When connection setup fails after the socket is opened, the network backends can leave the socket open:
start_tlsclosed the stream only onException, so a cancelled handshake (asyncio.CancelledError,trio.Cancelled, orgevent.Timeoutwith the sync backend) left the TCP socket open.TrioStream.start_tlsalso builttrio.SSLStreambefore thetry, so an error fromwrap_bio, for example on a malformedsni_hostname, leaked the socket as well.connect_tcpandconnect_unix_socketdidn't close the socket whensetsockoptraised for asocket_optionsentry. The error surfaces asConnectError, and withretriesconfigured every attempt leaks another socket.SyncBackend.connect_unix_socketdidn't close the socket whenconnect()failed, for example when the socket path doesn't exist.
Each of these now closes the socket and re-raises, catching BaseException like the existing cleanup in http11.py and connection_pool.py. In the anyio and trio backends the setsockopt cleanup runs outside fail_after, so a deadline that expires right after connecting can't turn the ConnectError into a ConnectTimeout.
No tests were added: like the existing start_tls failure handling, the new cleanup branches are marked # pragma: no cover.
Checklist
- I understand that this PR may be closed in case there was no previous discussion. (This doesn't apply to typos!)
- I've added a test for each change that was introduced, and I tried as much as possible to make a single atomic change.
- I've updated the documentation accordingly.