1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use core::ffi::{c_char, c_int, c_uint, c_void};
use core::ptr::{self, NonNull};
use bun_core::Fd;
use crate::{LIBUS_SOCKET_DESCRIPTOR, SocketGroup, SocketKind, SslCtx, us_bun_verify_error_t};
bun_core::declare_scope!(uws, visible);
const MAX_I32: usize = i32::MAX as usize;
// Rust bindings for `us_socket_t`.
//
// TLS is per-socket (`s->ssl != NULL` in C); there is no `int ssl` selector.
// Dispatch is by `kind()` — see `SocketKind` and `dispatch.rs`.
//
// Higher-level wrappers (`uws::SocketTCP`/`SocketTLS`) cover named pipes,
// upgraded duplexes, and async DNS.
bun_opaque::opaque_ffi! { pub struct us_socket_t; }
#[repr(i32)]
#[derive(Copy, Clone, Eq, PartialEq, strum::IntoStaticStr)]
pub enum CloseCode {
/// TLS: send close_notify and defer fd close until peer replies. TCP: FIN.
normal = 0,
/// TLS: fast-shutdown (no wait). TCP: SO_LINGER{1,0} → RST, dropping any
/// unflushed send buffer. Only for `terminate()` / GC abort.
failure = 1,
/// TLS: fast-shutdown (no wait). TCP: FIN. For `_handle.close()` where
/// the JS wrapper detaches immediately so `.normal`'s deferral would
/// orphan the `us_socket_t`, but already-written data must still drain.
fast_shutdown = 2,
}
impl us_socket_t {
pub fn open(&mut self, is_client: bool, ip_addr: Option<&[u8]>) {
bun_core::scoped_log!(uws, "us_socket_open({:p}, is_client: {})", self, is_client);
if let Some(ip) = ip_addr {
debug_assert!(ip.len() < MAX_I32);
unsafe {
// SAFETY: self is a live us_socket_t; ip.ptr valid for ip.len bytes
let _ = c::us_socket_open(
self,
is_client as i32,
ip.as_ptr(),
i32::try_from(ip.len().min(MAX_I32)).expect("int cast"),
);
}
} else {
unsafe {
// SAFETY: self is a live us_socket_t
let _ = c::us_socket_open(self, is_client as i32, ptr::null(), 0);
}
}
}
pub fn pause(&mut self) {
bun_core::scoped_log!(uws, "us_socket_pause({:p})", self);
c::us_socket_pause(self);
}
pub fn resume(&mut self) {
bun_core::scoped_log!(uws, "us_socket_resume({:p})", self);
c::us_socket_resume(self);
}
pub fn close(&mut self, code: CloseCode) {
bun_core::scoped_log!(
uws,
"us_socket_close({:p}, {})",
self,
<&'static str>::from(code)
);
unsafe {
// SAFETY: self is a live us_socket_t
let _ = c::us_socket_close(self, code, ptr::null_mut());
}
}
pub fn shutdown(&mut self) {
bun_core::scoped_log!(uws, "us_socket_shutdown({:p})", self);
c::us_socket_shutdown(self);
}
pub fn shutdown_read(&mut self) {
c::us_socket_shutdown_read(self);
}
pub fn is_closed(&self) -> bool {
c::us_socket_is_closed(self) > 0
}
pub fn is_shutdown(&self) -> bool {
c::us_socket_is_shut_down(self) > 0
}
pub fn is_tls(&self) -> bool {
c::us_socket_is_tls(self) > 0
}
pub fn local_port(&self) -> i32 {
c::us_socket_local_port(self)
}
pub fn remote_port(&self) -> i32 {
c::us_socket_remote_port(self)
}
/// Returned slice is a view into `buf`.
// TODO(port): narrow error set
pub fn local_address<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8], bun_core::Error> {
let mut length: i32 = i32::try_from(buf.len().min(MAX_I32)).expect("int cast");
unsafe {
// SAFETY: buf.as_mut_ptr() valid for `length` bytes; length is in/out
c::us_socket_local_address(self, buf.as_mut_ptr(), &raw mut length);
}
if length < 0 {
let errno = bun_errno::get_errno(length);
debug_assert!(errno != bun_errno::E::SUCCESS);
// TODO(port): bun.errnoToZigErr — map errno to bun_core::Error
return Err(bun_core::errno_to_zig_err(errno as i32));
}
debug_assert!(buf.len() >= length as usize);
Ok(&buf[..usize::try_from(length).expect("int cast")])
}
/// Returned slice is a view into `buf`. On error, `errno` should be set.
// TODO(port): narrow error set
pub fn remote_address<'a>(&self, buf: &'a mut [u8]) -> Result<&'a [u8], bun_core::Error> {
let mut length: i32 = i32::try_from(buf.len().min(MAX_I32)).expect("int cast");
unsafe {
// SAFETY: buf.as_mut_ptr() valid for `length` bytes; length is in/out
c::us_socket_remote_address(self, buf.as_mut_ptr(), &raw mut length);
}
if length < 0 {
let errno = bun_errno::get_errno(length);
debug_assert!(errno != bun_errno::E::SUCCESS);
// TODO(port): bun.errnoToZigErr — map errno to bun_core::Error
return Err(bun_core::errno_to_zig_err(errno as i32));
}
debug_assert!(buf.len() >= length as usize);
Ok(&buf[..usize::try_from(length).expect("int cast")])
}
pub fn set_timeout(&mut self, seconds: u32) {
c::us_socket_timeout(self, seconds);
}
pub fn set_long_timeout(&mut self, minutes: u32) {
c::us_socket_long_timeout(self, minutes);
}
pub fn set_nodelay(&mut self, enabled: bool) {
c::us_socket_nodelay(self, enabled as c_int);
}
pub fn set_keepalive(&mut self, enabled: bool, delay: u32) -> i32 {
c::us_socket_keepalive(self, enabled as c_int, delay)
}
/// `SSL*` if TLS, else null. Use `get_fd()` for the descriptor.
pub fn ssl(&mut self) -> Option<&mut bun_boringssl_sys::SSL> {
if !self.is_tls() {
return None;
}
unsafe {
// SAFETY: is_tls() guarantees the native handle is a non-null SSL*
c::us_socket_get_native_handle(self)
.cast::<bun_boringssl_sys::SSL>()
.as_mut()
}
}
/// Node-compat `_handle` shape: `SSL*` for TLS sockets, fd-as-pointer for
/// plain TCP. Consumers that want one or the other should call `ssl()` /
/// `get_fd()` directly; this is the round-trip-to-JS form.
pub fn get_native_handle(&mut self) -> Option<*mut c_void> {
let p = c::us_socket_get_native_handle(self);
if p.is_null() { None } else { Some(p) }
}
pub fn ext<T>(&mut self) -> &mut T {
unsafe {
// SAFETY: us_socket_ext returns LIBUS_EXT_ALIGNMENT-aligned storage
// sized for T at socket creation; caller picks the same T it stored.
&mut *c::us_socket_ext(self).cast::<T>()
}
}
/// Type-erased ext storage — `LIBUS_EXT_ALIGNMENT`-aligned bytes
/// immediately after the C struct. Prefer `ext<T>()`.
pub fn ext_ptr(&mut self) -> *mut u8 {
// TODO(port): Rust pointer types do not carry alignment; LIBUS_EXT_ALIGNMENT == 16
c::us_socket_ext(self).cast::<u8>()
}
pub fn group(&mut self) -> &mut SocketGroup {
unsafe {
// SAFETY: us_socket_group never returns null for a live socket
&mut *c::us_socket_group(self)
}
}
// Zig: `pub const rawGroup = group;`
#[inline]
pub fn raw_group(&mut self) -> &mut SocketGroup {
self.group()
}
pub fn kind(&self) -> SocketKind {
SocketKind::from_u8(c::us_socket_kind(self))
}
/// Re-stamp the dispatch kind in place. Used after `Listener.onCreate`
/// stashes the `NewSocket*` in ext so subsequent events skip the listener
/// arm and route straight to `BunSocket`.
pub fn set_kind(&mut self, k: SocketKind) {
c::us_socket_set_kind(self, k as u8);
}
/// Move this socket to a new group/kind, optionally resizing its ext.
/// Returns the (possibly relocated) socket; `self` is invalid after.
// TODO(port): lifetime — self is consumed/invalidated; returned ptr may be a different allocation
pub fn adopt(
&mut self,
g: &mut SocketGroup,
k: SocketKind,
old_ext: i32,
new_ext: i32,
) -> Option<NonNull<us_socket_t>> {
// SAFETY: self and g are live; C may realloc and return a different us_socket_t*
unsafe { NonNull::new(c::us_socket_adopt(self, g, k as u8, old_ext, new_ext)) }
}
/// `adopt` + attach a fresh `SSL*` from `ssl_ctx` (refcounted by the C
/// side for the socket's lifetime). Does NOT kick the handshake — the
/// caller must repoint `ext` first (so any dispatch lands in the new
/// owner) and then call `start_tls_handshake`. Replaces
/// `us_socket_upgrade_to_tls` / `wrapTLS`.
// TODO(port): lifetime — self is consumed/invalidated; returned ptr may be a different allocation
pub fn adopt_tls(
&mut self,
g: &mut SocketGroup,
k: SocketKind,
ssl_ctx: &mut SslCtx,
sni: Option<&core::ffi::CStr>,
old_ext: i32,
new_ext: i32,
) -> Option<NonNull<us_socket_t>> {
// SAFETY: self/g/ssl_ctx are live; sni is null or a valid C string; C may
// realloc and return a different us_socket_t*
unsafe {
NonNull::new(c::us_socket_adopt_tls(
self,
g,
k as u8,
ssl_ctx,
sni.map_or(ptr::null(), |s| s.as_ptr()),
old_ext,
new_ext,
))
}
}
/// Send ClientHello. Separate from `adopt_tls` so the ext slot can be
/// repointed before any handshake/close dispatch can fire.
pub fn start_tls_handshake(&mut self) {
c::us_socket_start_tls_handshake(self);
}
/// Tee inbound ciphertext to `us_dispatch_ssl_raw_tap` before `SSL_read`
/// consumes it, so the `[raw, tls]` pair from `upgradeTLS` can surface
/// encrypted bytes to the original net.Socket `data` listener.
pub fn set_ssl_raw_tap(&mut self, enabled: bool) {
c::us_socket_set_ssl_raw_tap(self, enabled as c_int);
}
pub fn write(&mut self, data: &[u8]) -> i32 {
let rc = unsafe {
// SAFETY: data.as_ptr() valid for data.len() bytes
c::us_socket_write(
self,
data.as_ptr(),
i32::try_from(data.len().min(MAX_I32)).expect("int cast"),
)
};
bun_core::scoped_log!(uws, "us_socket_write({:p}, {}) = {}", self, data.len(), rc);
rc
}
#[cfg(not(windows))]
pub fn write_fd(&mut self, data: &[u8], file_descriptor: Fd) -> i32 {
let rc = unsafe {
// SAFETY: data.as_ptr() valid for data.len() bytes; fd is a valid native descriptor
c::us_socket_ipc_write_fd(
self,
data.as_ptr(),
i32::try_from(data.len().min(MAX_I32)).expect("int cast"),
file_descriptor.native(),
)
};
bun_core::scoped_log!(
uws,
"us_socket_ipc_write_fd({:p}, {}, {}) = {}",
self,
data.len(),
file_descriptor.native(),
rc
);
rc
}
#[cfg(windows)]
pub fn write_fd(&mut self, _data: &[u8], _file_descriptor: Fd) -> i32 {
// Zig: `if (Environment.isWindows) @compileError(...)` — that fires only
// on call (lazy semantics). Rust evaluates `compile_error!` at item
// definition, so this would brick the windows build even with no callers.
// Mirror Zig intent with a runtime trap; no current Windows call site.
unreachable!("us_socket_t::write_fd is not implemented on Windows")
}
pub fn write2(&mut self, first: &[u8], second: &[u8]) -> i32 {
let rc = unsafe {
// SAFETY: both slices valid for their respective lengths
c::us_socket_write2(
self,
first.as_ptr(),
first.len(),
second.as_ptr(),
second.len(),
)
};
bun_core::scoped_log!(
uws,
"us_socket_write2({:p}, {}, {}) = {}",
self,
first.len(),
second.len(),
rc
);
rc
}
/// Bypass TLS — raw bytes to the fd even if `is_tls()`.
pub fn raw_write(&mut self, data: &[u8]) -> i32 {
bun_core::scoped_log!(uws, "us_socket_raw_write({:p}, {})", self, data.len());
unsafe {
// SAFETY: data.as_ptr() valid for data.len() bytes
c::us_socket_raw_write(
self,
data.as_ptr(),
i32::try_from(data.len().min(MAX_I32)).expect("int cast"),
)
}
}
pub fn flush(&mut self) {
c::us_socket_flush(self);
}
pub fn send_file_needs_more(&mut self) {
c::us_socket_sendfile_needs_more(self);
}
pub fn get_fd(&self) -> Fd {
let raw = c::us_socket_get_fd(self);
// LIBUS_SOCKET_DESCRIPTOR is `c_int` on POSIX, `SOCKET` (`usize`) on
// Windows. Tag kind=system explicitly — `from_native` would store raw
// bits verbatim and mis-tag `INVALID_SOCKET` (~0) as kind=uv.
#[cfg(windows)]
{
Fd::from_system(raw as *mut core::ffi::c_void)
}
#[cfg(not(windows))]
{
Fd::from_native(raw)
}
}
pub fn get_verify_error(&self) -> us_bun_verify_error_t {
c::us_socket_verify_error(self)
}
pub fn get_error(&self) -> i32 {
c::us_socket_get_error(self)
}
pub fn is_established(&self) -> bool {
c::us_socket_is_established(self) > 0
}
}
/// Raw externs. Private — every operation has a typed method on `us_socket_t`.
mod c {
use super::*;
// Every C-side decl takes `us_socket_r` (= `us_socket_t* nonnull_arg`), so
// mirror that here — passing null is UB and the typed methods above never do.
// `us_socket_t` is `#[repr(C)]` with `UnsafeCell<[u8; 0]>`, so `&us_socket_t`
// / `&mut us_socket_t` are ABI-identical to a non-null pointer with no
// `readonly`/`noalias` attribute. Shims whose only pointer argument is the
// socket itself (plus value types) are declared `safe fn` so the validity
// proof lives in the type signature instead of per-call-site `unsafe { }`.
// Shims that take a (ptr,len) pair, nullable raw, or transfer ownership
// stay unsafe.
unsafe extern "C" {
pub(super) safe fn us_socket_get_native_handle(s: &mut us_socket_t) -> *mut c_void;
pub(super) safe fn us_socket_local_port(s: &us_socket_t) -> i32;
pub(super) safe fn us_socket_remote_port(s: &us_socket_t) -> i32;
pub(super) fn us_socket_remote_address(
s: *const us_socket_t,
buf: *mut u8,
length: *mut i32,
);
pub(super) fn us_socket_local_address(
s: *const us_socket_t,
buf: *mut u8,
length: *mut i32,
);
pub(super) safe fn us_socket_timeout(s: &mut us_socket_t, seconds: c_uint);
pub(super) safe fn us_socket_long_timeout(s: &mut us_socket_t, minutes: c_uint);
pub(super) safe fn us_socket_nodelay(s: &mut us_socket_t, enable: c_int);
pub(super) safe fn us_socket_keepalive(
s: &mut us_socket_t,
enable: c_int,
delay: c_uint,
) -> c_int;
pub(super) safe fn us_socket_ext(s: &mut us_socket_t) -> *mut c_void;
pub(super) safe fn us_socket_group(s: &mut us_socket_t) -> *mut SocketGroup;
pub(super) safe fn us_socket_kind(s: &us_socket_t) -> u8;
pub(super) safe fn us_socket_set_kind(s: &mut us_socket_t, kind: u8);
pub(super) safe fn us_socket_set_ssl_raw_tap(s: &mut us_socket_t, enabled: c_int);
pub(super) safe fn us_socket_is_tls(s: &us_socket_t) -> i32;
pub(super) fn us_socket_write(s: *mut us_socket_t, data: *const u8, length: i32) -> i32;
#[cfg(not(windows))]
pub(super) fn us_socket_ipc_write_fd(
s: *mut us_socket_t,
data: *const u8,
length: i32,
fd: i32,
) -> i32;
pub(super) fn us_socket_write2(
s: *mut us_socket_t,
header: *const u8,
len: usize,
payload: *const u8,
len2: usize,
) -> i32;
pub(super) fn us_socket_raw_write(s: *mut us_socket_t, data: *const u8, length: i32)
-> i32;
pub(super) safe fn us_socket_flush(s: &mut us_socket_t);
pub(super) fn us_socket_open(
s: *mut us_socket_t,
is_client: i32,
ip: *const u8,
ip_length: i32,
) -> *mut us_socket_t;
pub(super) safe fn us_socket_pause(s: &mut us_socket_t);
pub(super) safe fn us_socket_resume(s: &mut us_socket_t);
pub(super) fn us_socket_close(
s: *mut us_socket_t,
code: CloseCode,
reason: *mut c_void,
) -> *mut us_socket_t;
pub(super) safe fn us_socket_shutdown(s: &mut us_socket_t);
pub(super) safe fn us_socket_is_closed(s: &us_socket_t) -> i32;
pub(super) safe fn us_socket_shutdown_read(s: &mut us_socket_t);
pub(super) safe fn us_socket_is_shut_down(s: &us_socket_t) -> i32;
pub(super) safe fn us_socket_sendfile_needs_more(socket: &mut us_socket_t);
pub(super) safe fn us_socket_get_fd(s: &us_socket_t) -> LIBUS_SOCKET_DESCRIPTOR;
pub(super) safe fn us_socket_verify_error(s: &us_socket_t) -> us_bun_verify_error_t;
pub(super) safe fn us_socket_get_error(s: &us_socket_t) -> c_int;
pub(super) safe fn us_socket_is_established(s: &us_socket_t) -> i32;
pub(super) fn us_socket_adopt(
s: *mut us_socket_t,
group: *mut SocketGroup,
kind: u8,
old_ext_size: i32,
ext_size: i32,
) -> *mut us_socket_t;
/// ssl_ctx is required (the whole point); sni may be null.
pub(super) fn us_socket_adopt_tls(
s: *mut us_socket_t,
group: *mut SocketGroup,
kind: u8,
ssl_ctx: *mut SslCtx,
sni: *const c_char,
old_ext_size: i32,
ext_size: i32,
) -> *mut us_socket_t;
pub(super) safe fn us_socket_start_tls_handshake(s: &mut us_socket_t);
}
}
#[repr(C)]
pub struct us_socket_stream_buffer_t {
pub list_ptr: *mut u8,
pub list_cap: usize,
pub list_len: usize,
pub total_bytes_written: usize,
pub cursor: usize,
}
impl Default for us_socket_stream_buffer_t {
fn default() -> Self {
Self {
list_ptr: ptr::null_mut(),
list_cap: 0,
list_len: 0,
total_bytes_written: 0,
cursor: 0,
}
}
}
/// Minimal structural mirror of `bun_io::StreamBuffer` for tier-0 interop.
/// The higher-tier `bun_io::StreamBuffer` is field-identical and converts via
/// `From`/`Into` (added in the move-in pass).
pub struct StreamBuffer {
pub list: Vec<u8>,
pub cursor: usize,
}
impl us_socket_stream_buffer_t {
// TODO(port): ownership — Zig does not free the previous list_ptr here; matches that.
pub fn update(&mut self, stream_buffer: StreamBuffer) {
// Decompose the Vec<u8> backing `stream_buffer.list` into raw parts so
// the C side can read ptr/len/cap directly.
let mut list = core::mem::ManuallyDrop::new(stream_buffer.list);
if list.capacity() > 0 {
self.list_ptr = list.as_mut_ptr();
} else {
self.list_ptr = ptr::null_mut();
}
self.list_len = list.len();
self.list_cap = list.capacity();
self.cursor = stream_buffer.cursor;
}
pub fn wrote(&mut self, written: usize) {
self.total_bytes_written = self.total_bytes_written.saturating_add(written);
}
pub fn to_stream_buffer(&self) -> StreamBuffer {
StreamBuffer {
list: if !self.list_ptr.is_null() {
unsafe {
// SAFETY: list_ptr/list_len/list_cap were produced by decomposing a
// Vec<u8> in `update`; global allocator (mimalloc) matches.
Vec::from_raw_parts(self.list_ptr, self.list_len, self.list_cap)
}
} else {
Vec::new()
},
cursor: self.cursor,
}
}
/// Explicit teardown — this struct is `#[repr(C)]` and freed via the
/// exported `us_socket_free_stream_buffer`, so no `Drop` impl.
///
/// SAFETY: `this` must point to a live `us_socket_stream_buffer_t` whose
/// `list_ptr`/`list_cap` were produced by `update` (decomposed `Vec<u8>` on
/// the global mimalloc allocator). Not called more than once.
pub unsafe fn destroy(this: *mut Self) {
// SAFETY: caller contract — `this` is non-null and exclusively borrowed
let this = unsafe { &mut *this };
if !this.list_ptr.is_null() {
unsafe {
// SAFETY: list_ptr/list_cap came from a decomposed Vec<u8> (global mimalloc).
drop(Vec::from_raw_parts(this.list_ptr, 0, this.list_cap));
}
}
}
}
#[unsafe(no_mangle)]
pub(crate) extern "C" fn us_socket_free_stream_buffer(buffer: *mut us_socket_stream_buffer_t) {
// SAFETY: caller (C) passes a live us_socket_stream_buffer_t*
unsafe { us_socket_stream_buffer_t::destroy(buffer) };
}
// us_socket_buffered_js_write moved to src/runtime/socket/uws_jsc.rs
// ported from: src/uws_sys/us_socket_t.zig