Skip to content

Commit

Permalink
always safe deinit socket context (#2611)
Browse files Browse the repository at this point in the history
  • Loading branch information
cirospaciari authored Apr 10, 2023
1 parent f4ab79d commit f91dc8c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
12 changes: 7 additions & 5 deletions src/bun.js/api/bun/socket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,6 @@ pub const Listener = struct {
std.debug.assert(this.handlers.active_connections == 0);

if (this.socket_context) |ctx| {
ctx.close(this.ssl);
ctx.deinit(this.ssl);
}

Expand Down Expand Up @@ -1049,14 +1048,17 @@ fn NewSocket(comptime ssl: bool) type {

pub fn markInactive(this: *This) void {
if (this.reffer.has) {
var vm = this.handlers.vm;
this.reffer.unref(vm);

// we have to close the socket before the socket context is closed
// otherwise we will get a segfault
// uSockets will defer closing the TCP socket until the next tick
if (!this.socket.isClosed())
if (!this.socket.isClosed()) {
this.socket.close(0, null);
// onClose will call markInactive again
return;
}

var vm = this.handlers.vm;
this.reffer.unref(vm);

this.handlers.markInactive(ssl, this.socket.context());
this.poll_ref.unref(vm);
Expand Down
20 changes: 19 additions & 1 deletion src/deps/uws.zig
Original file line number Diff line number Diff line change
Expand Up @@ -394,13 +394,31 @@ pub const Timer = opaque {
return @ptrCast(*?Type, @alignCast(@alignOf(Type), us_timer_ext(this))).*.?;
}
};

pub const SocketContext = opaque {
pub fn getNativeHandle(this: *SocketContext, comptime ssl: bool) *anyopaque {
return us_socket_context_get_native_handle(comptime @as(i32, @boolToInt(ssl)), this).?;
}

fn _deinit_ssl(this: *SocketContext) void {
us_socket_context_free(@as(i32, 1), this);
}

fn _deinit(this: *SocketContext) void {
us_socket_context_free(@as(i32, 0), this);
}

/// closes and deinit the SocketContexts
pub fn deinit(this: *SocketContext, ssl: bool) void {
us_socket_context_free(@as(i32, @boolToInt(ssl)), this);
this.close(ssl);
//always deinit in next iteration
if (Loop.get()) |loop| {
if (ssl) {
loop.nextTick(*SocketContext, this, SocketContext._deinit_ssl);
} else {
loop.nextTick(*SocketContext, this, SocketContext._deinit);
}
}
}

pub fn close(this: *SocketContext, ssl: bool) void {
Expand Down

0 comments on commit f91dc8c

Please sign in to comment.