Skip to main content

nodejs/stdlib/
dgram.rs

1//! Node `dgram` module: real UDP sockets over `std::net::UdpSocket`.
2//!
3//! Threading model mirrors `net` (see `host::run_event_loop`): each bound socket
4//! runs a `recv_from` loop on its own thread. That thread NEVER touches the JS
5//! heap — it only moves raw datagram bytes and posts `IoTask` closures onto the
6//! host channel. Every JS-visible effect (emitting `message`/`listening`/`close`,
7//! running callbacks) happens on the main thread when the event loop runs the
8//! posted closure. The `UdpSocket` is shared with the recv thread through an
9//! `Arc` (both `recv_from` and `send_to` take `&self`). All main-thread records
10//! live in a `thread_local`, so they need no locking of their own.
11
12use crate::host::{invoke, with_host, JsObj};
13use fusevm::Value;
14use indexmap::IndexMap;
15use std::collections::HashMap;
16use std::net::UdpSocket;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::Arc;
19use std::time::Duration;
20
21/// `dgram` module functions routed through `stdlib::call`.
22pub const MODULE_METHODS: &[&str] = &["createSocket"];
23
24/// The `dgram.Socket` `@@native` tag.
25pub const SOCKET_TAG: &str = "UdpSocket";
26
27/// Instance methods on a `dgram.Socket` (for `instance_has_method` / dispatch).
28pub const SOCKET_METHODS: &[&str] = &[
29    "bind",
30    "send",
31    "close",
32    "address",
33    "setBroadcast",
34    "setTTL",
35    "setMulticastTTL",
36    "setMulticastLoopback",
37    "setMulticastInterface",
38    "addMembership",
39    "dropMembership",
40    "addSourceSpecificMembership",
41    "dropSourceSpecificMembership",
42    "setRecvBufferSize",
43    "setSendBufferSize",
44    "getRecvBufferSize",
45    "getSendBufferSize",
46    "connect",
47    "disconnect",
48    "remoteAddress",
49    "ref",
50    "unref",
51];
52
53/// How long a `recv_from` blocks before the loop re-checks its stop flag.
54const POLL: Duration = Duration::from_millis(200);
55
56/// Main-thread record for a bound socket.
57struct UdpRec {
58    /// The JS socket object (a native emitter).
59    emitter: Value,
60    /// The live UDP socket, shared with the recv thread.
61    socket: Arc<UdpSocket>,
62    /// Set by `close` to stop the `recv_from` loop.
63    stop: Arc<AtomicBool>,
64}
65
66#[derive(Default)]
67struct DgramState {
68    next_id: u64,
69    sockets: HashMap<u64, UdpRec>,
70}
71
72thread_local! {
73    static DGRAM: std::cell::RefCell<DgramState> = std::cell::RefCell::new(DgramState::default());
74}
75
76fn next_id() -> u64 {
77    DGRAM.with(|s| {
78        let mut s = s.borrow_mut();
79        s.next_id += 1;
80        s.next_id
81    })
82}
83
84// ── object helpers ────────────────────────────────────────────────────────────
85
86fn get_prop(recv: &Value, key: &str) -> Option<Value> {
87    with_host(|h| match h.get(recv) {
88        Some(JsObj::Object(p)) => p.get(key).cloned(),
89        _ => None,
90    })
91}
92
93fn set_prop(recv: &Value, key: &str, val: Value) {
94    with_host(|h| {
95        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
96            p.insert(key.to_string(), val);
97        }
98    });
99}
100
101fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
102    get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
103}
104
105fn is_udp6(recv: &Value) -> bool {
106    get_prop(recv, "@@udptype")
107        .map(|v| with_host(|h| h.str_of(&v)))
108        .as_deref()
109        == Some("udp6")
110}
111
112/// The default bind/target host for this socket's address family.
113fn default_bind_host(recv: &Value) -> &'static str {
114    if is_udp6(recv) {
115        "::"
116    } else {
117        "0.0.0.0"
118    }
119}
120
121fn default_send_host(recv: &Value) -> &'static str {
122    if is_udp6(recv) {
123        "::1"
124    } else {
125        "127.0.0.1"
126    }
127}
128
129fn is_num(v: &Value) -> bool {
130    matches!(v, Value::Float(_) | Value::Int(_))
131}
132
133fn is_str(v: &Value) -> bool {
134    matches!(v, Value::Str(_)) || with_host(|h| matches!(h.get(v), Some(JsObj::Str(_))))
135}
136
137/// Raw bytes of a `send` message argument: a Buffer's `@@bytes`, else a string's
138/// UTF-8 (mirrors `net::value_bytes`).
139fn value_bytes(v: &Value) -> Vec<u8> {
140    let is_buffer =
141        with_host(|h| matches!(h.get(v), Some(JsObj::Object(p)) if p.contains_key("@@bytes")));
142    if is_buffer {
143        return with_host(|h| match h.get(v) {
144            Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
145            _ => Vec::new(),
146        });
147    }
148    with_host(|h| h.str_of(v)).into_bytes()
149}
150
151/// Delegate the EventEmitter methods to `events`; `None` for a non-emitter method.
152fn emitter_dispatch(recv: &Value, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
153    super::events::METHODS
154        .contains(&method)
155        .then(|| super::events::instance_call(recv, method, args.to_vec()))
156}
157
158// ── module: dgram.createSocket ────────────────────────────────────────────────
159
160/// `stdlib::call` entry for `dgram.<method>`.
161pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
162    match method {
163        "createSocket" => Some(Ok(create_socket(args))),
164        _ => None,
165    }
166}
167
168/// `dgram.createSocket(type[, callback])` or `dgram.createSocket(options[, callback])`.
169/// `type` is `'udp4'`/`'udp6'`; an options object reads its `.type`. A `callback`
170/// is registered as a one-time-per-`emit` `'message'` listener (Node semantics).
171pub fn create_socket(args: &[Value]) -> Value {
172    let first = args.first().cloned().unwrap_or(Value::Undef);
173    let sock_type = if is_str(&first) {
174        with_host(|h| h.str_of(&first))
175    } else {
176        // options object: read `.type`.
177        with_host(|h| match h.get(&first) {
178            Some(JsObj::Object(p)) => p.get("type").map(|v| h.str_of(v)),
179            _ => None,
180        })
181        .unwrap_or_else(|| "udp4".to_string())
182    };
183    let sock_type = if sock_type == "udp6" { "udp6" } else { "udp4" };
184
185    let mut extra = IndexMap::new();
186    extra.insert("@@udptype".into(), with_host(|h| h.new_str(sock_type)));
187    let socket = super::net::new_emitter_object(SOCKET_TAG, extra);
188
189    // A trailing callback becomes a `message` listener.
190    if let Some(cb) = args
191        .get(1)
192        .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
193    {
194        let _ = super::events::instance_call(
195            &socket,
196            "on",
197            vec![with_host(|h| h.new_str("message")), cb.clone()],
198        );
199    }
200    socket
201}
202
203// ── instance dispatch ─────────────────────────────────────────────────────────
204
205pub fn instance_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
206    if let Some(r) = emitter_dispatch(recv, method, &args) {
207        return r;
208    }
209    match method {
210        "bind" => socket_bind(recv, &args),
211        "send" => socket_send(recv, &args),
212        "close" => socket_close(recv, &args),
213        "address" => socket_address(recv),
214        // Best-effort socket options: applied to the live `UdpSocket` where std
215        // exposes them, otherwise accepted no-ops (multicast/buffer sizing).
216        "setBroadcast" => {
217            let on = with_host(|h| h.truthy(args.first().unwrap_or(&Value::Undef)));
218            if let Some(sock) = live_socket(recv) {
219                sock.set_broadcast(on).ok();
220            }
221            Ok(recv.clone())
222        }
223        "setTTL" | "setMulticastTTL" => {
224            let ttl = with_host(|h| h.to_number(args.first().unwrap_or(&Value::Undef))) as u32;
225            if let Some(sock) = live_socket(recv) {
226                if method == "setTTL" {
227                    sock.set_ttl(ttl).ok();
228                } else {
229                    sock.set_multicast_ttl_v4(ttl).ok();
230                }
231            }
232            Ok(args.first().cloned().unwrap_or(Value::Undef))
233        }
234        "getRecvBufferSize" | "getSendBufferSize" => Ok(Value::Float(65536.0)),
235        // Accepted no-ops: multicast membership, buffer sizing, connect/disconnect,
236        // ref counting. Documented as best-effort — std::net exposes no portable
237        // API for most, and the datagram path does not need them.
238        "setMulticastLoopback"
239        | "setMulticastInterface"
240        | "addMembership"
241        | "dropMembership"
242        | "addSourceSpecificMembership"
243        | "dropSourceSpecificMembership"
244        | "setRecvBufferSize"
245        | "setSendBufferSize"
246        | "connect"
247        | "disconnect"
248        | "remoteAddress"
249        | "ref"
250        | "unref" => Ok(recv.clone()),
251        _ => Err(crate::host::type_error(&format!(
252            "socket.{method} is not a function"
253        ))),
254    }
255}
256
257/// The live `UdpSocket` for `recv`, if it is currently bound.
258fn live_socket(recv: &Value) -> Option<Arc<UdpSocket>> {
259    let id = u64_prop(recv, "@@dgramid")?;
260    DGRAM.with(|s| s.borrow().sockets.get(&id).map(|r| r.socket.clone()))
261}
262
263// ── bind ──────────────────────────────────────────────────────────────────────
264
265/// `socket.bind([port][, address][, callback])`. Binds on the main thread (so a
266/// bind error surfaces from the call), registers the socket as a live handle, and
267/// spawns the `recv_from` loop. The `listening` event + callback fire
268/// asynchronously via a posted `IoTask`.
269fn socket_bind(recv: &Value, args: &[Value]) -> Result<Value, String> {
270    // Argument shapes: (), (port), (port, cb), (port, addr), (port, addr, cb),
271    // and an options-object first arg `{ port, address }`.
272    let mut port: u16 = 0;
273    let mut host = default_bind_host(recv).to_string();
274    let mut cb: Option<Value> = None;
275
276    if let Some(first) = args.first() {
277        if is_num(first) {
278            port = with_host(|h| h.to_number(first)) as u16;
279        } else if with_host(
280            |h| matches!(h.get(first), Some(JsObj::Object(p)) if !p.contains_key("@@native")),
281        ) {
282            // Options object `{ port, address }`.
283            with_host(|h| {
284                if let Some(JsObj::Object(p)) = h.get(first) {
285                    if let Some(pv) = p.get("port") {
286                        port = h.to_number(pv) as u16;
287                    }
288                    if let Some(av) = p.get("address").map(|v| h.str_of(v)) {
289                        host = av;
290                    }
291                }
292            });
293        }
294    }
295    for a in args.iter().skip(1) {
296        if is_str(a) {
297            host = with_host(|h| h.str_of(a));
298        } else if with_host(|h| crate::host::is_callable(h, a)) {
299            cb = Some(a.clone());
300        }
301    }
302
303    do_bind(recv, &host, port)?;
304
305    // Fire `listening` + callback asynchronously on the main thread.
306    let socket = recv.clone();
307    let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
308        if let Some(cb) = cb {
309            super::events::instance_call(
310                &socket,
311                "once",
312                vec![with_host(|h| h.new_str("listening")), cb],
313            )?;
314        }
315        super::events::instance_call(&socket, "emit", vec![with_host(|h| h.new_str("listening"))])?;
316        Ok(())
317    }));
318    Ok(recv.clone())
319}
320
321/// Bind the socket (idempotent: returns the existing socket if already bound),
322/// register its record, take an event-loop handle, and spawn the recv loop.
323fn do_bind(recv: &Value, host: &str, port: u16) -> Result<Arc<UdpSocket>, String> {
324    if let Some(sock) = live_socket(recv) {
325        return Ok(sock);
326    }
327    let socket =
328        UdpSocket::bind((host, port)).map_err(|e| format!("Error: bind EADDRINUSE: {e}"))?;
329    // A read timeout lets the recv loop re-check its stop flag on a quiet socket.
330    socket.set_read_timeout(Some(POLL)).ok();
331    let socket = Arc::new(socket);
332
333    let id = next_id();
334    set_prop(recv, "@@dgramid", Value::Float(id as f64));
335    let stop = Arc::new(AtomicBool::new(false));
336    DGRAM.with(|s| {
337        s.borrow_mut().sockets.insert(
338            id,
339            UdpRec {
340                emitter: recv.clone(),
341                socket: socket.clone(),
342                stop: stop.clone(),
343            },
344        );
345    });
346    with_host(|h| h.incr_handle());
347
348    // Spawn the recv loop: raw datagrams → posted IoTasks. Never touches the host.
349    let tx = with_host(|h| h.io_sender());
350    let recv_sock = socket.clone();
351    std::thread::spawn(move || recv_loop(recv_sock, id, stop, tx));
352
353    Ok(socket)
354}
355
356/// Background reader: blocking `recv_from` loop posting `message` events. Runs off
357/// the main thread and only moves `Send` data (bytes, addr, port) into the closure.
358fn recv_loop(
359    socket: Arc<UdpSocket>,
360    id: u64,
361    stop: Arc<AtomicBool>,
362    tx: std::sync::mpsc::Sender<crate::host::IoTask>,
363) {
364    let mut buf = [0u8; 65536];
365    loop {
366        if stop.load(Ordering::Acquire) {
367            break;
368        }
369        match socket.recv_from(&mut buf) {
370            Ok((n, src)) => {
371                let bytes = buf[..n].to_vec();
372                let address = src.ip().to_string();
373                let port = src.port();
374                let family = if src.is_ipv6() { "IPv6" } else { "IPv4" };
375                let _ = tx.send(Box::new(move || {
376                    on_message(id, bytes, address, port, family)
377                }));
378            }
379            // A read-timeout (or non-blocking would-block) just re-checks `stop`.
380            Err(ref e)
381                if e.kind() == std::io::ErrorKind::WouldBlock
382                    || e.kind() == std::io::ErrorKind::TimedOut =>
383            {
384                continue;
385            }
386            Err(_) => break,
387        }
388    }
389}
390
391/// Main-thread delivery of one datagram: emit `message` with `(msg, rinfo)` where
392/// `rinfo = { address, family, port, size }` (matching Node).
393fn on_message(
394    id: u64,
395    bytes: Vec<u8>,
396    address: String,
397    port: u16,
398    family: &'static str,
399) -> Result<(), String> {
400    let socket = DGRAM.with(|s| s.borrow().sockets.get(&id).map(|r| r.emitter.clone()));
401    let Some(socket) = socket else { return Ok(()) };
402
403    let size = bytes.len();
404    let msg = super::buffer::from_bytes(&bytes);
405    let rinfo = with_host(|h| {
406        let mut m = IndexMap::new();
407        m.insert("address".into(), h.new_str(address));
408        m.insert("family".into(), h.new_str(family));
409        m.insert("port".into(), Value::Float(port as f64));
410        m.insert("size".into(), Value::Float(size as f64));
411        h.new_object(m)
412    });
413    super::events::instance_call(
414        &socket,
415        "emit",
416        vec![with_host(|h| h.new_str("message")), msg, rinfo],
417    )?;
418    Ok(())
419}
420
421// ── send ──────────────────────────────────────────────────────────────────────
422
423/// `socket.send(msg[, offset, length], port[, address][, callback])`. Auto-binds
424/// to an ephemeral port on the socket's address family if not yet bound (Node
425/// semantics), then `send_to` the bytes. The callback fires with `null` on
426/// success (asynchronously, on the main thread).
427fn socket_send(recv: &Value, args: &[Value]) -> Result<Value, String> {
428    let msg = args.first().cloned().unwrap_or(Value::Undef);
429    let full = value_bytes(&msg);
430
431    // Collect the leading numeric args after `msg`: either `[port]` or
432    // `[offset, length, port]` (Node distinguishes by count).
433    let mut nums: Vec<f64> = Vec::new();
434    let mut i = 1;
435    while i < args.len() && is_num(&args[i]) {
436        nums.push(with_host(|h| h.to_number(&args[i])));
437        i += 1;
438    }
439    let (offset, length, port) = if nums.len() >= 3 {
440        (
441            nums[0].max(0.0) as usize,
442            nums[1].max(0.0) as usize,
443            nums[2] as u16,
444        )
445    } else if let Some(p) = nums.first() {
446        (0usize, full.len(), *p as u16)
447    } else {
448        return Err(crate::host::type_error("Port should be > 0 and < 65536"));
449    };
450
451    // Trailing args: optional address (string) then optional callback.
452    let mut address = default_send_host(recv).to_string();
453    let mut cb: Option<Value> = None;
454    for a in args.iter().skip(i) {
455        if is_str(a) {
456            address = with_host(|h| h.str_of(a));
457        } else if with_host(|h| crate::host::is_callable(h, a)) {
458            cb = Some(a.clone());
459        }
460    }
461
462    // Slice the payload to [offset, offset+length).
463    let end = offset.saturating_add(length).min(full.len());
464    let start = offset.min(full.len());
465    let data = &full[start..end.max(start)];
466
467    // Auto-bind to an ephemeral port on the socket's family if needed.
468    let socket = do_bind(recv, default_bind_host(recv), 0)?;
469    socket
470        .send_to(data, (address.as_str(), port))
471        .map_err(|e| format!("Error: send {e}"))?;
472
473    // The send callback fires asynchronously with `(null)`.
474    if let Some(cb) = cb {
475        let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
476            let nul = with_host(|h| h.null());
477            invoke(&cb, vec![nul], None)?;
478            Ok(())
479        }));
480    }
481    Ok(Value::Undef)
482}
483
484// ── close / address ───────────────────────────────────────────────────────────
485
486/// `socket.close([callback])`: stop the recv loop, drop the handle, emit `close`,
487/// and wake the event loop so a closed last handle lets it exit.
488fn socket_close(recv: &Value, args: &[Value]) -> Result<Value, String> {
489    if let Some(id) = u64_prop(recv, "@@dgramid") {
490        let rec = DGRAM.with(|s| s.borrow_mut().sockets.remove(&id));
491        if let Some(rec) = rec {
492            rec.stop.store(true, Ordering::Release);
493            with_host(|h| h.decr_handle());
494            // Wake the blocking loop so it can re-evaluate `open_handles`.
495            let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
496        }
497    }
498    // A `close` callback registers as a one-shot `close` listener in Node.
499    if let Some(cb) = args
500        .first()
501        .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
502    {
503        invoke(cb, Vec::new(), None)?;
504    }
505    super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))])?;
506    Ok(Value::Undef)
507}
508
509/// `socket.address()` → `{ address, family, port }` from `local_addr`. Throws if
510/// the socket is not bound (matching Node's `Not running` error).
511fn socket_address(recv: &Value) -> Result<Value, String> {
512    let socket = live_socket(recv)
513        .ok_or_else(|| "Error: getsockname EBADF: bad file descriptor".to_string())?;
514    let addr = socket
515        .local_addr()
516        .map_err(|e| format!("Error: getsockname {e}"))?;
517    Ok(with_host(|h| {
518        let mut m = IndexMap::new();
519        m.insert("address".into(), h.new_str(addr.ip().to_string()));
520        m.insert(
521            "family".into(),
522            h.new_str(if addr.is_ipv6() { "IPv6" } else { "IPv4" }),
523        );
524        m.insert("port".into(), Value::Float(addr.port() as f64));
525        h.new_object(m)
526    }))
527}