fix(usockets): safely handle socket reallocation during context adoption #25361
+141
−59
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
is_closed,adopted, andis_tlsflagsWhat does this PR do?
This PR improves event loop stability by addressing potential use-after-free issues that can occur when sockets are reallocated during adoption (e.g., when upgrading a TCP socket to TLS).
Key Changes
Socket State Tracking (internal.h)
is_closedflag to explicitly track when a socket has been closedadoptedflag to mark sockets that were reallocated during context adoptionis_tlsflag to track TLS socket state for proper low-priority queue handlingSafe Socket Adoption (context.c)
us_poll_resize()returns a new pointer (reallocation occurred), the old socket is now:is_closed = 1)adopted = 1)prevpointer set to the new socket for event redirectionus_internal_socket_context_link_socket/listen_socket/connecting_socketto prevent linking already-closed socketsEvent Loop Handling (loop.c)
on_open,on_writable,on_data), the event loop now checks if the socket was reallocated and redirects to the new socketis_closedstate and usesis_tlsflag for correct SSL handlingPoll Resize Safety (epoll_kqueue.c)
us_poll_resize()to always allocate new memory withus_calloc()instead ofus_realloc()to ensure the old pointer remains valid for cleanupold_ext_sizeparameter to correctly calculate memory sizesus_internal_loop_update_pending_ready_polls()call inus_poll_change()to ensure pending events are properly redirectedHow did you verify your code works?
Run existing CI and existing socket upgrade tests under asan build