Skip to content

Commit da99b46

Browse files
If TLS fails, then close the socket (#475)
1 parent 55d03fc commit da99b46

3 files changed

Lines changed: 26 additions & 12 deletions

File tree

httpcore/backends/asyncio.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,18 @@ async def start_tls(
5858
anyio.BrokenResourceError: ConnectError,
5959
}
6060
with map_exceptions(exc_map):
61-
with anyio.fail_after(timeout):
62-
ssl_stream = await anyio.streams.tls.TLSStream.wrap(
63-
self._stream,
64-
ssl_context=ssl_context,
65-
hostname=server_hostname,
66-
standard_compatible=False,
67-
server_side=False,
68-
)
61+
try:
62+
with anyio.fail_after(timeout):
63+
ssl_stream = await anyio.streams.tls.TLSStream.wrap(
64+
self._stream,
65+
ssl_context=ssl_context,
66+
hostname=server_hostname,
67+
standard_compatible=False,
68+
server_side=False,
69+
)
70+
except Exception as exc: # pragma: nocover
71+
await self.aclose()
72+
raise exc
6973
return AsyncIOStream(ssl_stream)
7074

7175
def get_extra_info(self, info: str) -> typing.Any:

httpcore/backends/sync.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,14 @@ def start_tls(
4747
) -> NetworkStream:
4848
exc_map = {socket.timeout: ConnectTimeout, socket.error: ConnectError}
4949
with map_exceptions(exc_map):
50-
self._sock.settimeout(timeout)
51-
sock = ssl_context.wrap_socket(self._sock, server_hostname=server_hostname)
50+
try:
51+
self._sock.settimeout(timeout)
52+
sock = ssl_context.wrap_socket(
53+
self._sock, server_hostname=server_hostname
54+
)
55+
except Exception as exc: # pragma: nocover
56+
self.close()
57+
raise exc
5258
return SyncStream(sock)
5359

5460
def get_extra_info(self, info: str) -> typing.Any:

httpcore/backends/trio.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,12 @@ async def start_tls(
6161
server_side=False,
6262
)
6363
with map_exceptions(exc_map):
64-
with trio.fail_after(timeout_or_inf):
65-
await ssl_stream.do_handshake()
64+
try:
65+
with trio.fail_after(timeout_or_inf):
66+
await ssl_stream.do_handshake()
67+
except Exception as exc: # pragma: nocover
68+
await self.aclose()
69+
raise exc
6670
return TrioStream(ssl_stream)
6771

6872
def get_extra_info(self, info: str) -> typing.Any:

0 commit comments

Comments
 (0)