Skip to content

Detach socket on create_connection cancellation to prevent fd double-close#740

Open
junjzhang wants to merge 1 commit intoMagicStack:masterfrom
junjzhang:fix/detach-socket-on-cancellation
Open

Detach socket on create_connection cancellation to prevent fd double-close#740
junjzhang wants to merge 1 commit intoMagicStack:masterfrom
junjzhang:fix/detach-socket-on-cancellation

Conversation

@junjzhang
Copy link

Summary

Fixes #738.

When create_connection(sock=sock) or create_unix_connection(sock=sock) is cancelled or raises, tr._close() closes the fd via libuv but the Python socket object still believes it owns that fd. Its __del__ later closes whatever fd the OS recycled into that slot, silently corrupting an unrelated transport.

This adds sock.detach() on the error path of both create_connection and create_unix_connection, matching the semantics of standard asyncio where the transport always takes full ownership of the socket.

Changes

  • loop.pyx: Call sock.detach() after tr._close() in the except BaseException block for both TCP and Unix sock= paths
  • test_tcp.py: Add test_create_connection_sock_cancel_detaches verifying that sock.fileno() == -1 after cancellation

When create_connection(sock=sock) or create_unix_connection(sock=sock) is
cancelled or raises, tr._close() closes the fd via libuv but the Python
socket object still believes it owns that fd number. Its __del__ later
closes whatever fd the OS recycled into that slot, corrupting unrelated
transports.

Call sock.detach() on the error path so the Python socket sets its
internal fd to -1, matching the semantics of standard asyncio where the
transport always takes full ownership of the socket.

Fixes MagicStack#738
@junjzhang
Copy link
Author

@1st1 Please have a look! thx

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.

create_connection(sock=sock) does not detach socket on cancellation, causing fd double-close

1 participant