Skip to content

turn: close socket when allocation is cancelled during gathering - #111

Open
Freazg wants to merge 1 commit into
aiortc:mainfrom
Freazg:fix/turn-socket-leak-on-cancel
Open

turn: close socket when allocation is cancelled during gathering#111
Freazg wants to merge 1 commit into
aiortc:mainfrom
Freazg:fix/turn-socket-leak-on-cancel

Conversation

@Freazg

@Freazg Freazg commented Jul 13, 2026

Copy link
Copy Markdown

Problem

create_turn_endpoint() opens a datagram/stream transport to the TURN
server, then awaits the allocation in TurnTransport._connect(). During
ICE candidate gathering, Connection.gather_candidates() runs the relay
task under asyncio.wait(timeout=...) and cancels it if it does not
complete in time (e.g. a slow or unreachable TURN server).

The resulting CancelledError is raised inside _connect(), but the
cleanup handler in create_turn_endpoint() only catches except Exception. Since CancelledError is a BaseException, it bypasses
inner_transport.close(), and the already-open socket to the TURN server
is leaked. The protocol is never added to Connection._protocols either,
so Connection.close() does not close it. Under repeated short-lived
connections against a distant TURN server this leaks one fd per gather.

Fix

Catch BaseException instead of Exception, so a cancellation also
closes the inner transport before re-raising.

Test

Added TurnTest.test_udp_transport_cancelled, which cancels the
allocation mid-setup and asserts the underlying transport is closed.
It fails on main (socket left open) and passes with this change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants