Skip to main content

seq_runtime/
tcp.rs

1//! TCP Socket Operations for Seq
2//!
3//! Provides non-blocking TCP socket operations using May's coroutine-aware I/O.
4//! All operations yield the strand instead of blocking the OS thread.
5//!
6//! These functions are exported with C ABI for LLVM codegen.
7
8use crate::stack::{Stack, pop, push};
9use crate::value::Value;
10use may::net::{TcpListener, TcpStream};
11#[cfg(feature = "http")]
12use rustls::{ClientConnection, StreamOwned};
13use std::io::{Read, Write};
14use std::net::{IpAddr, SocketAddr};
15use std::sync::Mutex;
16
17/// What a Socket id actually points at in the STREAMS registry.
18///
19/// `Tcp` is a connected plain stream (the only kind PR1/PR2 produced).
20/// `Tls` is a connected stream that has been upgraded via
21/// `net.tls.client` — every read/write goes through rustls over the
22/// same may-aware TcpStream. Both arms implement `Read + Write`, so
23/// `net.tcp.read` / `net.tcp.write` / `net.tcp.close` dispatch over
24/// either variant without the caller knowing the difference.
25///
26/// The TLS arm is boxed not to shrink the *enum* (size_of TcpStream is
27/// non-trivial and tends to dominate the discriminant size anyway) but
28/// to keep the `StreamOwned<ClientConnection, _>` payload — which
29/// embeds rustls's per-connection record buffers — off the registry
30/// allocation. Without the box, every plain-TCP allocation would have
31/// to find a contiguous chunk large enough for the TLS variant.
32enum StreamKind {
33    Tcp(TcpStream),
34    /// TLS-upgraded stream (`net.tls.client`) — exists only when the
35    /// `http` capability (TLS + HTTP) is compiled in; base builds have
36    /// no rustls at all (see docs/design/RUNTIME_CAPABILITY_LINKING.md).
37    #[cfg(feature = "http")]
38    Tls(Box<StreamOwned<ClientConnection, TcpStream>>),
39}
40
41impl Read for StreamKind {
42    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
43        match self {
44            StreamKind::Tcp(s) => s.read(buf),
45            #[cfg(feature = "http")]
46            StreamKind::Tls(s) => s.read(buf),
47        }
48    }
49}
50
51impl Write for StreamKind {
52    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
53        match self {
54            StreamKind::Tcp(s) => s.write(buf),
55            #[cfg(feature = "http")]
56            StreamKind::Tls(s) => s.write(buf),
57        }
58    }
59    fn flush(&mut self) -> std::io::Result<()> {
60        match self {
61            StreamKind::Tcp(s) => s.flush(),
62            #[cfg(feature = "http")]
63            StreamKind::Tls(s) => s.flush(),
64        }
65    }
66}
67
68// Maximum number of concurrent connections to prevent unbounded growth
69const MAX_SOCKETS: usize = 10_000;
70
71// Architectural cap for any future read-N or full-body socket reader
72// (e.g. an HTTP-client migration off ureq). The current `tcp.read` does
73// one 4 KB read per call and so doesn't need to consult this; it stays
74// here as the ceiling that bounded-buffer variants must respect.
75#[allow(dead_code)]
76const MAX_READ_SIZE: usize = 1_048_576; // 1 MB
77
78// Socket registry with ID reuse via free list. Private — the only
79// cross-module operation is `upgrade_tcp_in_place`, which hides the
80// registry behind a callback.
81struct SocketRegistry<T> {
82    sockets: Vec<Option<T>>,
83    free_ids: Vec<usize>,
84}
85
86impl<T> SocketRegistry<T> {
87    const fn new() -> Self {
88        Self {
89            sockets: Vec::new(),
90            free_ids: Vec::new(),
91        }
92    }
93
94    fn allocate(&mut self, socket: T) -> Result<i64, &'static str> {
95        // Try to reuse a free ID first
96        if let Some(id) = self.free_ids.pop() {
97            self.sockets[id] = Some(socket);
98            return Ok(id as i64);
99        }
100
101        // Check max connections limit
102        if self.sockets.len() >= MAX_SOCKETS {
103            return Err("Maximum socket limit reached");
104        }
105
106        // Allocate new ID
107        let id = self.sockets.len();
108        self.sockets.push(Some(socket));
109        Ok(id as i64)
110    }
111
112    fn get_mut(&mut self, id: usize) -> Option<&mut Option<T>> {
113        self.sockets.get_mut(id)
114    }
115
116    fn free(&mut self, id: usize) {
117        if let Some(slot) = self.sockets.get_mut(id)
118            && slot.is_some()
119        {
120            *slot = None;
121            self.free_ids.push(id);
122        }
123    }
124
125    /// Release an id that was reserved by `take_tcp` but whose
126    /// caller never reinstalled a value into the slot.
127    ///
128    /// Symmetric pair to `take_tcp` for the failure path: after a
129    /// successful take the slot's inner Option is `None`, which
130    /// makes plain `free()` a silent no-op (its `slot.is_some()`
131    /// guard treats reserved-None the same as already-freed). This
132    /// method bypasses that guard to push the id back onto the
133    /// free list so subsequent allocations can reuse it.
134    ///
135    /// The `contains` check protects against double-release should
136    /// a buggy caller invoke this twice or against an already-freed
137    /// id. The free list is normally short, so the linear scan is
138    /// cheap.
139    ///
140    /// Only legitimate caller: `upgrade_tcp_in_place`'s Err branch.
141    fn release_reserved(&mut self, id: usize) {
142        let is_reserved = self
143            .sockets
144            .get(id)
145            .map(|slot| slot.is_none())
146            .unwrap_or(false);
147        if is_reserved && !self.free_ids.contains(&id) {
148            self.free_ids.push(id);
149        }
150    }
151}
152
153// Global registry for TCP listeners and streams. STREAMS holds a
154// StreamKind so that plain-TCP and TLS-wrapped sockets share one id
155// space (and one set of read/write/close builtins).
156//
157// The "free + allocate is dangerous across a strand yield" invariant
158// lives entirely inside this module — `tls::upgrade_tcp_to_tls` (the
159// only cross-module reason to touch STREAMS) goes through
160// `upgrade_tcp_in_place`, which holds the slot reserved (Some(None))
161// across the caller's yield-able TLS handshake so no concurrent
162// strand can grab the id.
163static LISTENERS: Mutex<SocketRegistry<TcpListener>> = Mutex::new(SocketRegistry::new());
164static STREAMS: Mutex<SocketRegistry<StreamKind>> = Mutex::new(SocketRegistry::new());
165
166/// Take the underlying `TcpStream` out of `STREAMS[id]`, only if the
167/// slot holds a `Tcp` variant. A `Tls` variant or empty slot
168/// short-circuits to `None`; a wrong-kind variant is restored so a
169/// double-upgrade caller doesn't accidentally destroy the connection.
170///
171/// On `Some` return, the slot at `id` is left holding `None` —
172/// reserved for the caller. The caller MUST either reinstall a value
173/// into that slot or release the id via `free_stream`. The recommended
174/// way to do this safely across a strand-yielding operation (e.g. a
175/// TLS handshake) is `upgrade_tcp_in_place`, which handles the
176/// reinstall/free for you.
177fn take_tcp(id: usize) -> Option<may::net::TcpStream> {
178    let mut streams = STREAMS.lock().unwrap();
179    let slot = streams.get_mut(id)?;
180    match slot.take() {
181        Some(StreamKind::Tcp(t)) => Some(t),
182        Some(other) => {
183            *slot = Some(other);
184            None
185        }
186        None => None,
187    }
188}
189
190/// Release an id that `take_tcp` reserved but no caller reinstalled.
191/// Bypasses the `slot.is_some()` guard in plain `free()` (which
192/// would silently no-op against a reserved-None slot, leaking the
193/// id for the lifetime of the process).
194#[cfg(feature = "http")] // only the TLS upgrade path reserves-and-fails
195fn release_reserved_stream(id: usize) {
196    STREAMS.lock().unwrap().release_reserved(id);
197}
198
199/// In-place upgrade of a TCP socket to its TLS-wrapped form.
200///
201/// The flow:
202/// 1. Take the underlying `TcpStream` out of `STREAMS[id]` via
203///    `take_tcp`. The slot is now reserved (Some(None)) — concurrent
204///    strands can't allocate this id while the caller runs `f`.
205/// 2. Hand the stream to `f` (which is allowed to yield the strand —
206///    typically the TLS handshake).
207/// 3. On success, wrap the returned StreamOwned in `StreamKind::Tls`
208///    and reinstall into the same slot — the Socket id is preserved.
209/// 4. On failure, drop the (already-consumed) `TcpStream` and release
210///    the id back to the free list.
211///
212/// Returns `true` iff the slot was found, the upgrade succeeded, and
213/// the reinstall completed. The Socket id is unchanged on success.
214///
215/// Crate-internal entry point for `tls::patch_seq_tls_client`. Keeps
216/// the "reserve across yield" invariant inside this module.
217#[cfg(feature = "http")]
218pub(crate) fn upgrade_tcp_in_place<F>(id: usize, f: F) -> bool
219where
220    F: FnOnce(
221        may::net::TcpStream,
222    )
223        -> Result<rustls::StreamOwned<rustls::ClientConnection, may::net::TcpStream>, ()>,
224{
225    let tcp = match take_tcp(id) {
226        Some(t) => t,
227        None => return false,
228    };
229    let stream = match f(tcp) {
230        Ok(s) => s,
231        Err(()) => {
232            // `f` consumed (and dropped) the TcpStream — socket
233            // closed. Release the reserved id back to the free list.
234            // Plain `free()` here would silently no-op because
235            // `take_tcp` already nulled the slot's inner Option;
236            // `release_reserved` bypasses that guard.
237            release_reserved_stream(id);
238            return false;
239        }
240    };
241    let mut streams = STREAMS.lock().unwrap();
242    match streams.get_mut(id) {
243        Some(slot) => {
244            *slot = Some(StreamKind::Tls(Box::new(stream)));
245            true
246        }
247        // Currently impossible with the append-only registry; future
248        // eviction would surface here as a clean false rather than a
249        // panic.
250        None => false,
251    }
252}
253
254/// Per-connect timeout in milliseconds. Default 10 000ms.
255///
256/// Bounds the kernel SYN timeout against silent peers. Read once via
257/// `LazyLock`; override per-process with `SEQ_TCP_CONNECT_TIMEOUT_MS`.
258/// Zero or a missing value falls back to the default — disabling
259/// the timeout would re-introduce the original 60–130s hazard.
260const DEFAULT_TCP_CONNECT_TIMEOUT_MS: u64 = 10_000;
261
262static TCP_CONNECT_TIMEOUT: std::sync::LazyLock<std::time::Duration> =
263    std::sync::LazyLock::new(|| {
264        let ms = std::env::var("SEQ_TCP_CONNECT_TIMEOUT_MS")
265            .ok()
266            .and_then(|v| v.parse::<u64>().ok())
267            .filter(|n| *n > 0)
268            .unwrap_or(DEFAULT_TCP_CONNECT_TIMEOUT_MS);
269        std::time::Duration::from_millis(ms)
270    });
271
272/// Test-only override for `TCP_CONNECT_TIMEOUT`. When `Some`, takes
273/// precedence over the LazyLock-cached value (which can't be reset
274/// once initialised). Mirrors the TLS-handshake and HTTP-request
275/// override hooks so the connect-timeout integration test can drive a
276/// deterministic short deadline without depending on env-var read order.
277#[cfg(test)]
278static TCP_CONNECT_TIMEOUT_OVERRIDE: Mutex<Option<std::time::Duration>> = Mutex::new(None);
279
280#[cfg(test)]
281pub(crate) fn set_test_tcp_connect_timeout(dur: Option<std::time::Duration>) {
282    *TCP_CONNECT_TIMEOUT_OVERRIDE.lock().unwrap() = dur;
283}
284
285fn tcp_connect_timeout() -> std::time::Duration {
286    #[cfg(test)]
287    if let Some(dur) = *TCP_CONNECT_TIMEOUT_OVERRIDE.lock().unwrap() {
288        return dur;
289    }
290    *TCP_CONNECT_TIMEOUT
291}
292
293/// Connect to the first reachable address in `addrs` at `port`.
294///
295/// Walks the list in order, returning the first successful
296/// `may::net::TcpStream::connect_timeout`. Yields the strand on each
297/// SYN/SYN-ACK round-trip. Returns `None` if every address fails or
298/// every connect attempt exceeds the configured timeout.
299///
300/// Building `SocketAddr` directly from the `IpAddr` avoids the
301/// IPv6 string-formatting trap (`"::1:80"` is not a parseable
302/// SocketAddr — brackets are required in that form).
303///
304/// Each individual connect attempt is bounded by `TCP_CONNECT_TIMEOUT`
305/// (default 10s, overridable via `SEQ_TCP_CONNECT_TIMEOUT_MS`). A
306/// peer that silently drops SYNs surfaces as `None` in seconds, not
307/// minutes.
308///
309/// Exposed to the crate so the HTTP client (which pre-resolves +
310/// SSRF-validates before connecting) can dial without re-resolving.
311pub(crate) fn connect_to_addrs(addrs: &[IpAddr], port: u16) -> Option<TcpStream> {
312    let timeout = tcp_connect_timeout();
313    addrs
314        .iter()
315        .find_map(|ip| TcpStream::connect_timeout(&SocketAddr::new(*ip, port), timeout).ok())
316}
317
318/// TCP listen on a port
319///
320/// Stack effect: ( port -- listener_id Bool )
321///
322/// Binds to 0.0.0.0:port and returns a listener ID with success flag.
323/// Returns (0, false) on failure (invalid port, bind error, socket limit).
324///
325/// # Safety
326/// Stack must have an Int (port number) on top
327#[unsafe(no_mangle)]
328pub unsafe extern "C" fn patch_seq_tcp_listen(stack: Stack) -> Stack {
329    unsafe {
330        let (stack, port_val) = pop(stack);
331        let port = match port_val {
332            Value::Int(p) => p,
333            _ => {
334                // Type error - return failure
335                let stack = push(stack, Value::Int(0));
336                return push(stack, Value::Bool(false));
337            }
338        };
339
340        // Validate port range (1-65535, or 0 for OS-assigned)
341        if !(0..=65535).contains(&port) {
342            let stack = push(stack, Value::Int(0));
343            return push(stack, Value::Bool(false));
344        }
345
346        // Bind to the port (non-blocking via May)
347        let addr = format!("0.0.0.0:{}", port);
348        let listener = match TcpListener::bind(&addr) {
349            Ok(l) => l,
350            Err(_) => {
351                let stack = push(stack, Value::Int(0));
352                return push(stack, Value::Bool(false));
353            }
354        };
355
356        // Store listener and get ID
357        let mut listeners = LISTENERS.lock().unwrap();
358        match listeners.allocate(listener) {
359            Ok(listener_id) => {
360                let stack = push(stack, Value::Int(listener_id));
361                push(stack, Value::Bool(true))
362            }
363            Err(_) => {
364                let stack = push(stack, Value::Int(0));
365                push(stack, Value::Bool(false))
366            }
367        }
368    }
369}
370
371/// TCP connect to a remote endpoint.
372///
373/// Stack effect: ( host:String port:Int -- Socket Bool )
374///
375/// Resolves `host` through the may-aware DNS layer (cache + worker
376/// pool — no `getaddrinfo` ever runs on a may carrier), then tries
377/// each resolved address in order until one connects via
378/// `may::net::TcpStream::connect`. Yields the strand on every step.
379///
380/// Returns `(0, false)` on resolution failure, every-address-failed,
381/// invalid port, or socket-registry exhaustion.
382///
383/// # Safety
384/// Stack must have a String (host) and Int (port) on top — port topmost.
385#[unsafe(no_mangle)]
386pub unsafe extern "C" fn patch_seq_tcp_connect(stack: Stack) -> Stack {
387    unsafe {
388        let (stack, port_val) = pop(stack);
389        let port = match port_val {
390            Value::Int(p) => p,
391            _ => {
392                let stack = push(stack, Value::Int(0));
393                return push(stack, Value::Bool(false));
394            }
395        };
396        if !(1..=65535).contains(&port) {
397            let stack = push(stack, Value::Int(0));
398            return push(stack, Value::Bool(false));
399        }
400
401        let (stack, host_val) = pop(stack);
402        let host = match host_val {
403            Value::String(s) => s,
404            _ => {
405                let stack = push(stack, Value::Int(0));
406                return push(stack, Value::Bool(false));
407            }
408        };
409        let hostname = host.as_str_or_empty();
410        if hostname.is_empty() {
411            let stack = push(stack, Value::Int(0));
412            return push(stack, Value::Bool(false));
413        }
414
415        let addrs = crate::dns::resolve_to_ips(hostname);
416        if addrs.is_empty() {
417            let stack = push(stack, Value::Int(0));
418            return push(stack, Value::Bool(false));
419        }
420        let stream = match connect_to_addrs(&addrs, port as u16) {
421            Some(s) => s,
422            None => {
423                let stack = push(stack, Value::Int(0));
424                return push(stack, Value::Bool(false));
425            }
426        };
427
428        let mut streams = STREAMS.lock().unwrap();
429        match streams.allocate(StreamKind::Tcp(stream)) {
430            Ok(id) => {
431                let stack = push(stack, Value::Int(id));
432                push(stack, Value::Bool(true))
433            }
434            Err(_) => {
435                let stack = push(stack, Value::Int(0));
436                push(stack, Value::Bool(false))
437            }
438        }
439    }
440}
441
442/// TCP accept a connection
443///
444/// Stack effect: ( listener_id -- client_id Bool )
445///
446/// Accepts a connection (yields the strand until one arrives).
447/// Returns (0, false) on failure (invalid listener, accept error, socket limit).
448///
449/// # Safety
450/// Stack must have an Int (listener_id) on top
451#[unsafe(no_mangle)]
452pub unsafe extern "C" fn patch_seq_tcp_accept(stack: Stack) -> Stack {
453    unsafe {
454        let (stack, listener_id_val) = pop(stack);
455        let listener_id = match listener_id_val {
456            Value::Int(id) => id as usize,
457            _ => {
458                let stack = push(stack, Value::Int(0));
459                return push(stack, Value::Bool(false));
460            }
461        };
462
463        // Take the listener out temporarily (so we don't hold lock during accept)
464        let listener = {
465            let mut listeners = LISTENERS.lock().unwrap();
466            match listeners.get_mut(listener_id).and_then(|opt| opt.take()) {
467                Some(l) => l,
468                None => {
469                    let stack = push(stack, Value::Int(0));
470                    return push(stack, Value::Bool(false));
471                }
472            }
473        };
474        // Lock released
475
476        // Accept connection (this yields the strand, doesn't block OS thread)
477        let (stream, _addr) = match listener.accept() {
478            Ok(result) => result,
479            Err(_) => {
480                // Put listener back before returning
481                let mut listeners = LISTENERS.lock().unwrap();
482                if let Some(slot) = listeners.get_mut(listener_id) {
483                    *slot = Some(listener);
484                }
485                let stack = push(stack, Value::Int(0));
486                return push(stack, Value::Bool(false));
487            }
488        };
489
490        // Put the listener back
491        {
492            let mut listeners = LISTENERS.lock().unwrap();
493            if let Some(slot) = listeners.get_mut(listener_id) {
494                *slot = Some(listener);
495            }
496        }
497
498        // Store stream and get ID
499        let mut streams = STREAMS.lock().unwrap();
500        match streams.allocate(StreamKind::Tcp(stream)) {
501            Ok(client_id) => {
502                let stack = push(stack, Value::Int(client_id));
503                push(stack, Value::Bool(true))
504            }
505            Err(_) => {
506                let stack = push(stack, Value::Int(0));
507                push(stack, Value::Bool(false))
508            }
509        }
510    }
511}
512
513/// TCP read from a socket
514///
515/// Stack effect: ( socket_id -- string Bool )
516///
517/// Reads all available data from the socket.
518/// Returns ("", false) on failure (invalid socket, read error, size limit, invalid UTF-8).
519///
520/// # Safety
521/// Stack must have an Int (socket_id) on top
522#[unsafe(no_mangle)]
523pub unsafe extern "C" fn patch_seq_tcp_read(stack: Stack) -> Stack {
524    unsafe {
525        let (stack, socket_id_val) = pop(stack);
526        let socket_id = match socket_id_val {
527            Value::Int(id) => id as usize,
528            _ => {
529                let stack = push(stack, Value::String("".into()));
530                return push(stack, Value::Bool(false));
531            }
532        };
533
534        // Take the stream out of the registry (so we don't hold the lock during I/O)
535        let mut stream = {
536            let mut streams = STREAMS.lock().unwrap();
537            match streams.get_mut(socket_id).and_then(|opt| opt.take()) {
538                Some(s) => s,
539                None => {
540                    let stack = push(stack, Value::String("".into()));
541                    return push(stack, Value::Bool(false));
542                }
543            }
544        };
545        // Registry lock is now released
546
547        // One read per call. may::net::TcpStream::read suspends the
548        // strand until at least one byte is available (or the peer
549        // closes), then returns whatever the kernel had ready in one
550        // batch. Returning here lets a caller wait for client data
551        // without our own read holding the socket past the first
552        // payload — request/response framing happens in user code.
553        //
554        // The chunk size caps a single batch at 4 KB, well under
555        // MAX_READ_SIZE, so a size check is unnecessary at the
556        // per-read level.
557        let mut buffer = Vec::new();
558        let mut chunk = [0u8; 4096];
559        let mut read_error = false;
560        match stream.read(&mut chunk) {
561            Ok(0) => {} // EOF — return empty payload, success=true
562            Ok(n) => buffer.extend_from_slice(&chunk[..n]),
563            Err(_) => read_error = true,
564        }
565
566        // Put the stream back
567        {
568            let mut streams = STREAMS.lock().unwrap();
569            if let Some(slot) = streams.get_mut(socket_id) {
570                *slot = Some(stream);
571            }
572        }
573
574        if read_error {
575            let stack = push(stack, Value::String("".into()));
576            return push(stack, Value::Bool(false));
577        }
578
579        // The bytes go into a byte-clean SeqString unchanged — TCP can
580        // now serve binary protocols (HTTP/2 frames, gRPC, raw TLS,
581        // protocol-buffer streams, anything that isn't text). UTF-8 is
582        // a property of the application protocol, not of the transport.
583        let stack = push(stack, Value::String(crate::seqstring::global_bytes(buffer)));
584        push(stack, Value::Bool(true))
585    }
586}
587
588/// TCP write to a socket
589///
590/// Stack effect: ( string socket_id -- Bool )
591///
592/// Writes string to the socket.
593/// Returns false on failure (invalid socket, write error).
594///
595/// # Safety
596/// Stack must have Int (socket_id) and String on top
597#[unsafe(no_mangle)]
598pub unsafe extern "C" fn patch_seq_tcp_write(stack: Stack) -> Stack {
599    unsafe {
600        let (stack, socket_id_val) = pop(stack);
601        let socket_id = match socket_id_val {
602            Value::Int(id) => id as usize,
603            _ => {
604                return push(stack, Value::Bool(false));
605            }
606        };
607
608        let (stack, data_val) = pop(stack);
609        let data = match data_val {
610            Value::String(s) => s,
611            _ => {
612                return push(stack, Value::Bool(false));
613            }
614        };
615
616        // Take the stream out of the registry (so we don't hold the lock during I/O)
617        let mut stream = {
618            let mut streams = STREAMS.lock().unwrap();
619            match streams.get_mut(socket_id).and_then(|opt| opt.take()) {
620                Some(s) => s,
621                None => {
622                    return push(stack, Value::Bool(false));
623                }
624            }
625        };
626        // Registry lock is now released
627
628        // Write data (non-blocking via May, yields strand as needed)
629        let write_result = stream.write_all(data.as_bytes());
630        let flush_result = if write_result.is_ok() {
631            stream.flush()
632        } else {
633            write_result
634        };
635
636        // Put the stream back
637        {
638            let mut streams = STREAMS.lock().unwrap();
639            if let Some(slot) = streams.get_mut(socket_id) {
640                *slot = Some(stream);
641            }
642        }
643
644        push(stack, Value::Bool(flush_result.is_ok()))
645    }
646}
647
648/// TCP close a socket
649///
650/// Stack effect: ( socket_id -- Bool )
651///
652/// Closes the socket connection and frees the socket ID for reuse.
653/// Returns true on success, false if socket_id was invalid.
654///
655/// # Safety
656/// Stack must have an Int (socket_id) on top
657#[unsafe(no_mangle)]
658pub unsafe extern "C" fn patch_seq_tcp_close(stack: Stack) -> Stack {
659    unsafe {
660        let (stack, socket_id_val) = pop(stack);
661        let socket_id = match socket_id_val {
662            Value::Int(id) => id as usize,
663            _ => {
664                return push(stack, Value::Bool(false));
665            }
666        };
667
668        // A user-visible `Socket` unifies listeners and connected
669        // streams, so close has to look in both registries. Streams
670        // are checked first because they're far more common at
671        // shutdown time. Ids are not globally unique across the two
672        // registries (each starts at 0); for finite servers that
673        // close exactly one of each that's fine, but multi-socket
674        // shutdowns with id-aliasing across registries remain an
675        // open design wart.
676        {
677            let mut streams = STREAMS.lock().unwrap();
678            if streams
679                .get_mut(socket_id)
680                .is_some_and(|slot| slot.is_some())
681            {
682                streams.free(socket_id);
683                return push(stack, Value::Bool(true));
684            }
685        }
686        {
687            let mut listeners = LISTENERS.lock().unwrap();
688            if listeners
689                .get_mut(socket_id)
690                .is_some_and(|slot| slot.is_some())
691            {
692                listeners.free(socket_id);
693                return push(stack, Value::Bool(true));
694            }
695        }
696        push(stack, Value::Bool(false))
697    }
698}
699
700// Public re-exports with short names for internal use
701pub use patch_seq_tcp_accept as tcp_accept;
702pub use patch_seq_tcp_close as tcp_close;
703pub use patch_seq_tcp_connect as tcp_connect;
704pub use patch_seq_tcp_listen as tcp_listen;
705pub use patch_seq_tcp_local_port as tcp_local_port;
706pub use patch_seq_tcp_read as tcp_read;
707pub use patch_seq_tcp_write as tcp_write;
708
709/// Get the local port a Socket is bound to.
710///
711/// Stack effect: `( Socket -- Int Bool )`
712///
713/// Works on both listeners (returns the port from `net.tcp.listen`,
714/// useful when `0` was passed to let the OS pick) and connected
715/// streams (returns the ephemeral local port the kernel chose for
716/// the connection). For TLS-wrapped sockets, returns the underlying
717/// TCP local port.
718///
719/// Returns `(0, false)` when the socket id is invalid or the OS
720/// can't report the local address.
721///
722/// # Safety
723/// Stack must have an Int (socket_id) on top.
724#[unsafe(no_mangle)]
725pub unsafe extern "C" fn patch_seq_tcp_local_port(stack: Stack) -> Stack {
726    unsafe {
727        let (stack, socket_id_val) = pop(stack);
728        let socket_id = match socket_id_val {
729            Value::Int(id) => id as usize,
730            _ => {
731                let stack = push(stack, Value::Int(0));
732                return push(stack, Value::Bool(false));
733            }
734        };
735
736        // Streams first, then listeners — same dispatch order as close.
737        let port: Option<u16> = {
738            let mut streams = STREAMS.lock().unwrap();
739            streams
740                .get_mut(socket_id)
741                .and_then(|slot| slot.as_ref())
742                .and_then(|sk| match sk {
743                    StreamKind::Tcp(s) => s.local_addr().ok().map(|a| a.port()),
744                    #[cfg(feature = "http")]
745                    StreamKind::Tls(s) => s.sock.local_addr().ok().map(|a| a.port()),
746                })
747        };
748        if let Some(port) = port {
749            let stack = push(stack, Value::Int(port as i64));
750            return push(stack, Value::Bool(true));
751        }
752        let port: Option<u16> = {
753            let mut listeners = LISTENERS.lock().unwrap();
754            listeners
755                .get_mut(socket_id)
756                .and_then(|slot| slot.as_ref())
757                .and_then(|l| l.local_addr().ok())
758                .map(|a| a.port())
759        };
760        if let Some(port) = port {
761            let stack = push(stack, Value::Int(port as i64));
762            return push(stack, Value::Bool(true));
763        }
764
765        let stack = push(stack, Value::Int(0));
766        push(stack, Value::Bool(false))
767    }
768}
769
770/// Cast between Socket and Int (both directions): identity at runtime.
771///
772/// Socket is a compile-time-only nominal wrapper over the same i64 file
773/// descriptor; the type checker enforces the distinction. This shim exists
774/// so codegen can emit a callable symbol for `fd->socket` / `socket->fd`
775/// without inventing a new value tag.
776///
777/// # Safety
778/// Stack must have an Int (or Socket-shaped Int) value on top.
779#[unsafe(no_mangle)]
780pub unsafe extern "C" fn patch_seq_socket_cast(stack: Stack) -> Stack {
781    assert!(!stack.is_null(), "fd<->socket cast: stack is empty");
782    let (rest, val) = unsafe { pop(stack) };
783    match val {
784        Value::Int(fd) => unsafe { push(rest, Value::Int(fd)) },
785        _ => panic!("fd<->socket cast: expected Int on stack"),
786    }
787}
788
789#[cfg(test)]
790mod tests;