Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions newsfragments/3581.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
A concurrent task using :class:`trio.SSLStream` no longer hangs forever when the
lazy handshake fails or when the task performing it is cancelled. The waiting
task now raises :exc:`trio.BrokenResourceError`, like any later attempt to use
the stream.
34 changes: 27 additions & 7 deletions src/trio/_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ class NeedHandshakeError(Exception):


class _Once:
__slots__ = ("_afn", "_args", "_done", "started")
__slots__ = ("_afn", "_args", "_done", "_failed", "started")

def __init__(
self,
Expand All @@ -234,21 +234,41 @@ def __init__(
self._afn = afn
self._args = args
self.started = False
self._failed = False
self._done = _sync.Event()

async def ensure(self, *, checkpoint: bool) -> None:
if not self.started:
self.started = True
await self._afn(*self._args)
self._done.set()
elif not checkpoint and self._done.is_set():
try:
await self._afn(*self._args)
except BaseException:
# The operation failed or was cancelled. Wake up any waiters
# so they don't hang forever, and let them know the stream is
# unusable. We deliberately don't store the original exception:
# re-raising it in another task would mutate its traceback and
# could create a reference cycle (#3397).
self._failed = True
raise
finally:
self._done.set()
return
else:
await self._done.wait()

if not checkpoint and self._done.is_set():
if self._failed:
raise trio.BrokenResourceError
return

await self._done.wait()
if self._failed:
raise trio.BrokenResourceError

@property
def done(self) -> bool:
return bool(self._done.is_set())
# Keep this meaning "the operation completed successfully", so that
# e.g. SSLStream's guarded attribute forwarders still raise
# NeedHandshakeError after a failed handshake.
return bool(self._done.is_set()) and not self._failed


_State = _Enum("_State", ["OK", "BROKEN", "CLOSED"])
Expand Down
120 changes: 119 additions & 1 deletion src/trio/_tests/test_ssl.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,15 @@
from .._highlevel_generic import aclose_forcefully
from .._highlevel_open_tcp_stream import open_tcp_stream
from .._highlevel_socket import SocketListener, SocketStream
from .._ssl import NeedHandshakeError, SSLListener, SSLStream, _is_eof
from .._ssl import NeedHandshakeError, SSLListener, SSLStream, _is_eof, _Once
from .._util import ConflictDetector
from ..testing import (
Sequencer,
assert_checkpoints,
check_two_way_stream,
lockstep_stream_pair,
memory_stream_pair,
wait_all_tasks_blocked,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -1237,6 +1238,123 @@ async def client_side(cancel_scope: CancelScope) -> None:
await client.do_handshake()


async def test_concurrent_handshake_failure_wakes_waiter(
client_ctx: SSLContext,
) -> None:
# Regression test for #3581: if the lazy handshake fails, a concurrent
# send_all/receive_some must not wait forever on _Once.
send, recv = memory_stream_pair()
stream = SSLStream(
send,
client_ctx,
server_hostname="trio-test-1.example.org",
)
outcomes: dict[str, BaseException] = {}

async def sender() -> None:
try:
await stream.send_all(b"hello")
except BaseException as exc:
outcomes["sender"] = exc

async def receiver() -> None:
try:
await stream.receive_some()
except BaseException as exc:
outcomes["receiver"] = exc

with trio.fail_after(2):
async with _core.open_nursery() as nursery:
nursery.start_soon(sender)
await wait_all_tasks_blocked()
nursery.start_soon(receiver)
await wait_all_tasks_blocked()
await recv.aclose()

assert isinstance(outcomes["sender"], BrokenResourceError)
assert isinstance(outcomes["receiver"], BrokenResourceError)


async def test_concurrent_handshake_cancellation_wakes_waiter(
client_ctx: SSLContext,
) -> None:
# Regression test for #3581: cancelling the task performing the handshake
# must wake a concurrent waiter instead of leaving it parked forever.
send, _recv = memory_stream_pair()
stream = SSLStream(
send,
client_ctx,
server_hostname="trio-test-1.example.org",
)
outcomes: dict[str, BaseException] = {}
handshake_scope = trio.CancelScope()

async def sender() -> None:
with handshake_scope:
try:
await stream.do_handshake()
except BaseException as exc:
outcomes["sender"] = exc
raise

async def receiver() -> None:
try:
await stream.receive_some()
except BaseException as exc:
outcomes["receiver"] = exc

with trio.fail_after(2):
async with _core.open_nursery() as nursery:
nursery.start_soon(sender)
await wait_all_tasks_blocked()
nursery.start_soon(receiver)
await wait_all_tasks_blocked()
handshake_scope.cancel()

assert isinstance(outcomes["sender"], trio.Cancelled)
assert isinstance(outcomes["receiver"], BrokenResourceError)


async def test_concurrent_handshake_success(client_ctx: SSLContext) -> None:
# The fix for #3581 must not disturb the successful-handshake path, where
# multiple tasks wait on the same _Once and then all proceed.
client, server = ssl_memory_stream_pair(client_ctx)

with trio.fail_after(2):
async with _core.open_nursery() as nursery:
nursery.start_soon(client.do_handshake)
await wait_all_tasks_blocked()
nursery.start_soon(client.do_handshake)
await wait_all_tasks_blocked()
nursery.start_soon(server.do_handshake)

assert client.version() == server.version()
await client.send_all(b"hello")
assert await server.receive_some(5) == b"hello"


async def test_once_failure_propagates_without_checkpoint() -> None:
# The checkpoint=False fast path must also report a failed operation rather
# than silently returning. It isn't reachable through SSLStream's public
# API once the stream is marked broken, so test it directly.
async def fail() -> None:
raise KeyError

once = _Once(fail)

with trio.fail_after(2):
with pytest.raises(KeyError):
await once.ensure(checkpoint=True)

with pytest.raises(BrokenResourceError):
await once.ensure(checkpoint=False)

with pytest.raises(BrokenResourceError):
await once.ensure(checkpoint=True)

assert not once.done


def test_selected_alpn_protocol_before_handshake(client_ctx: SSLContext) -> None:
client, server = ssl_memory_stream_pair(client_ctx)

Expand Down
Loading