Skip to main content

nodejs/stdlib/
http2.rs

1//! Node `http2` module: a REAL, minimal HTTP/2 server over TLS+ALPN.
2//!
3//! This is a genuine HTTP/2 server (RFC 7540 framing + RFC 7541 HPACK via the
4//! `hpack` crate) layered on the same blocking-`rustls` model as `tls`/`https`.
5//! A real h2 client (`curl --http2`, `nghttp`, Node's `http2` client) can perform
6//! a GET and receive a response body from a server built with
7//! `http2.createSecureServer`.
8//!
9//! ── Threading model (identical discipline to `net`/`tls`) ────────────────────
10//! Background threads NEVER touch the JS heap (a main-thread `thread_local`). One
11//! thread per TCP connection owns the `rustls::StreamOwned`, performs the TLS
12//! handshake (negotiating ALPN `h2`), then runs the full HTTP/2 framing loop:
13//! reading/parsing frames and writing response frames. HPACK `Encoder`/`Decoder`
14//! (with their connection-scoped dynamic tables) live on that thread. Every
15//! JS-visible effect — building the `Http2Stream`/`Http2Session` objects, emitting
16//! `stream`/`session`/`request`, running listeners — happens on the main thread
17//! via posted `IoTask` closures. The stream objects talk back to their connection
18//! thread through an `mpsc` channel of `H2Cmd`s (`respond`/`write`/`end` enqueue a
19//! command; the owner thread encodes+writes the frame), so reads and writes stay
20//! on the single thread that owns the stateful TLS + HPACK cipher/table state.
21//!
22//! ── What IS implemented (server) ─────────────────────────────────────────────
23//!   * TLS handshake with ALPN offering only `h2`; non-`h2` clients are closed.
24//!   * Client connection preface check (`PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n`).
25//!   * SETTINGS: we send our (empty, valid) SETTINGS; we ACK the client's SETTINGS
26//!     and ignore incoming SETTINGS ACKs.
27//!   * HEADERS (type 1) inbound: PADDED + PRIORITY flags stripped, header block
28//!     HPACK-decoded into pseudo-headers (`:method`/`:path`/`:scheme`/`:authority`)
29//!     + regular headers. Fires `stream` (and compat `request`).
30//!   * DATA (type 0) inbound: emitted on the stream as `data`/`end` (request body).
31//!   * `Http2Stream.respond(headers)` → HPACK-encoded HEADERS with `:status`.
32//!   * `Http2Stream.write(data)` / `.end([data])` → DATA frames (END_STREAM on end),
33//!     chunked to <= 16384 (the default SETTINGS_MAX_FRAME_SIZE) per frame.
34//!   * PING (type 6): answered with a PING ACK echoing the 8-byte payload.
35//!   * WINDOW_UPDATE (type 8) / PRIORITY (type 2) / RST_STREAM (type 3): accepted
36//!     and ignored (large-enough default windows; see caveats).
37//!   * GOAWAY (type 7): sent on connection close; inbound GOAWAY ends the loop.
38//!
39//! ── Honest limitations (NOT implemented — deliberately, not faked) ────────────
40//!   * `http2.connect` (CLIENT) is NOT implemented — it throws a clear error.
41//!   * `http2.createServer` (cleartext h2c / prior-knowledge) is NOT implemented.
42//!   * CONTINUATION frames (type 9): a HEADERS frame WITHOUT END_HEADERS is not
43//!     reassembled — that stream is skipped. Real clients pack a single small GET
44//!     header block into one HEADERS frame, so this rarely triggers, but a very
45//!     large request header block would be dropped rather than mis-parsed.
46//!   * Flow control is minimal: we advertise/assume the default windows and IGNORE
47//!     inbound WINDOW_UPDATE for our own send side. A response body larger than the
48//!     peer's stream/connection window (65535 bytes by default) can STALL. Small
49//!     responses (the common case, and the test target) are unaffected.
50//!   * No server push, no trailers, no PRIORITY tree, no per-stream RST bookkeeping,
51//!     no ALTSVC/ORIGIN. These are absent, never stubbed to look present.
52//!
53//! ── Handler-fault isolation (why the server used to close right after HEADERS) ─
54//! The event loop treats an `Err` returned from a posted `IoTask` as FATAL
55//! (`host::drive_event_loop` runs `task()?`), which terminates the whole process
56//! and closes every live socket. `events::emit` propagates a listener's error
57//! (`invoke(&f, …)?`). So an exception thrown by the user's `stream`/`request`
58//! handler used to bubble out of the connection's `on_headers` IoTask and kill the
59//! server the instant the first request arrived — the client sees the TCP close as
60//! a "broken pipe" with no response. To prevent one faulty handler from taking
61//! down the server, the connection IoTasks (`on_headers`/`on_data`/`on_session`)
62//! CATCH handler errors, print them to stderr (like Node's uncaught-exception
63//! output, so the cause is visible), and return `Ok` — the loop and other
64//! connections survive. Set `HTTP2_DEBUG=1` to trace every frame in/out on stderr.
65//!
66//! ── Verification status ──────────────────────────────────────────────────────
67//! The framing (9-octet header layout, big-endian 24-bit length, frame type/flag
68//! values, HPACK usage) is written to RFC 7540/7541. It has NOT been compiled or
69//! run in this session (the parent owns the shared build), so the byte-level
70//! correctness is verified-by-construction against the RFCs, not by a live curl.
71//! See the final report for the exact `curl --http2` command to confirm it.
72
73use crate::host::{invoke, with_host, IoTask, JsObj};
74use fusevm::Value;
75use hpack::{Decoder, Encoder};
76use indexmap::IndexMap;
77use rustls::pki_types::{CertificateDer, PrivateKeyDer};
78use rustls::{ServerConfig, ServerConnection, StreamOwned};
79use std::collections::HashMap;
80use std::io::{Read, Write};
81use std::net::{TcpListener, TcpStream};
82use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
83use std::sync::mpsc::Sender;
84use std::sync::Arc;
85
86/// `http2` module functions routed through `stdlib::call`.
87pub const METHODS: &[&str] = &[
88    "createSecureServer",
89    "createServer",
90    "connect",
91    "getDefaultSettings",
92    "getPackedSettings",
93    "getUnpackedSettings",
94];
95
96/// Instance method names for the `@@native` tags this module owns (exposed to
97/// `stdlib::instance_has_method` so a method *read* yields a bound method).
98pub const SERVER_METHODS: &[&str] = &["listen", "close", "address", "setTimeout"];
99pub const STREAM_METHODS: &[&str] = &[
100    "respond",
101    "write",
102    "end",
103    "close",
104    "setEncoding",
105    "setTimeout",
106    "pause",
107    "resume",
108    // HTTP/1-compat surface (Http2ServerResponse), best-effort:
109    "writeHead",
110    "setHeader",
111    "getHeader",
112    "removeHeader",
113];
114pub const SESSION_METHODS: &[&str] = &[
115    "settings",
116    "ping",
117    "goaway",
118    "close",
119    "destroy",
120    "ref",
121    "unref",
122    "setTimeout",
123];
124
125// ── HTTP/2 constants (RFC 7540 §6, §11) ──────────────────────────────────────
126
127const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
128
129// Frame types.
130const FT_DATA: u8 = 0x0;
131const FT_HEADERS: u8 = 0x1;
132const FT_PRIORITY: u8 = 0x2;
133const FT_RST_STREAM: u8 = 0x3;
134const FT_SETTINGS: u8 = 0x4;
135const FT_PING: u8 = 0x6;
136const FT_GOAWAY: u8 = 0x7;
137const FT_WINDOW_UPDATE: u8 = 0x8;
138const FT_CONTINUATION: u8 = 0x9;
139
140// Frame flags.
141const FL_END_STREAM: u8 = 0x1;
142const FL_ACK: u8 = 0x1; // SETTINGS/PING re-use bit 0 as ACK
143const FL_END_HEADERS: u8 = 0x4;
144const FL_PADDED: u8 = 0x8;
145const FL_PRIORITY: u8 = 0x20;
146
147/// Default SETTINGS_MAX_FRAME_SIZE — the largest DATA payload we emit per frame.
148const MAX_FRAME_SIZE: usize = 16384;
149
150// ── process-global id sources (ids minted on background threads) ─────────────
151
152static NEXT_SERVER_ID: AtomicU64 = AtomicU64::new(1);
153static NEXT_STREAM_KEY: AtomicU64 = AtomicU64::new(1);
154static NEXT_SESSION_KEY: AtomicU64 = AtomicU64::new(1);
155
156fn next_server_id() -> u64 {
157    NEXT_SERVER_ID.fetch_add(1, Ordering::Relaxed)
158}
159fn next_stream_key() -> u64 {
160    NEXT_STREAM_KEY.fetch_add(1, Ordering::Relaxed)
161}
162fn next_session_key() -> u64 {
163    NEXT_SESSION_KEY.fetch_add(1, Ordering::Relaxed)
164}
165
166// ── commands from the main thread to a connection's owner thread ─────────────
167
168/// A frame the owner thread should encode + write, produced by JS method calls.
169enum H2Cmd {
170    /// Send a HEADERS frame carrying the given (already ordered, `:status`-first)
171    /// header list; `end` sets END_STREAM (a header-only response).
172    Respond {
173        stream_id: u32,
174        headers: Vec<(String, String)>,
175        end: bool,
176    },
177    /// Send DATA (chunked to MAX_FRAME_SIZE); `end` sets END_STREAM on the last.
178    Data {
179        stream_id: u32,
180        data: Vec<u8>,
181        end: bool,
182    },
183    /// RST_STREAM with NO_ERROR.
184    Close { stream_id: u32 },
185    /// GOAWAY(NO_ERROR) then terminate the owner loop.
186    Goaway,
187}
188
189// ── main-thread state ────────────────────────────────────────────────────────
190
191struct H2ServerRec {
192    emitter: Value,
193    stop: Arc<AtomicBool>,
194}
195
196struct H2StreamRec {
197    emitter: Value,
198    tx: Sender<H2Cmd>,
199    stream_id: u32,
200    /// True once a HEADERS response frame has been sent (respond/writeHead).
201    responded: bool,
202}
203
204struct H2SessionRec {
205    #[allow(dead_code)]
206    emitter: Value,
207    tx: Sender<H2Cmd>,
208}
209
210#[derive(Default)]
211struct H2State {
212    servers: HashMap<u64, H2ServerRec>,
213    streams: HashMap<u64, H2StreamRec>,
214    sessions: HashMap<u64, H2SessionRec>,
215}
216
217thread_local! {
218    static H2: std::cell::RefCell<H2State> = std::cell::RefCell::new(H2State::default());
219    /// `ServerConfig`s built by `createSecureServer` before `listen` assigns an id
220    /// (mirrors `tls::PENDING_CONFIGS`).
221    static PENDING_CONFIGS: std::cell::RefCell<Vec<(Value, Arc<ServerConfig>)>> =
222        const { std::cell::RefCell::new(Vec::new()) };
223}
224
225// ── shared object / prop helpers (same shape as net/tls) ─────────────────────
226
227fn get_prop(recv: &Value, key: &str) -> Option<Value> {
228    with_host(|h| match h.get(recv) {
229        Some(JsObj::Object(p)) => p.get(key).cloned(),
230        _ => None,
231    })
232}
233
234fn set_prop(recv: &Value, key: &str, val: Value) {
235    with_host(|h| {
236        if let Some(JsObj::Object(p)) = h.get_mut(recv) {
237            p.insert(key.to_string(), val);
238        }
239    });
240}
241
242fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
243    get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
244}
245
246/// Delegate the EventEmitter surface to `events`; `None` for a non-emitter method.
247fn emitter_dispatch(recv: &Value, method: &str, args: &[Value]) -> Option<Result<Value, String>> {
248    super::events::METHODS
249        .contains(&method)
250        .then(|| super::events::instance_call(recv, method, args.to_vec()))
251}
252
253/// Raw bytes of a `write`/`end`/`key`/`cert` argument (Buffer bytes or UTF-8).
254fn value_bytes(v: Option<&Value>) -> Vec<u8> {
255    let Some(v) = v else { return Vec::new() };
256    let is_buffer =
257        with_host(|h| matches!(h.get(v), Some(JsObj::Object(p)) if p.contains_key("@@bytes")));
258    if is_buffer {
259        return with_host(|h| match h.get(v) {
260            Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
261            _ => Vec::new(),
262        });
263    }
264    with_host(|h| h.str_of(v)).into_bytes()
265}
266
267/// Enumerable string key/value pairs of a plain object (for a `respond`/`writeHead`
268/// headers argument). Hidden `@@`/`#` keys are skipped.
269fn object_pairs(obj: &Value) -> Vec<(String, String)> {
270    with_host(|h| match h.get(obj) {
271        Some(JsObj::Object(p)) => p
272            .iter()
273            .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
274            .map(|(k, v)| (k.clone(), h.str_of(v)))
275            .collect(),
276        _ => Vec::new(),
277    })
278}
279
280// ── module entry ─────────────────────────────────────────────────────────────
281
282/// `stdlib::call` entry for `http2.<method>`.
283pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
284    Some(match method {
285        "createSecureServer" => create_secure_server(args),
286        "createServer" => Err(
287            "Error: http2.createServer (cleartext h2c / prior-knowledge) \
288            is not implemented in node-js; use http2.createSecureServer (h2 over TLS)"
289                .to_string(),
290        ),
291        "connect" => Err(
292            "Error: http2.connect (HTTP/2 client) is not implemented in node-js; \
293            only the HTTP/2 server (http2.createSecureServer) is implemented"
294                .to_string(),
295        ),
296        "getDefaultSettings" => Ok(default_settings_object()),
297        "getPackedSettings" => Ok(pack_settings(args)),
298        "getUnpackedSettings" => unpack_settings(args),
299        _ => return None,
300    })
301}
302
303/// `http2.constants` and other non-function properties, reachable via
304/// `namespace_property` → `stdlib::constant`.
305pub fn constant(name: &str) -> Option<Value> {
306    match name {
307        "constants" => Some(constants_object()),
308        // Expose ctor namespaces so `http2.Http2ServerRequest.prototype` etc. resolve
309        // to *something* (they are not separately constructable here).
310        "Http2ServerRequest" => Some(with_host(|h| {
311            h.alloc(JsObj::Builtin("Http2ServerRequest".into()))
312        })),
313        "Http2ServerResponse" => Some(with_host(|h| {
314            h.alloc(JsObj::Builtin("Http2ServerResponse".into()))
315        })),
316        _ => None,
317    }
318}
319
320/// The `http2.constants` object (a representative subset of RFC 7540 / nghttp2
321/// names — HTTP status codes, header-name constants, and error/settings codes).
322fn constants_object() -> Value {
323    with_host(|h| {
324        let mut m = IndexMap::new();
325        let put_i = |m: &mut IndexMap<String, Value>, k: &str, v: i64| {
326            m.insert(k.to_string(), Value::Float(v as f64));
327        };
328        // Common HTTP status constants.
329        put_i(&mut m, "HTTP_STATUS_OK", 200);
330        put_i(&mut m, "HTTP_STATUS_NO_CONTENT", 204);
331        put_i(&mut m, "HTTP_STATUS_MOVED_PERMANENTLY", 301);
332        put_i(&mut m, "HTTP_STATUS_FOUND", 302);
333        put_i(&mut m, "HTTP_STATUS_NOT_MODIFIED", 304);
334        put_i(&mut m, "HTTP_STATUS_BAD_REQUEST", 400);
335        put_i(&mut m, "HTTP_STATUS_UNAUTHORIZED", 401);
336        put_i(&mut m, "HTTP_STATUS_FORBIDDEN", 403);
337        put_i(&mut m, "HTTP_STATUS_NOT_FOUND", 404);
338        put_i(&mut m, "HTTP_STATUS_INTERNAL_SERVER_ERROR", 500);
339        // NGHTTP2 error codes (RFC 7540 §7).
340        put_i(&mut m, "NGHTTP2_NO_ERROR", 0x0);
341        put_i(&mut m, "NGHTTP2_PROTOCOL_ERROR", 0x1);
342        put_i(&mut m, "NGHTTP2_INTERNAL_ERROR", 0x2);
343        put_i(&mut m, "NGHTTP2_FLOW_CONTROL_ERROR", 0x3);
344        put_i(&mut m, "NGHTTP2_SETTINGS_TIMEOUT", 0x4);
345        put_i(&mut m, "NGHTTP2_STREAM_CLOSED", 0x5);
346        put_i(&mut m, "NGHTTP2_FRAME_SIZE_ERROR", 0x6);
347        put_i(&mut m, "NGHTTP2_REFUSED_STREAM", 0x7);
348        put_i(&mut m, "NGHTTP2_CANCEL", 0x8);
349        put_i(&mut m, "NGHTTP2_COMPRESSION_ERROR", 0x9);
350        put_i(&mut m, "NGHTTP2_ENHANCE_YOUR_CALM", 0xb);
351        // SETTINGS identifiers (RFC 7540 §6.5.2).
352        put_i(&mut m, "NGHTTP2_SETTINGS_HEADER_TABLE_SIZE", 0x1);
353        put_i(&mut m, "NGHTTP2_SETTINGS_ENABLE_PUSH", 0x2);
354        put_i(&mut m, "NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS", 0x3);
355        put_i(&mut m, "NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE", 0x4);
356        put_i(&mut m, "NGHTTP2_SETTINGS_MAX_FRAME_SIZE", 0x5);
357        put_i(&mut m, "NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE", 0x6);
358        // A representative subset of the HTTP2_HEADER_* string constants.
359        let hdr =
360            |m: &mut IndexMap<String, Value>, k: &str, v: &str, h: &mut crate::host::JsHost| {
361                let s = h.new_str(v);
362                m.insert(k.to_string(), s);
363            };
364        hdr(&mut m, "HTTP2_HEADER_STATUS", ":status", h);
365        hdr(&mut m, "HTTP2_HEADER_METHOD", ":method", h);
366        hdr(&mut m, "HTTP2_HEADER_AUTHORITY", ":authority", h);
367        hdr(&mut m, "HTTP2_HEADER_SCHEME", ":scheme", h);
368        hdr(&mut m, "HTTP2_HEADER_PATH", ":path", h);
369        hdr(&mut m, "HTTP2_HEADER_CONTENT_TYPE", "content-type", h);
370        hdr(&mut m, "HTTP2_HEADER_CONTENT_LENGTH", "content-length", h);
371        hdr(&mut m, "HTTP2_METHOD_GET", "GET", h);
372        hdr(&mut m, "HTTP2_METHOD_POST", "POST", h);
373        h.new_object(m)
374    })
375}
376
377/// A minimal default-settings object (Node's `http2.getDefaultSettings()` shape).
378fn default_settings_object() -> Value {
379    with_host(|h| {
380        let mut m = IndexMap::new();
381        m.insert("headerTableSize".into(), Value::Float(4096.0));
382        m.insert("enablePush".into(), Value::Bool(false));
383        m.insert("initialWindowSize".into(), Value::Float(65535.0));
384        m.insert("maxFrameSize".into(), Value::Float(MAX_FRAME_SIZE as f64));
385        m.insert("maxConcurrentStreams".into(), Value::Float(100.0));
386        h.new_object(m)
387    })
388}
389
390// ── getPackedSettings / getUnpackedSettings (RFC 7540 §6.5.1 wire form) ───────
391
392/// Append one SETTINGS entry (2-byte identifier + 4-byte value, big-endian).
393fn push_setting(out: &mut Vec<u8>, id: u16, val: u32) {
394    out.extend_from_slice(&id.to_be_bytes());
395    out.extend_from_slice(&val.to_be_bytes());
396}
397
398/// `http2.getPackedSettings(settings)` — serialize the SETTINGS values present on
399/// `settings` into the RFC 7540 §6.5.1 wire form (6 octets per entry: a 2-byte
400/// identifier followed by a 4-byte value, big-endian). Only keys actually present
401/// on the object are emitted, in the canonical identifier order (1..6) Node uses;
402/// this is the exact inverse of `getUnpackedSettings`.
403fn pack_settings(args: &[Value]) -> Value {
404    let settings = args.first().cloned().unwrap_or(Value::Undef);
405    let num = |key: &str| -> Option<u32> {
406        get_prop(&settings, key)
407            .filter(|v| !matches!(v, Value::Undef))
408            .map(|v| with_host(|h| h.to_number(&v)) as u32)
409    };
410    let mut out: Vec<u8> = Vec::new();
411    if let Some(v) = num("headerTableSize") {
412        push_setting(&mut out, 0x1, v);
413    }
414    if let Some(p) = get_prop(&settings, "enablePush").filter(|v| !matches!(v, Value::Undef)) {
415        let on = with_host(|h| h.truthy(&p));
416        push_setting(&mut out, 0x2, u32::from(on));
417    }
418    if let Some(v) = num("maxConcurrentStreams") {
419        push_setting(&mut out, 0x3, v);
420    }
421    if let Some(v) = num("initialWindowSize") {
422        push_setting(&mut out, 0x4, v);
423    }
424    if let Some(v) = num("maxFrameSize") {
425        push_setting(&mut out, 0x5, v);
426    }
427    if let Some(v) = num("maxHeaderListSize").or_else(|| num("maxHeaderSize")) {
428        push_setting(&mut out, 0x6, v);
429    }
430    super::buffer::from_bytes(&out)
431}
432
433/// `http2.getUnpackedSettings(buf)` — parse a packed SETTINGS payload (6 octets per
434/// entry: 2-byte identifier + 4-byte value, big-endian) back into a settings object
435/// (`{ headerTableSize, enablePush, maxConcurrentStreams, initialWindowSize,
436/// maxFrameSize, maxHeaderSize, maxHeaderListSize }`, only the keys present in the
437/// buffer). The inverse of `getPackedSettings`. Throws `ERR_HTTP2_INVALID_PACKED_
438/// SETTINGS_LENGTH` when the length is not a multiple of six.
439fn unpack_settings(args: &[Value]) -> Result<Value, String> {
440    let bytes = value_bytes(args.first());
441    if bytes.len() % 6 != 0 {
442        return Err("RangeError [ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH]: \
443                    Packed settings length must be a multiple of six"
444            .to_string());
445    }
446    let mut m = IndexMap::new();
447    for chunk in bytes.chunks_exact(6) {
448        let id = u16::from_be_bytes([chunk[0], chunk[1]]);
449        let val = u32::from_be_bytes([chunk[2], chunk[3], chunk[4], chunk[5]]);
450        match id {
451            0x1 => {
452                m.insert("headerTableSize".to_string(), Value::Float(val as f64));
453            }
454            0x2 => {
455                m.insert("enablePush".to_string(), Value::Bool(val != 0));
456            }
457            0x3 => {
458                m.insert("maxConcurrentStreams".to_string(), Value::Float(val as f64));
459            }
460            0x4 => {
461                m.insert("initialWindowSize".to_string(), Value::Float(val as f64));
462            }
463            0x5 => {
464                m.insert("maxFrameSize".to_string(), Value::Float(val as f64));
465            }
466            // Identifier 6 maps to BOTH `maxHeaderSize` and its `maxHeaderListSize`
467            // alias (Node emits both, in that order).
468            0x6 => {
469                m.insert("maxHeaderSize".to_string(), Value::Float(val as f64));
470                m.insert("maxHeaderListSize".to_string(), Value::Float(val as f64));
471            }
472            // Unknown identifiers are ignored per RFC 7540 §6.5.
473            _ => {}
474        }
475    }
476    Ok(with_host(|h| h.new_object(m)))
477}
478
479// ── http2.createSecureServer ─────────────────────────────────────────────────
480
481/// `http2.createSecureServer(options[, onRequestHandler])`. Parses `key`+`cert`
482/// into a `ServerConfig` with ALPN `h2` (a bad cert throws synchronously) and
483/// returns an `Http2Server` emitter. A supplied handler is registered as a compat
484/// `request` listener (Node semantics).
485fn create_secure_server(args: &[Value]) -> Result<Value, String> {
486    let mut options: Option<Value> = None;
487    let mut handler: Option<Value> = None;
488    for a in args {
489        if with_host(|h| crate::host::is_callable(h, a)) {
490            handler = Some(a.clone());
491        } else if matches!(a, Value::Obj(_)) {
492            options = Some(a.clone());
493        }
494    }
495    let opts = options.ok_or_else(|| {
496        crate::host::type_error("http2.createSecureServer requires options with `key` and `cert`")
497    })?;
498    let cert = value_bytes(get_prop(&opts, "cert").as_ref());
499    let key = value_bytes(get_prop(&opts, "key").as_ref());
500    if cert.is_empty() || key.is_empty() {
501        return Err(crate::host::type_error(
502            "http2.createSecureServer requires `key` and `cert`",
503        ));
504    }
505    let config = build_h2_server_config(&cert, &key)?;
506
507    let server = new_emitter_object("Http2Server", IndexMap::new());
508    if let Some(cb) = handler {
509        // Node registers the createSecureServer handler as a `request` listener.
510        super::events::instance_call(&server, "on", vec![with_host(|h| h.new_str("request")), cb])?;
511    }
512    PENDING_CONFIGS.with(|p| p.borrow_mut().push((server.clone(), config)));
513    Ok(server)
514}
515
516/// Build a `ServerConfig` from PEM `key`+`cert`, offering ALPN `h2` only.
517fn build_h2_server_config(cert_pem: &[u8], key_pem: &[u8]) -> Result<Arc<ServerConfig>, String> {
518    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut &cert_pem[..])
519        .collect::<Result<_, _>>()
520        .map_err(|e| format!("Error: http2: bad certificate PEM: {e}"))?;
521    if certs.is_empty() {
522        return Err("Error: http2: no certificates found in `cert`".to_string());
523    }
524    let key: PrivateKeyDer<'static> = rustls_pemfile::private_key(&mut &key_pem[..])
525        .map_err(|e| format!("Error: http2: bad private key PEM: {e}"))?
526        .ok_or_else(|| "Error: http2: no private key found in `key`".to_string())?;
527    let mut cfg = ServerConfig::builder()
528        .with_no_client_auth()
529        .with_single_cert(certs, key)
530        .map_err(|e| format!("Error: http2: invalid key/cert: {e}"))?;
531    // ALPN: offer only "h2" so the handshake negotiates HTTP/2.
532    cfg.alpn_protocols = vec![b"h2".to_vec()];
533    Ok(Arc::new(cfg))
534}
535
536fn take_pending_config(server: &Value) -> Option<Arc<ServerConfig>> {
537    PENDING_CONFIGS.with(|p| {
538        let mut p = p.borrow_mut();
539        p.iter()
540            .position(|(s, _)| s == server)
541            .map(|pos| p.remove(pos).1)
542    })
543}
544
545// ── instance dispatch (Http2Server / Http2Stream / Http2Session) ─────────────
546
547pub fn instance_call(
548    tag: &str,
549    recv: &Value,
550    method: &str,
551    args: Vec<Value>,
552) -> Result<Value, String> {
553    match tag {
554        "Http2Server" => server_call(recv, method, args),
555        "Http2Stream" => stream_call(recv, method, args),
556        "Http2Session" => session_call(recv, method, args),
557        _ => Err(crate::host::type_error(&format!(
558            "{method} is not a function"
559        ))),
560    }
561}
562
563fn server_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
564    if let Some(r) = emitter_dispatch(recv, method, &args) {
565        return r;
566    }
567    match method {
568        "listen" => server_listen(recv, &args),
569        "close" => server_close(recv, &args),
570        "address" => Ok(get_prop(recv, "@@address").unwrap_or(Value::Undef)),
571        "setTimeout" => Ok(recv.clone()),
572        _ => Err(crate::host::type_error(&format!(
573            "server.{method} is not a function"
574        ))),
575    }
576}
577
578/// `server.listen(port[, host][, callback])`. Binds on the main thread, spawns the
579/// accept loop, and fires `listening` + callback asynchronously.
580fn server_listen(recv: &Value, args: &[Value]) -> Result<Value, String> {
581    let port = with_host(|h| args.first().map(|v| h.to_number(v)).unwrap_or(0.0)) as u16;
582    let mut host = "0.0.0.0".to_string();
583    let mut cb: Option<Value> = None;
584    for a in &args[1.min(args.len())..] {
585        if with_host(|h| h.as_str(a)).is_some() {
586            host = with_host(|h| h.str_of(a));
587        } else if with_host(|h| crate::host::is_callable(h, a)) {
588            cb = Some(a.clone());
589        }
590    }
591
592    let config = take_pending_config(recv)
593        .ok_or_else(|| crate::host::type_error("http2 server has no secure context"))?;
594    let listener = TcpListener::bind((host.as_str(), port))
595        .map_err(|e| format!("Error: listen EADDRINUSE: {e}"))?;
596    let local = listener.local_addr().ok();
597
598    let id = next_server_id();
599    set_prop(recv, "@@serverid", Value::Float(id as f64));
600    if let Some(addr) = local {
601        let mut a = IndexMap::new();
602        a.insert("port".into(), Value::Float(addr.port() as f64));
603        a.insert(
604            "address".into(),
605            with_host(|h| h.new_str(addr.ip().to_string())),
606        );
607        a.insert(
608            "family".into(),
609            with_host(|h| h.new_str(if addr.is_ipv6() { "IPv6" } else { "IPv4" })),
610        );
611        let addr_obj = with_host(|h| h.new_object(a));
612        set_prop(recv, "@@address", addr_obj);
613    }
614    let stop = Arc::new(AtomicBool::new(false));
615    H2.with(|s| {
616        s.borrow_mut().servers.insert(
617            id,
618            H2ServerRec {
619                emitter: recv.clone(),
620                stop: stop.clone(),
621            },
622        );
623    });
624    with_host(|h| h.incr_handle());
625
626    let io_tx = with_host(|h| h.io_sender());
627    listener.set_nonblocking(true).ok();
628    std::thread::spawn(move || loop {
629        if stop.load(Ordering::Acquire) {
630            break;
631        }
632        match listener.accept() {
633            Ok((stream, _addr)) => {
634                let cfg = config.clone();
635                let tx = io_tx.clone();
636                std::thread::spawn(move || serve_connection(id, stream, cfg, tx));
637            }
638            Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
639                std::thread::sleep(std::time::Duration::from_millis(5));
640            }
641            Err(_) => break,
642        }
643    });
644
645    let server = recv.clone();
646    let _ = with_host(|h| h.io_sender()).send(Box::new(move || {
647        super::events::instance_call(&server, "emit", vec![with_host(|h| h.new_str("listening"))])?;
648        if let Some(cb) = cb {
649            invoke(&cb, Vec::new(), None)?;
650        }
651        Ok(())
652    }));
653    Ok(recv.clone())
654}
655
656fn server_close(recv: &Value, args: &[Value]) -> Result<Value, String> {
657    if let Some(id) = u64_prop(recv, "@@serverid") {
658        let rec = H2.with(|s| s.borrow_mut().servers.remove(&id));
659        if let Some(rec) = rec {
660            rec.stop.store(true, Ordering::Release);
661            with_host(|h| h.decr_handle());
662            let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
663        }
664    }
665    if let Some(cb) = args
666        .first()
667        .filter(|v| with_host(|h| crate::host::is_callable(h, v)))
668    {
669        invoke(cb, Vec::new(), None)?;
670    }
671    super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))])?;
672    Ok(recv.clone())
673}
674
675// ── the per-connection owner thread: TLS + HTTP/2 framing ────────────────────
676
677/// One background thread per accepted TCP connection: complete the TLS handshake
678/// (negotiating ALPN `h2`), then run the HTTP/2 framing loop. Owns the
679/// `StreamOwned` and the HPACK `Encoder`/`Decoder` for the whole connection.
680fn serve_connection(
681    server_id: u64,
682    mut sock: TcpStream,
683    config: Arc<ServerConfig>,
684    io_tx: Sender<IoTask>,
685) {
686    // The socket is inherited non-blocking from the accept poll loop; put it in
687    // blocking mode so the TLS handshake and the initial SETTINGS write can't
688    // fail with WouldBlock. A per-read timeout (set later) gives the framing loop
689    // its read/write interleave without making writes non-blocking.
690    sock.set_nonblocking(false).ok();
691    let mut conn = match ServerConnection::new(config) {
692        Ok(c) => c,
693        Err(_) => return,
694    };
695    if conn.complete_io(&mut sock).is_err() {
696        return;
697    }
698    // ALPN must have negotiated "h2"; otherwise this is not an HTTP/2 connection.
699    let is_h2 = conn.alpn_protocol().map(|p| p == b"h2").unwrap_or(false);
700    let mut stream = StreamOwned::new(conn, sock);
701    if !is_h2 {
702        // Honest fallback: we only speak h2. Close the connection.
703        stream.conn.send_close_notify();
704        let _ = stream.flush();
705        let _ = stream.sock.shutdown(std::net::Shutdown::Both);
706        return;
707    }
708    // Command channel: main-thread stream/session methods post frames to write.
709    let (tx, rx) = std::sync::mpsc::channel::<H2Cmd>();
710
711    // Announce the session on the main thread.
712    let session_key = next_session_key();
713    {
714        let tx_sess = tx.clone();
715        let _ = io_tx.send(Box::new(move || {
716            on_session(server_id, session_key, tx_sess)
717        }));
718    }
719
720    if h2_debug() {
721        eprintln!("[http2] connection {session_key}: ALPN h2 negotiated, starting framing loop");
722    }
723
724    // Send our SETTINGS immediately (empty payload is valid). This runs in
725    // BLOCKING mode — the read timeout is set AFTERWARDS, because rustls's write
726    // internally completes pending handshake I/O (a read), and a read-timeout set
727    // beforehand makes that read WouldBlock → the write fails → the loop never
728    // starts (the connection-startup race).
729    let mut ok = true;
730    ok &= write_frame(&mut stream, FT_SETTINGS, 0, 0, &[]).is_ok();
731    ok &= stream.flush().is_ok();
732    // Now switch to a short read timeout so the loop interleaves reads with the
733    // outbound-command drain.
734    stream
735        .sock
736        .set_read_timeout(Some(std::time::Duration::from_millis(20)))
737        .ok();
738
739    let mut decoder = Decoder::new();
740    let mut encoder = Encoder::new();
741    let mut inbuf: Vec<u8> = Vec::new();
742    let mut got_preface = false;
743    let mut max_stream_id: u32 = 0;
744    // Map stream-id → main-thread stream key (for routing inbound DATA).
745    let mut id_to_key: HashMap<u32, u64> = HashMap::new();
746    let mut buf = [0u8; MAX_FRAME_SIZE];
747
748    'conn: loop {
749        // If the initial SETTINGS write failed the connection is already dead;
750        // fall through to the GOAWAY/close cleanup below. (`ok` is only ever set
751        // before the loop, so this is the entry gate, not a per-iteration test.)
752        if !ok {
753            break;
754        }
755        // 1) Drain queued outbound commands (respond/write/end frames enqueued by
756        //    the main thread). This runs on EVERY loop iteration — including after
757        //    a WouldBlock read — so async responses are written promptly.
758        loop {
759            match rx.try_recv() {
760                Ok(cmd) => {
761                    if h2_debug() {
762                        eprintln!(
763                            "[http2] connection {session_key}: draining {}",
764                            cmd_name(&cmd)
765                        );
766                    }
767                    if !apply_cmd(&mut stream, &mut encoder, max_stream_id, cmd) {
768                        if h2_debug() {
769                            eprintln!("[http2] connection {session_key}: write failed, closing");
770                        }
771                        break 'conn;
772                    }
773                }
774                Err(std::sync::mpsc::TryRecvError::Empty) => break,
775                Err(std::sync::mpsc::TryRecvError::Disconnected) => break,
776            }
777        }
778
779        // 2) Read whatever plaintext (HTTP/2 frames) is available.
780        match stream.read(&mut buf) {
781            Ok(0) => {
782                if h2_debug() {
783                    eprintln!("[http2] connection {session_key}: read EOF (Ok 0)");
784                }
785                break;
786            }
787            Ok(n) => inbuf.extend_from_slice(&buf[..n]),
788            Err(ref e)
789                if matches!(
790                    e.kind(),
791                    std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
792                ) =>
793            {
794                continue;
795            }
796            Err(e) => {
797                if h2_debug() {
798                    eprintln!(
799                        "[http2] connection {session_key}: read error {:?} ({e})",
800                        e.kind()
801                    );
802                }
803                break;
804            }
805        }
806
807        // 3) Consume the client connection preface (first 24 octets).
808        if !got_preface {
809            if inbuf.len() < PREFACE.len() {
810                continue;
811            }
812            if &inbuf[..PREFACE.len()] != PREFACE {
813                break; // not an HTTP/2 connection preface — bail.
814            }
815            inbuf.drain(..PREFACE.len());
816            got_preface = true;
817        }
818
819        // 4) Parse and dispatch every complete frame currently buffered.
820        loop {
821            if inbuf.len() < 9 {
822                break;
823            }
824            let len =
825                ((inbuf[0] as usize) << 16) | ((inbuf[1] as usize) << 8) | (inbuf[2] as usize);
826            if inbuf.len() < 9 + len {
827                break; // await the rest of the frame body.
828            }
829            let ftype = inbuf[3];
830            let flags = inbuf[4];
831            let stream_id =
832                u32::from_be_bytes([inbuf[5], inbuf[6], inbuf[7], inbuf[8]]) & 0x7fff_ffff;
833            let payload: Vec<u8> = inbuf[9..9 + len].to_vec();
834            inbuf.drain(..9 + len);
835            if h2_debug() {
836                eprintln!(
837                    "[http2] connection {session_key}: recv frame type={ftype} flags={flags:#04x} \
838                     stream={stream_id} len={len}"
839                );
840            }
841
842            match ftype {
843                FT_SETTINGS => {
844                    if flags & FL_ACK == 0 {
845                        // ACK the client's SETTINGS (empty payload, ACK flag).
846                        if write_frame(&mut stream, FT_SETTINGS, FL_ACK, 0, &[])
847                            .and_then(|_| stream.flush())
848                            .is_err()
849                        {
850                            break 'conn;
851                        }
852                    }
853                }
854                FT_PING => {
855                    if flags & FL_ACK == 0 {
856                        // Echo the 8-byte opaque data with the ACK flag set.
857                        if write_frame(&mut stream, FT_PING, FL_ACK, 0, &payload)
858                            .and_then(|_| stream.flush())
859                            .is_err()
860                        {
861                            break 'conn;
862                        }
863                    }
864                }
865                FT_HEADERS => {
866                    if stream_id > max_stream_id {
867                        max_stream_id = stream_id;
868                    }
869                    if flags & FL_END_HEADERS == 0 {
870                        // CONTINUATION reassembly is not implemented; skip this stream.
871                        continue;
872                    }
873                    let block = strip_headers_padding_priority(&payload, flags);
874                    let decoded = match decoder.decode(&block) {
875                        Ok(d) => d,
876                        Err(_) => continue,
877                    };
878                    let headers: Vec<(String, String)> = decoded
879                        .into_iter()
880                        .map(|(k, v)| {
881                            (
882                                String::from_utf8_lossy(&k).into_owned(),
883                                String::from_utf8_lossy(&v).into_owned(),
884                            )
885                        })
886                        .collect();
887                    let end_stream = flags & FL_END_STREAM != 0;
888                    let key = next_stream_key();
889                    id_to_key.insert(stream_id, key);
890                    let tx_stream = tx.clone();
891                    let _ = io_tx.send(Box::new(move || {
892                        on_headers(server_id, key, stream_id, headers, end_stream, tx_stream)
893                    }));
894                }
895                FT_DATA => {
896                    if let Some(&key) = id_to_key.get(&stream_id) {
897                        let data = strip_data_padding(&payload, flags);
898                        let end_stream = flags & FL_END_STREAM != 0;
899                        let _ = io_tx.send(Box::new(move || on_data(key, data, end_stream)));
900                    }
901                }
902                FT_GOAWAY => break 'conn,
903                // WINDOW_UPDATE / PRIORITY / RST_STREAM / CONTINUATION: accepted and
904                // ignored (large-enough default windows; see module limitations).
905                FT_WINDOW_UPDATE | FT_PRIORITY | FT_RST_STREAM | FT_CONTINUATION => {}
906                // Unknown/extension frame types: ignored per RFC 7540 §4.1.
907                _ => {}
908            }
909        }
910    }
911
912    // Best-effort GOAWAY then close.
913    if h2_debug() {
914        eprintln!(
915            "[http2] connection {session_key}: framing loop exited, sending GOAWAY + closing"
916        );
917    }
918    let mut goaway = Vec::with_capacity(8);
919    goaway.extend_from_slice(&(max_stream_id & 0x7fff_ffff).to_be_bytes());
920    goaway.extend_from_slice(&0u32.to_be_bytes()); // NO_ERROR
921    let _ = write_frame(&mut stream, FT_GOAWAY, 0, 0, &goaway);
922    let _ = stream.flush();
923    stream.conn.send_close_notify();
924    let _ = stream.flush();
925    let _ = stream.sock.shutdown(std::net::Shutdown::Both);
926
927    // Release the per-connection handle and drop this connection's records on the
928    // main thread (balances the `incr_handle` in `on_session`).
929    let stream_keys: Vec<u64> = id_to_key.values().copied().collect();
930    let _ = io_tx.send(Box::new(move || on_session_close(session_key, stream_keys)));
931}
932
933/// A short label for an `H2Cmd` (diagnostic tracing only).
934fn cmd_name(cmd: &H2Cmd) -> &'static str {
935    match cmd {
936        H2Cmd::Respond { .. } => "respond(HEADERS)",
937        H2Cmd::Data { .. } => "data(DATA)",
938        H2Cmd::Close { .. } => "close(RST_STREAM)",
939        H2Cmd::Goaway => "goaway(GOAWAY)",
940    }
941}
942
943/// Apply one outbound command by encoding + writing its frame(s). Returns false on
944/// a write error or an explicit GOAWAY (terminating the owner loop).
945fn apply_cmd(
946    stream: &mut StreamOwned<ServerConnection, TcpStream>,
947    encoder: &mut Encoder<'_>,
948    max_stream_id: u32,
949    cmd: H2Cmd,
950) -> bool {
951    match cmd {
952        H2Cmd::Respond {
953            stream_id,
954            headers,
955            end,
956        } => {
957            let block = encode_header_block(encoder, &headers);
958            if h2_debug() {
959                eprintln!(
960                    "[http2] write HEADERS stream={stream_id} end_stream={end} \
961                     hpack_len={} headers={headers:?}",
962                    block.len()
963                );
964            }
965            let flags = FL_END_HEADERS | if end { FL_END_STREAM } else { 0 };
966            write_frame(stream, FT_HEADERS, flags, stream_id, &block)
967                .and_then(|_| stream.flush())
968                .is_ok()
969        }
970        H2Cmd::Data {
971            stream_id,
972            data,
973            end,
974        } => {
975            if h2_debug() {
976                eprintln!(
977                    "[http2] write DATA stream={stream_id} len={} end_stream={end}",
978                    data.len()
979                );
980            }
981            send_data(stream, stream_id, &data, end)
982        }
983        H2Cmd::Close { stream_id } => {
984            // RST_STREAM(NO_ERROR).
985            write_frame(stream, FT_RST_STREAM, 0, stream_id, &0u32.to_be_bytes())
986                .and_then(|_| stream.flush())
987                .is_ok()
988        }
989        H2Cmd::Goaway => {
990            let mut g = Vec::with_capacity(8);
991            g.extend_from_slice(&(max_stream_id & 0x7fff_ffff).to_be_bytes());
992            g.extend_from_slice(&0u32.to_be_bytes());
993            let _ = write_frame(stream, FT_GOAWAY, 0, 0, &g);
994            let _ = stream.flush();
995            false
996        }
997    }
998}
999
1000/// Send a body as DATA frames, chunked to MAX_FRAME_SIZE. END_STREAM is set on the
1001/// final frame when `end` is true (an empty body still emits one END_STREAM DATA).
1002fn send_data(
1003    stream: &mut StreamOwned<ServerConnection, TcpStream>,
1004    stream_id: u32,
1005    data: &[u8],
1006    end: bool,
1007) -> bool {
1008    if data.is_empty() {
1009        let flags = if end { FL_END_STREAM } else { 0 };
1010        return write_frame(stream, FT_DATA, flags, stream_id, &[])
1011            .and_then(|_| stream.flush())
1012            .is_ok();
1013    }
1014    let chunks: Vec<&[u8]> = data.chunks(MAX_FRAME_SIZE).collect();
1015    let last = chunks.len() - 1;
1016    for (i, chunk) in chunks.iter().enumerate() {
1017        let flags = if end && i == last { FL_END_STREAM } else { 0 };
1018        if write_frame(stream, FT_DATA, flags, stream_id, chunk).is_err() {
1019            return false;
1020        }
1021    }
1022    stream.flush().is_ok()
1023}
1024
1025/// Write one HTTP/2 frame: 9-octet header (24-bit length, 8-bit type, 8-bit flags,
1026/// 31-bit stream id) followed by the payload (RFC 7540 §4.1).
1027fn write_frame<W: Write>(
1028    w: &mut W,
1029    ftype: u8,
1030    flags: u8,
1031    stream_id: u32,
1032    payload: &[u8],
1033) -> std::io::Result<()> {
1034    let len = payload.len();
1035    let mut hdr = [0u8; 9];
1036    hdr[0] = (len >> 16) as u8;
1037    hdr[1] = (len >> 8) as u8;
1038    hdr[2] = len as u8;
1039    hdr[3] = ftype;
1040    hdr[4] = flags;
1041    hdr[5..9].copy_from_slice(&(stream_id & 0x7fff_ffff).to_be_bytes());
1042    w.write_all(&hdr)?;
1043    w.write_all(payload)?;
1044    Ok(())
1045}
1046
1047/// HPACK-encode a header list into a header block fragment.
1048fn encode_header_block(encoder: &mut Encoder<'_>, headers: &[(String, String)]) -> Vec<u8> {
1049    let owned: Vec<(Vec<u8>, Vec<u8>)> = headers
1050        .iter()
1051        .map(|(k, v)| (k.as_bytes().to_vec(), v.as_bytes().to_vec()))
1052        .collect();
1053    encoder.encode(owned.iter().map(|(k, v)| (k.as_slice(), v.as_slice())))
1054}
1055
1056/// Strip PADDED/PRIORITY prefixes/suffixes from a HEADERS payload, yielding the raw
1057/// header block fragment (RFC 7540 §6.2).
1058fn strip_headers_padding_priority(payload: &[u8], flags: u8) -> Vec<u8> {
1059    let mut start = 0usize;
1060    let mut pad_len = 0usize;
1061    if flags & FL_PADDED != 0 && !payload.is_empty() {
1062        pad_len = payload[0] as usize;
1063        start = 1;
1064    }
1065    if flags & FL_PRIORITY != 0 {
1066        start += 5; // 4-byte stream dependency + 1-byte weight
1067    }
1068    let end = payload.len().saturating_sub(pad_len);
1069    if start > end {
1070        return Vec::new();
1071    }
1072    payload[start..end].to_vec()
1073}
1074
1075/// Strip a PADDED prefix/suffix from a DATA payload (RFC 7540 §6.1).
1076fn strip_data_padding(payload: &[u8], flags: u8) -> Vec<u8> {
1077    if flags & FL_PADDED != 0 && !payload.is_empty() {
1078        let pad_len = payload[0] as usize;
1079        let end = payload.len().saturating_sub(pad_len);
1080        if 1 <= end {
1081            return payload[1..end].to_vec();
1082        }
1083        return Vec::new();
1084    }
1085    payload.to_vec()
1086}
1087
1088// ── main-thread event handlers (run from posted IoTasks) ─────────────────────
1089
1090/// Build the `Http2Session` object and emit `session` on the server. Also takes a
1091/// per-connection event-loop handle (released by `on_session_close`) so the loop
1092/// stays alive while this connection is served — mirroring `tls`'s per-socket
1093/// `incr_handle`.
1094fn on_session(server_id: u64, session_key: u64, tx: Sender<H2Cmd>) -> Result<(), String> {
1095    with_host(|h| h.incr_handle());
1096    let server = H2.with(|s| {
1097        s.borrow()
1098            .servers
1099            .get(&server_id)
1100            .map(|r| r.emitter.clone())
1101    });
1102    let Some(server) = server else { return Ok(()) };
1103    let mut extra = IndexMap::new();
1104    extra.insert("@@h2session".into(), Value::Float(session_key as f64));
1105    let session = new_emitter_object("Http2Session", extra);
1106    H2.with(|s| {
1107        s.borrow_mut().sessions.insert(
1108            session_key,
1109            H2SessionRec {
1110                emitter: session.clone(),
1111                tx,
1112            },
1113        );
1114    });
1115    if let Err(e) = super::events::instance_call(
1116        &server,
1117        "emit",
1118        vec![with_host(|h| h.new_str("session")), session],
1119    ) {
1120        report_handler_error("session", &e);
1121    }
1122    Ok(())
1123}
1124
1125/// Release the per-connection handle and drop the session + its stream records
1126/// (posted by the owner thread when its framing loop exits).
1127fn on_session_close(session_key: u64, stream_keys: Vec<u64>) -> Result<(), String> {
1128    H2.with(|s| {
1129        let mut st = s.borrow_mut();
1130        st.sessions.remove(&session_key);
1131        for k in &stream_keys {
1132            st.streams.remove(k);
1133        }
1134    });
1135    with_host(|h| h.decr_handle());
1136    // Wake the loop so a closed last handle lets it exit.
1137    let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1138    Ok(())
1139}
1140
1141/// Handle a decoded HEADERS frame: build the `Http2Stream`, emit `stream`
1142/// (and compat `request`).
1143fn on_headers(
1144    server_id: u64,
1145    stream_key: u64,
1146    stream_id: u32,
1147    headers: Vec<(String, String)>,
1148    end_stream: bool,
1149    tx: Sender<H2Cmd>,
1150) -> Result<(), String> {
1151    let server = H2.with(|s| {
1152        s.borrow()
1153            .servers
1154            .get(&server_id)
1155            .map(|r| r.emitter.clone())
1156    });
1157    let Some(server) = server else { return Ok(()) };
1158
1159    // Build the header object exposed to JS (pseudo-headers kept as `:`-prefixed).
1160    let headers_obj = with_host(|h| {
1161        let mut m = IndexMap::new();
1162        for (k, v) in &headers {
1163            m.insert(k.clone(), h.new_str(v.clone()));
1164        }
1165        h.new_object(m)
1166    });
1167
1168    // The core Http2Stream object.
1169    let mut extra = IndexMap::new();
1170    extra.insert("@@h2key".into(), Value::Float(stream_key as f64));
1171    extra.insert("id".into(), Value::Float(stream_id as f64));
1172    let stream_obj = new_emitter_object("Http2Stream", extra);
1173    H2.with(|s| {
1174        s.borrow_mut().streams.insert(
1175            stream_key,
1176            H2StreamRec {
1177                emitter: stream_obj.clone(),
1178                tx,
1179                stream_id,
1180                responded: false,
1181            },
1182        );
1183    });
1184
1185    let method = header_value(&headers, ":method").unwrap_or_else(|| "GET".to_string());
1186    let path = header_value(&headers, ":path").unwrap_or_else(|| "/".to_string());
1187    if h2_debug() {
1188        eprintln!("[http2] dispatch stream={stream_id} {method} {path} (end_stream={end_stream})");
1189    }
1190
1191    // Emit the core `stream` event: (stream, headers). CRITICAL: a throwing user
1192    // handler must NOT propagate out of this IoTask — the event loop treats an
1193    // `Err` from a posted task as fatal (`drive_event_loop`: `task()?`) and would
1194    // tear the whole process down, closing every live connection (the classic
1195    // "server closed right after HEADERS → curl broken pipe"). So we catch the
1196    // handler error, surface it on stderr, and keep the loop (and other
1197    // connections) alive — mirroring how a server should isolate request faults.
1198    if let Err(e) = super::events::instance_call(
1199        &server,
1200        "emit",
1201        vec![
1202            with_host(|h| h.new_str("stream")),
1203            stream_obj.clone(),
1204            headers_obj.clone(),
1205        ],
1206    ) {
1207        report_handler_error("stream", &e);
1208        return Ok(());
1209    }
1210
1211    // Compat `request` event: (req, res). `req` is a lightweight emitter carrying
1212    // method/url/headers; `res` is the same Http2Stream (writeHead/end mapped).
1213    let req = super::events::new_emitter();
1214    set_prop(&req, "method", with_host(|h| h.new_str(method)));
1215    set_prop(&req, "url", with_host(|h| h.new_str(path)));
1216    set_prop(&req, "headers", headers_obj);
1217    if let Err(e) = super::events::instance_call(
1218        &server,
1219        "emit",
1220        vec![with_host(|h| h.new_str("request")), req, stream_obj.clone()],
1221    ) {
1222        report_handler_error("request", &e);
1223        return Ok(());
1224    }
1225
1226    // A GET (END_STREAM on HEADERS) has no body: signal `end` to the stream.
1227    if end_stream {
1228        if let Err(e) =
1229            super::events::instance_call(&stream_obj, "emit", vec![with_host(|h| h.new_str("end"))])
1230        {
1231            report_handler_error("stream.end", &e);
1232        }
1233    }
1234    Ok(())
1235}
1236
1237/// Report an uncaught error raised by a user request/stream handler. Printed to
1238/// stderr (a genuine program error, like Node's uncaught-exception output) so the
1239/// cause is visible instead of the process silently dying; never propagated, so
1240/// one faulty handler cannot kill the event loop / other in-flight connections.
1241fn report_handler_error(event: &str, err: &str) {
1242    eprintln!("http2: uncaught error in '{event}' handler: {err}");
1243}
1244
1245/// True when `HTTP2_DEBUG` is set in the environment — enables per-frame stderr
1246/// tracing for diagnosing the h2 framing path end-to-end.
1247fn h2_debug() -> bool {
1248    std::env::var_os("HTTP2_DEBUG").is_some()
1249}
1250
1251/// Emit an inbound request-body DATA chunk (and `end` on END_STREAM) on the stream.
1252fn on_data(stream_key: u64, data: Vec<u8>, end_stream: bool) -> Result<(), String> {
1253    let stream = H2.with(|s| {
1254        s.borrow()
1255            .streams
1256            .get(&stream_key)
1257            .map(|r| r.emitter.clone())
1258    });
1259    let Some(stream) = stream else { return Ok(()) };
1260    if !data.is_empty() {
1261        let chunk = super::buffer::from_bytes(&data);
1262        if let Err(e) = super::events::instance_call(
1263            &stream,
1264            "emit",
1265            vec![with_host(|h| h.new_str("data")), chunk],
1266        ) {
1267            report_handler_error("data", &e);
1268            return Ok(());
1269        }
1270    }
1271    if end_stream {
1272        if let Err(e) =
1273            super::events::instance_call(&stream, "emit", vec![with_host(|h| h.new_str("end"))])
1274        {
1275            report_handler_error("end", &e);
1276        }
1277    }
1278    Ok(())
1279}
1280
1281fn header_value(headers: &[(String, String)], name: &str) -> Option<String> {
1282    headers
1283        .iter()
1284        .find(|(k, _)| k == name)
1285        .map(|(_, v)| v.clone())
1286}
1287
1288// ── Http2Stream instance methods ─────────────────────────────────────────────
1289
1290fn stream_key_of(recv: &Value) -> Option<u64> {
1291    u64_prop(recv, "@@h2key")
1292}
1293
1294fn stream_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
1295    if let Some(r) = emitter_dispatch(recv, method, &args) {
1296        return r;
1297    }
1298    match method {
1299        "respond" => {
1300            let hdrs = args.first().map(object_pairs).unwrap_or_default();
1301            // `options.endStream` (arg 1) → header-only response.
1302            let end = args
1303                .get(1)
1304                .and_then(|o| get_prop(o, "endStream"))
1305                .map(|v| with_host(|h| h.truthy(&v)))
1306                .unwrap_or(false);
1307            do_respond(recv, hdrs, end)?;
1308            Ok(recv.clone())
1309        }
1310        // HTTP/1-compat: writeHead(status[, headersObj]) → respond.
1311        "writeHead" => {
1312            let status =
1313                with_host(|h| args.first().map(|v| h.to_number(v)).unwrap_or(200.0)) as u32;
1314            let mut hdrs: Vec<(String, String)> = Vec::new();
1315            for a in args.iter().skip(1) {
1316                if matches!(a, Value::Obj(_)) {
1317                    hdrs = object_pairs(a);
1318                    break;
1319                }
1320            }
1321            // Inject the `:status` pseudo-header (writeHead's implicit status).
1322            hdrs.insert(0, (":status".to_string(), status.to_string()));
1323            do_respond(recv, hdrs, false)?;
1324            Ok(recv.clone())
1325        }
1326        "setHeader" => {
1327            // Stash pending compat headers until the response HEADERS are sent.
1328            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
1329            let v = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
1330            let bag = pending_headers_obj(recv);
1331            set_prop(&bag, &k, with_host(|h| h.new_str(v)));
1332            Ok(Value::Undef)
1333        }
1334        "getHeader" => {
1335            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
1336            Ok(get_prop(recv, "@@pendingHeaders")
1337                .and_then(|bag| get_prop(&bag, &k))
1338                .unwrap_or(Value::Undef))
1339        }
1340        "removeHeader" => {
1341            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
1342            if let Some(bag) = get_prop(recv, "@@pendingHeaders") {
1343                with_host(|h| {
1344                    if let Some(JsObj::Object(p)) = h.get_mut(&bag) {
1345                        p.shift_remove(&k);
1346                    }
1347                });
1348            }
1349            Ok(Value::Undef)
1350        }
1351        "write" => {
1352            ensure_responded(recv)?;
1353            let bytes = value_bytes(args.first());
1354            send_stream_data(recv, bytes, false);
1355            Ok(Value::Bool(true))
1356        }
1357        "end" => {
1358            ensure_responded(recv)?;
1359            let bytes = args
1360                .first()
1361                .filter(|v| !matches!(v, Value::Undef))
1362                .map(|v| value_bytes(Some(v)))
1363                .unwrap_or_default();
1364            send_stream_data(recv, bytes, true);
1365            super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("finish"))])?;
1366            Ok(recv.clone())
1367        }
1368        "close" => {
1369            if let Some(key) = stream_key_of(recv) {
1370                let sent = H2.with(|s| {
1371                    s.borrow().streams.get(&key).map(|r| {
1372                        let _ = r.tx.send(H2Cmd::Close {
1373                            stream_id: r.stream_id,
1374                        });
1375                    })
1376                });
1377                let _ = sent;
1378            }
1379            Ok(recv.clone())
1380        }
1381        "setEncoding" | "setTimeout" | "pause" | "resume" => Ok(recv.clone()),
1382        _ => Err(crate::host::type_error(&format!(
1383            "stream.{method} is not a function"
1384        ))),
1385    }
1386}
1387
1388/// The lazily-created object holding compat `setHeader` values before the response.
1389fn pending_headers_obj(recv: &Value) -> Value {
1390    if let Some(bag) = get_prop(recv, "@@pendingHeaders") {
1391        return bag;
1392    }
1393    let bag = with_host(|h| h.new_object(IndexMap::new()));
1394    set_prop(recv, "@@pendingHeaders", bag.clone());
1395    bag
1396}
1397
1398/// Send a HEADERS response frame with the given headers (a `:status` is injected if
1399/// none present). Marks the stream responded.
1400fn do_respond(recv: &Value, mut headers: Vec<(String, String)>, end: bool) -> Result<(), String> {
1401    // Merge any compat setHeader() values collected before respond/writeHead.
1402    if let Some(bag) = get_prop(recv, "@@pendingHeaders") {
1403        for (k, v) in object_pairs(&bag) {
1404            if !headers.iter().any(|(hk, _)| hk.eq_ignore_ascii_case(&k)) {
1405                headers.push((k, v));
1406            }
1407        }
1408    }
1409    // Ensure a single `:status` pseudo-header appears first (HTTP/2 requires
1410    // pseudo-headers to precede regular ones).
1411    let status = headers
1412        .iter()
1413        .find(|(k, _)| k == ":status")
1414        .map(|(_, v)| v.clone())
1415        .unwrap_or_else(|| "200".to_string());
1416    let mut ordered: Vec<(String, String)> = vec![(":status".to_string(), status)];
1417    for (k, v) in headers.into_iter() {
1418        if k == ":status" {
1419            continue;
1420        }
1421        // HTTP/2 header names must be lowercase.
1422        ordered.push((k.to_ascii_lowercase(), v));
1423    }
1424
1425    let Some(key) = stream_key_of(recv) else {
1426        return Ok(());
1427    };
1428    H2.with(|s| {
1429        if let Some(r) = s.borrow_mut().streams.get_mut(&key) {
1430            if !r.responded {
1431                r.responded = true;
1432                let _ = r.tx.send(H2Cmd::Respond {
1433                    stream_id: r.stream_id,
1434                    headers: ordered,
1435                    end,
1436                });
1437            }
1438        }
1439    });
1440    Ok(())
1441}
1442
1443/// Ensure the response HEADERS have been sent (auto-`respond` with 200 otherwise).
1444fn ensure_responded(recv: &Value) -> Result<(), String> {
1445    let Some(key) = stream_key_of(recv) else {
1446        return Ok(());
1447    };
1448    let responded = H2.with(|s| {
1449        s.borrow()
1450            .streams
1451            .get(&key)
1452            .map(|r| r.responded)
1453            .unwrap_or(true)
1454    });
1455    if !responded {
1456        do_respond(recv, Vec::new(), false)?;
1457    }
1458    Ok(())
1459}
1460
1461/// Queue a DATA frame for this stream's connection thread.
1462fn send_stream_data(recv: &Value, data: Vec<u8>, end: bool) {
1463    if let Some(key) = stream_key_of(recv) {
1464        H2.with(|s| {
1465            if let Some(r) = s.borrow().streams.get(&key) {
1466                let _ = r.tx.send(H2Cmd::Data {
1467                    stream_id: r.stream_id,
1468                    data,
1469                    end,
1470                });
1471            }
1472        });
1473    }
1474}
1475
1476// ── Http2Session instance methods ────────────────────────────────────────────
1477
1478fn session_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
1479    if let Some(r) = emitter_dispatch(recv, method, &args) {
1480        return r;
1481    }
1482    match method {
1483        "close" | "destroy" | "goaway" => {
1484            if let Some(key) = u64_prop(recv, "@@h2session") {
1485                H2.with(|s| {
1486                    if let Some(r) = s.borrow().sessions.get(&key) {
1487                        let _ = r.tx.send(H2Cmd::Goaway);
1488                    }
1489                });
1490            }
1491            super::events::instance_call(recv, "emit", vec![with_host(|h| h.new_str("close"))])?;
1492            Ok(recv.clone())
1493        }
1494        "settings" | "ping" | "ref" | "unref" | "setTimeout" => Ok(recv.clone()),
1495        _ => Err(crate::host::type_error(&format!(
1496            "session.{method} is not a function"
1497        ))),
1498    }
1499}
1500
1501// ── shared emitter constructor (same shape as net/tls) ───────────────────────
1502
1503/// Build a native emitter object (`@@native` tag + `@@on`/`@@once` maps + extras),
1504/// sharing the EventEmitter shape with `events`/`net`/`tls`.
1505pub fn new_emitter_object(tag: &str, mut extra: IndexMap<String, Value>) -> Value {
1506    with_host(|h| {
1507        let on = h.new_object(IndexMap::new());
1508        let once = h.new_object(IndexMap::new());
1509        let mut m = IndexMap::new();
1510        m.insert("@@native".into(), h.new_str(tag));
1511        m.insert("@@on".into(), on);
1512        m.insert("@@once".into(), once);
1513        for (k, v) in extra.drain(..) {
1514            m.insert(k, v);
1515        }
1516        h.new_object(m)
1517    })
1518}