Skip to content

Commit

Permalink
Fixes #15480 (#15611)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarred-Sumner authored Dec 6, 2024
1 parent 1476e4c commit b453360
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 11 deletions.
6 changes: 4 additions & 2 deletions packages/bun-usockets/src/bsd.c
Original file line number Diff line number Diff line change
Expand Up @@ -965,8 +965,10 @@ int bsd_connect_udp_socket(LIBUS_SOCKET_DESCRIPTOR fd, const char *host, int por
char port_string[16];
snprintf(port_string, 16, "%d", port);

if (getaddrinfo(host, port_string, &hints, &result)) {
return -1;
int gai_error = getaddrinfo(host, port_string, &hints, &result);

if (gai_error != 0) {
return gai_error;
}

if (result == NULL) {
Expand Down
21 changes: 12 additions & 9 deletions src/bun.js/api/bun/udp_socket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -290,14 +290,6 @@ pub const UDPSocket = struct {
.vm = vm,
});

// also cleans up config
defer {
if (globalThis.hasException()) {
this.closed = true;
this.deinit();
}
}

if (uws.udp.Socket.create(
this.loop,
onData,
Expand All @@ -309,15 +301,26 @@ pub const UDPSocket = struct {
)) |socket| {
this.socket = socket;
} else {
this.closed = true;
this.deinit();
return globalThis.throw("Failed to bind socket", .{});
}

errdefer {
this.socket.close();
this.deinit();
}

if (config.connect) |connect| {
const ret = this.socket.connect(connect.address, connect.port);
if (ret != 0) {
if (JSC.Maybe(void).errnoSys(ret, .connect)) |err| {
return globalThis.throwValue(err.toJS(globalThis));
}

if (bun.c_ares.Error.initEAI(ret)) |err| {
return globalThis.throwValue(err.toJS(globalThis));
}
}
this.connect_info = .{ .port = connect.port };
}
Expand Down Expand Up @@ -645,7 +648,7 @@ pub const UDPSocket = struct {
// finalize is only called when js_refcount reaches 0
// js_refcount can only reach 0 when the socket is closed
bun.assert(this.closed);

this.poll_ref.disable();
this.config.deinit();
this.destroy();
}
Expand Down
8 changes: 8 additions & 0 deletions test/js/bun/udp/udp_socket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@ import { udpSocket } from "bun";
import { describe, expect, test } from "bun:test";
import { disableAggressiveGCScope, randomPort } from "harness";
import { dataCases, dataTypes } from "./testdata";
import { heapStats } from "bun:jsc";

describe("udpSocket()", () => {
test("connect with invalid hostname rejects", async () => {
expect(async () =>
udpSocket({
connect: { hostname: "example!!!!!.com", port: 443 },
}),
).toThrow();
});
test("can create a socket", async () => {
const socket = await udpSocket({});
expect(socket).toBeInstanceOf(Object);
Expand Down

0 comments on commit b453360

Please sign in to comment.