Skip to main content

nodejs/stdlib/
http.rs

1//! Node `http` module: an HTTP/1.1 server built on top of `net`.
2//!
3//! `http.createServer(requestListener)` returns a `net.Server` with an
4//! `http`-specific per-connection hook. As bytes arrive on a connection (posted
5//! by the socket reader thread and dispatched on the main thread by
6//! `net::on_socket_data` → `http::feed`), we buffer them, parse complete
7//! HTTP/1.1 requests, and for each one build an `IncomingMessage` (`req`) and a
8//! `ServerResponse` (`res`) and call the user's `(req, res)` listener on the main
9//! thread. `res.end` serializes a valid HTTP/1.1 response and writes it straight
10//! back to the socket via `net::socket_write_id`, keeping the connection alive.
11
12use crate::host::{invoke, with_host, JsObj};
13use fusevm::Value;
14use indexmap::IndexMap;
15use std::collections::HashMap;
16use std::io::{Read, Write};
17use std::net::TcpStream;
18
19/// `http` module functions routed through `stdlib::call`.
20pub const MODULE_METHODS: &[&str] = &[
21    "createServer",
22    "request",
23    "get",
24    "validateHeaderName",
25    "validateHeaderValue",
26    "setMaxIdleHTTPParsers",
27    "setGlobalProxyFromEnv",
28];
29
30/// Instance methods of a client `ClientRequest` (parent wires the `ClientRequest`
31/// tag via `native_tag`/`instance_call`).
32pub const CLIENT_REQUEST_METHODS: &[&str] = &[
33    "write",
34    "end",
35    "setHeader",
36    "getHeader",
37    "removeHeader",
38    "abort",
39    "destroy",
40    "setTimeout",
41    "flushHeaders",
42];
43
44/// The HTTP request methods Node exposes as `http.METHODS` (router derives its
45/// per-verb helpers by lowercasing this list).
46const METHODS: &[&str] = &[
47    "ACL",
48    "BIND",
49    "CHECKOUT",
50    "CONNECT",
51    "COPY",
52    "DELETE",
53    "GET",
54    "HEAD",
55    "LINK",
56    "LOCK",
57    "M-SEARCH",
58    "MERGE",
59    "MKACTIVITY",
60    "MKCALENDAR",
61    "MKCOL",
62    "MOVE",
63    "NOTIFY",
64    "OPTIONS",
65    "PATCH",
66    "POST",
67    "PROPFIND",
68    "PROPPATCH",
69    "PURGE",
70    "PUT",
71    "QUERY",
72    "REBIND",
73    "REPORT",
74    "SEARCH",
75    "SOURCE",
76    "SUBSCRIBE",
77    "TRACE",
78    "UNBIND",
79    "UNLINK",
80    "UNLOCK",
81    "UNSUBSCRIBE",
82];
83
84/// Non-function `http` module constants (`http.METHODS`, `http.STATUS_CODES`),
85/// reachable via `namespace_property` → `stdlib::constant`.
86pub fn constant(name: &str) -> Option<Value> {
87    match name {
88        "METHODS" => Some(with_host(|h| {
89            let items = METHODS.iter().map(|m| h.new_str(*m)).collect();
90            h.new_array(items)
91        })),
92        "STATUS_CODES" => Some(with_host(|h| {
93            let mut m = IndexMap::new();
94            for (code, msg) in crate::stdlib::http::status_table() {
95                m.insert(code.to_string(), h.new_str(*msg));
96            }
97            h.new_object(m)
98        })),
99        // The request/response constructors express augments
100        // (`Object.create(http.IncomingMessage.prototype)`): exposed as builtin
101        // ctor namespaces so `.prototype` resolves.
102        "IncomingMessage" => Some(with_host(|h| {
103            h.alloc(JsObj::Builtin("IncomingMessage".into()))
104        })),
105        "ServerResponse" => Some(with_host(|h| {
106            h.alloc(JsObj::Builtin("ServerResponse".into()))
107        })),
108        // Client/server constructors exposed as builtin ctor namespaces so
109        // `.prototype` resolves and `new http.X(...)` routes to `http::construct`.
110        // `http.Server` uses a distinct builtin name to disambiguate from
111        // `net.Server` in the shared `stdlib::construct`.
112        "Agent" => Some(with_host(|h| h.alloc(JsObj::Builtin("Agent".into())))),
113        "Server" => Some(with_host(|h| h.alloc(JsObj::Builtin("http.Server".into())))),
114        "ClientRequest" => Some(with_host(|h| {
115            h.alloc(JsObj::Builtin("ClientRequest".into()))
116        })),
117        "OutgoingMessage" => Some(with_host(|h| {
118            h.alloc(JsObj::Builtin("OutgoingMessage".into()))
119        })),
120        // One Agent for the process: `http.globalAgent === http.globalAgent`.
121        // Each read built a new one.
122        "globalAgent" => {
123            thread_local! {
124                static AGENT: std::cell::RefCell<Option<Value>> = const { std::cell::RefCell::new(None) };
125            }
126            if let Some(a) = AGENT.with(|a| a.borrow().clone()) {
127                return Some(a);
128            }
129            let a = construct_agent(&[]);
130            AGENT.with(|slot| *slot.borrow_mut() = Some(a.clone()));
131            Some(a)
132        }
133        _ => None,
134    }
135}
136
137/// `stdlib::construct` entry for `http` classes. Parent wires this in.
138pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
139    match name {
140        "Agent" => Some(Ok(construct_agent(args))),
141        // `new http.Server([requestListener])`.
142        "http.Server" => Some(Ok(create_server(
143            args.first()
144                .cloned()
145                .filter(|v| with_host(|h| crate::host::is_callable(h, v))),
146        ))),
147        _ => None,
148    }
149}
150
151/// The status-code → reason-phrase table shared by `STATUS_CODES` and response
152/// serialization.
153pub fn status_table() -> &'static [(u16, &'static str)] {
154    &[
155        (200, "OK"),
156        (201, "Created"),
157        (202, "Accepted"),
158        (204, "No Content"),
159        (301, "Moved Permanently"),
160        (302, "Found"),
161        (303, "See Other"),
162        (304, "Not Modified"),
163        (307, "Temporary Redirect"),
164        (308, "Permanent Redirect"),
165        (400, "Bad Request"),
166        (401, "Unauthorized"),
167        (403, "Forbidden"),
168        (404, "Not Found"),
169        (405, "Method Not Allowed"),
170        (406, "Not Acceptable"),
171        (409, "Conflict"),
172        (410, "Gone"),
173        (411, "Length Required"),
174        (413, "Payload Too Large"),
175        (414, "URI Too Long"),
176        (415, "Unsupported Media Type"),
177        (422, "Unprocessable Entity"),
178        (429, "Too Many Requests"),
179        (500, "Internal Server Error"),
180        (501, "Not Implemented"),
181        (502, "Bad Gateway"),
182        (503, "Service Unavailable"),
183        (504, "Gateway Timeout"),
184    ]
185}
186
187// ── per-connection parse state ───────────────────────────────────────────────
188
189/// Main-thread state for one live HTTP connection, keyed by the `net` socket id.
190struct HttpConn {
191    /// The underlying `net.Socket` object.
192    socket: Value,
193    /// The user's `requestListener` (`(req, res) => …`).
194    listener: Value,
195    /// Bytes received but not yet consumed into a complete request.
196    buf: Vec<u8>,
197}
198
199/// Main-thread state for one in-flight response, keyed by a fresh response id
200/// (stored on the `res` object as `@@resid`).
201struct ResState {
202    /// Socket id to write the serialized response to.
203    sock_id: u64,
204    /// The request was a HEAD, so the response carries headers and no body
205    /// (RFC 9110 §9.3.2). The headers stay exactly as a GET would produce
206    /// them — `Content-Length` still describes the body that GET *would*
207    /// return — only the bytes after the blank line are suppressed.
208    head: bool,
209    /// Status code (`writeHead`/`res.statusCode`).
210    status: u16,
211    /// Optional custom status message.
212    message: Option<String>,
213    /// Response headers in insertion order; name kept as given, matched
214    /// case-insensitively.
215    headers: Vec<(String, String)>,
216    /// Accumulated body bytes (`write`/`end`).
217    body: Vec<u8>,
218}
219
220thread_local! {
221    static CONNS: std::cell::RefCell<HashMap<u64, HttpConn>> =
222        std::cell::RefCell::new(HashMap::new());
223    static RESPONSES: std::cell::RefCell<HashMap<u64, ResState>> =
224        std::cell::RefCell::new(HashMap::new());
225    static NEXT_RESID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
226}
227
228fn next_resid() -> u64 {
229    NEXT_RESID.with(|c| {
230        let id = c.get();
231        c.set(id + 1);
232        id
233    })
234}
235
236// ── module: http.createServer ────────────────────────────────────────────────
237
238/// `stdlib::call` entry for `http.<method>`.
239pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
240    match method {
241        "createServer" => Some(Ok(create_server(args.first().cloned()))),
242        "request" => Some(request(args, false)),
243        "get" => Some(request(args, true)),
244        "validateHeaderName" => Some(validate_header_name(args)),
245        "validateHeaderValue" => Some(validate_header_value(args)),
246        // No pooling/proxy substrate: accepted no-ops (match Node's `undefined`).
247        "setMaxIdleHTTPParsers" | "setGlobalProxyFromEnv" => Some(Ok(Value::Undef)),
248        _ => None,
249    }
250}
251
252/// `http.validateHeaderName(name[, label])` — throws `ERR_INVALID_HTTP_TOKEN`
253/// unless `name` is a valid RFC 7230 field-name token, else returns `undefined`.
254fn validate_header_name(args: &[Value]) -> Result<Value, String> {
255    let name = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
256    if is_valid_token(&name) {
257        Ok(Value::Undef)
258    } else {
259        Err(crate::host::coded_error(
260            "TypeError",
261            "ERR_INVALID_HTTP_TOKEN",
262            &format!("Header name must be a valid HTTP token [\"{name}\"]"),
263        ))
264    }
265}
266
267/// `http.validateHeaderValue(name, value)` — throws if `value` is `undefined`
268/// (`ERR_HTTP_INVALID_HEADER_VALUE`) or contains an invalid character
269/// (`ERR_INVALID_CHAR`), else returns `undefined`.
270fn validate_header_value(args: &[Value]) -> Result<Value, String> {
271    let name = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
272    let raw = args.get(1).cloned().unwrap_or(Value::Undef);
273    if matches!(raw, Value::Undef) {
274        return Err(crate::host::coded_error(
275            "TypeError",
276            "ERR_HTTP_INVALID_HEADER_VALUE",
277            &format!("Invalid value \"undefined\" for header \"{name}\""),
278        ));
279    }
280    let value = with_host(|h| h.str_of(&raw));
281    if value.bytes().any(|b| b != b'\t' && (b < 0x20 || b == 0x7f)) {
282        return Err(crate::host::coded_error(
283            "TypeError",
284            "ERR_INVALID_CHAR",
285            &format!("Invalid character in header content [\"{name}\"]"),
286        ));
287    }
288    Ok(Value::Undef)
289}
290
291/// RFC 7230 field-name token: one or more of the `tchar` set.
292fn is_valid_token(s: &str) -> bool {
293    !s.is_empty()
294        && s.bytes().all(|b| {
295            b.is_ascii_alphanumeric()
296                || matches!(
297                    b,
298                    b'!' | b'#'
299                        | b'$'
300                        | b'%'
301                        | b'&'
302                        | b'\''
303                        | b'*'
304                        | b'+'
305                        | b'-'
306                        | b'.'
307                        | b'^'
308                        | b'_'
309                        | b'`'
310                        | b'|'
311                        | b'~'
312                )
313        })
314}
315
316/// `new http.Agent([options])` — a minimal connection-pool holder. We open a
317/// fresh connection per request (no reuse), so the agent only carries its
318/// configuration for the JS side to read back.
319pub fn construct_agent(args: &[Value]) -> Value {
320    let pairs = args
321        .first()
322        .filter(|v| matches!(v, Value::Obj(_)))
323        .map(object_pairs)
324        .unwrap_or_default();
325    with_host(|h| {
326        let mut m = IndexMap::new();
327        m.insert("@@native".into(), h.new_str("Agent"));
328        m.insert("maxSockets".into(), Value::Float(f64::INFINITY));
329        m.insert("maxFreeSockets".into(), Value::Float(256.0));
330        m.insert("sockets".into(), h.new_object(IndexMap::new()));
331        m.insert("requests".into(), h.new_object(IndexMap::new()));
332        for (k, v) in pairs {
333            m.insert(k, h.new_str(v));
334        }
335        h.new_object(m)
336    })
337}
338
339/// Build an HTTP server: a `net.Server` whose per-connection hook wires up the
340/// request parser and remembers the `requestListener`.
341pub fn create_server(request_listener: Option<Value>) -> Value {
342    let server = super::net::create_server(None);
343    let listener = request_listener.unwrap_or(Value::Undef);
344    let hook = std::rc::Rc::new(
345        move |_server: &Value, socket: &Value| -> Result<(), String> {
346            let sock_id = socket_id_of(socket);
347            CONNS.with(|c| {
348                c.borrow_mut().insert(
349                    sock_id,
350                    HttpConn {
351                        socket: socket.clone(),
352                        listener: listener.clone(),
353                        buf: Vec::new(),
354                    },
355                );
356            });
357            Ok(())
358        },
359    );
360    super::net::set_conn_hook(&server, hook);
361    server
362}
363
364fn socket_id_of(socket: &Value) -> u64 {
365    with_host(|h| match h.get(socket) {
366        Some(JsObj::Object(p)) => p.get("@@netid").map(|v| h.to_number(v) as u64).unwrap_or(0),
367        _ => 0,
368    })
369}
370
371/// Discard an HTTP connection when its socket closes.
372pub fn drop_conn(sock_id: u64) {
373    CONNS.with(|c| {
374        c.borrow_mut().remove(&sock_id);
375    });
376}
377
378// ── request parsing ──────────────────────────────────────────────────────────
379
380/// Feed freshly received socket bytes into the HTTP parser. No-op for a socket
381/// that is not an HTTP connection (plain `net`). Runs on the main thread.
382pub fn feed(sock_id: u64, _socket: &Value, bytes: &[u8]) -> Result<(), String> {
383    let is_http = CONNS.with(|c| c.borrow().contains_key(&sock_id));
384    if !is_http {
385        return Ok(());
386    }
387    CONNS.with(|c| {
388        c.borrow_mut()
389            .get_mut(&sock_id)
390            .unwrap()
391            .buf
392            .extend_from_slice(bytes)
393    });
394
395    // Parse and dispatch every complete request currently buffered (pipelining).
396    loop {
397        let (listener, socket, parsed) = CONNS.with(|c| {
398            let mut c = c.borrow_mut();
399            let conn = c.get_mut(&sock_id).unwrap();
400            match parse_request(&conn.buf) {
401                Some((req, consumed)) => {
402                    conn.buf.drain(..consumed);
403                    (conn.listener.clone(), conn.socket.clone(), Some(req))
404                }
405                None => (Value::Undef, Value::Undef, None),
406            }
407        });
408        let Some(parsed) = parsed else { break };
409
410        let req = build_incoming(&parsed);
411        let res = build_response(sock_id, parsed.method.eq_ignore_ascii_case("HEAD"));
412        if with_host(|h| crate::host::is_callable(h, &listener)) {
413            invoke(&listener, vec![req.clone(), res], None)?;
414        }
415        // Body streaming: emit any request body then `end` for downstream readers.
416        // A listener that called `req.setEncoding(enc)` gets a decoded string
417        // chunk instead of a Buffer, matching Node's Readable.
418        if !parsed.body.is_empty() {
419            let encoding = with_host(|h| match h.get(&req) {
420                Some(JsObj::Object(p)) => p.get("@@encoding").map(|v| h.str_of(v)),
421                _ => None,
422            });
423            let chunk = match encoding {
424                Some(enc) => with_host(|h| {
425                    let s = super::buffer::encode_bytes(&parsed.body, &enc);
426                    h.new_str(s)
427                }),
428                None => super::buffer::from_bytes(&parsed.body),
429            };
430            super::events::instance_call(
431                &req,
432                "emit",
433                vec![with_host(|h| h.new_str("data")), chunk],
434            )?;
435        }
436        super::events::instance_call(&req, "emit", vec![with_host(|h| h.new_str("end"))])?;
437        let _ = socket; // (kept for future keep-alive bookkeeping)
438    }
439    Ok(())
440}
441
442/// A fully parsed HTTP request.
443struct ParsedReq {
444    method: String,
445    url: String,
446    http_version: String,
447    /// Lowercased header name → value (last wins, like Node for simple headers).
448    headers: Vec<(String, String)>,
449    /// The same headers in WIRE order and case, for `rawHeaders`. The lowered
450    /// map cannot express either, so a caller needing the original casing or a
451    /// repeated header has nothing to read without it.
452    raw_headers: Vec<(String, String)>,
453    body: Vec<u8>,
454}
455
456/// Try to parse one complete request from `buf`. Returns the request and the
457/// number of bytes consumed, or `None` if more bytes are needed.
458fn parse_request(buf: &[u8]) -> Option<(ParsedReq, usize)> {
459    // Header block ends at the first CRLFCRLF.
460    let head_end = find_subslice(buf, b"\r\n\r\n")?;
461    let head = &buf[..head_end];
462    let body_start = head_end + 4;
463
464    let head_str = String::from_utf8_lossy(head);
465    let mut lines = head_str.split("\r\n");
466    let request_line = lines.next()?;
467    let mut parts = request_line.split(' ');
468    let method = parts.next()?.to_string();
469    let url = parts.next()?.to_string();
470    let version = parts.next().unwrap_or("HTTP/1.1");
471    let http_version = version.strip_prefix("HTTP/").unwrap_or("1.1").to_string();
472
473    let mut headers: Vec<(String, String)> = Vec::new();
474    let mut raw_headers: Vec<(String, String)> = Vec::new();
475    let mut content_length = 0usize;
476    for line in lines {
477        if line.is_empty() {
478            continue;
479        }
480        if let Some((k, v)) = line.split_once(':') {
481            let name = k.trim().to_ascii_lowercase();
482            let value = v.trim().to_string();
483            if name == "content-length" {
484                content_length = value.parse().unwrap_or(0);
485            }
486            raw_headers.push((k.trim().to_string(), value.clone()));
487            headers.push((name, value));
488        }
489    }
490
491    // Need the full body before dispatching.
492    if buf.len() < body_start + content_length {
493        return None;
494    }
495    let body = buf[body_start..body_start + content_length].to_vec();
496    Some((
497        ParsedReq {
498            method,
499            url,
500            http_version,
501            headers,
502            raw_headers,
503            body,
504        },
505        body_start + content_length,
506    ))
507}
508
509fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
510    haystack.windows(needle.len()).position(|w| w == needle)
511}
512
513// ── IncomingMessage (req) ────────────────────────────────────────────────────
514
515/// `rawHeaders`: the flat name/value list in WIRE order and case. The `headers`
516/// object is lower-cased and one-value-per-name, so it can express neither.
517fn flat_headers(pairs: &[(String, String)]) -> Value {
518    with_host(|h| {
519        let flat: Vec<Value> = pairs
520            .iter()
521            .flat_map(|(k, v)| [h.new_str(k.clone()), h.new_str(v.clone())])
522            .collect();
523        h.new_array(flat)
524    })
525}
526
527fn build_incoming(req: &ParsedReq) -> Value {
528    let headers_obj = with_host(|h| {
529        let mut m = IndexMap::new();
530        for (k, v) in &req.headers {
531            m.insert(k.clone(), h.new_str(v.clone()));
532        }
533        h.new_object(m)
534    });
535    let mut extra = IndexMap::new();
536    extra.insert(
537        "method".into(),
538        with_host(|h| h.new_str(req.method.clone())),
539    );
540    extra.insert("url".into(), with_host(|h| h.new_str(req.url.clone())));
541    extra.insert(
542        "httpVersion".into(),
543        with_host(|h| h.new_str(req.http_version.clone())),
544    );
545    extra.insert("headers".into(), headers_obj);
546    extra.insert("rawHeaders".into(), flat_headers(&req.raw_headers));
547    super::net::new_emitter_object("IncomingMessage", extra)
548}
549
550/// The Readable surface of `req`. node-js reads the whole request body off the
551/// socket BEFORE invoking the listener and then delivers it as a single `data`
552/// emit followed by `end` — so there is no partially-consumed stream to pause,
553/// resume or unpipe, and these really are complete rather than stubbed.
554/// `setEncoding` is the exception: it changes what the `data` chunk IS, so it
555/// records the encoding and `emit_body` decodes with it.
556fn incoming_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
557    match method {
558        // Nothing is piped anywhere (node-js has no `pipe` on `req`), and the
559        // body is already buffered, so these are no-ops that return `this` —
560        // which is exactly Node's contract for an already-drained readable.
561        "pause" | "resume" | "unpipe" | "destroy" => Ok(recv.clone()),
562        "isPaused" => Ok(Value::Bool(false)),
563        // Subsequent `data` chunks arrive as strings in this encoding.
564        "setEncoding" => {
565            let enc = super::arg_str(&args, 0);
566            with_host(|h| {
567                let v = h.new_str(enc);
568                if let Some(JsObj::Object(p)) = h.get_mut(recv) {
569                    p.insert("@@encoding".into(), v);
570                }
571            });
572            Ok(recv.clone())
573        }
574        _ => Err(crate::host::type_error(&format!(
575            "req.{method} is not a function"
576        ))),
577    }
578}
579
580// ── ServerResponse (res) ─────────────────────────────────────────────────────
581
582fn build_response(sock_id: u64, head: bool) -> Value {
583    let resid = next_resid();
584    RESPONSES.with(|r| {
585        r.borrow_mut().insert(
586            resid,
587            ResState {
588                sock_id,
589                head,
590                status: 200,
591                message: None,
592                headers: Vec::new(),
593                body: Vec::new(),
594            },
595        );
596    });
597    let mut extra = IndexMap::new();
598    extra.insert("@@resid".into(), Value::Float(resid as f64));
599    extra.insert("statusCode".into(), Value::Float(200.0));
600    super::net::new_emitter_object("ServerResponse", extra)
601}
602
603fn resid_of(res: &Value) -> Option<u64> {
604    with_host(|h| match h.get(res) {
605        Some(JsObj::Object(p)) => p.get("@@resid").map(|v| h.to_number(v) as u64),
606        _ => None,
607    })
608}
609
610/// Instance dispatch for `IncomingMessage`/`ServerResponse` (EventEmitter methods
611/// handled by `net`'s shared emitter delegation via `stdlib::instance_call`).
612pub fn instance_call(
613    tag: &str,
614    recv: &Value,
615    method: &str,
616    args: Vec<Value>,
617) -> Result<Value, String> {
618    // EventEmitter surface is shared with `net` sockets, and the set of names is
619    // read from `events::METHODS` rather than re-listed: the copy that used to
620    // live here was missing `listeners`, `setMaxListeners` and `getMaxListeners`,
621    // so `unpipe` — reached from `body-parser` on every `express.json()` request
622    // — died on `req.listeners('data') is not a function`.
623    if super::events::METHODS.contains(&method) {
624        return super::events::instance_call(recv, method, args);
625    }
626    match tag {
627        "IncomingMessage" => incoming_call(recv, method, args),
628        "ServerResponse" => response_call(recv, method, args),
629        "ClientRequest" => client_request_call(recv, method, args),
630        // Minimal Agent: no live sockets to tear down.
631        "Agent" => match method {
632            "destroy" => Ok(Value::Undef),
633            "getName" => Ok(with_host(|h| h.new_str("localhost:80:"))),
634            _ => Err(crate::host::type_error(&format!(
635                "agent.{method} is not a function"
636            ))),
637        },
638        _ => Err(crate::host::type_error(&format!(
639            "{method} is not a function"
640        ))),
641    }
642}
643
644fn response_call(res: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
645    let Some(resid) = resid_of(res) else {
646        return Err(crate::host::type_error("invalid ServerResponse"));
647    };
648    match method {
649        "writeHead" => {
650            let status =
651                with_host(|h| args.first().map(|v| h.to_number(v)).unwrap_or(200.0)) as u16;
652            // Second arg is either the status message (string) or the headers obj.
653            let mut message: Option<String> = None;
654            let mut headers_arg: Option<Value> = None;
655            if let Some(a) = args.get(1) {
656                if with_host(|h| h.as_str(a)).is_some() {
657                    message = Some(with_host(|h| h.str_of(a)));
658                } else if !matches!(a, Value::Undef) {
659                    headers_arg = Some(a.clone());
660                }
661            }
662            if let Some(a) = args.get(2) {
663                if !matches!(a, Value::Undef) {
664                    headers_arg = Some(a.clone());
665                }
666            }
667            let header_pairs = headers_arg.map(|h| object_pairs(&h)).unwrap_or_default();
668            RESPONSES.with(|r| {
669                if let Some(st) = r.borrow_mut().get_mut(&resid) {
670                    st.status = status;
671                    st.message = message;
672                    for (k, v) in header_pairs {
673                        upsert_header(&mut st.headers, &k, v);
674                    }
675                }
676            });
677            // Mirror onto the JS prop so `res.statusCode` reads reflect it.
678            set_res_prop(res, "statusCode", Value::Float(status as f64));
679            Ok(res.clone())
680        }
681        "setHeader" => {
682            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
683            let v = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
684            RESPONSES.with(|r| {
685                if let Some(st) = r.borrow_mut().get_mut(&resid) {
686                    upsert_header(&mut st.headers, &k, v);
687                }
688            });
689            Ok(Value::Undef)
690        }
691        "getHeader" => {
692            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)))
693                .to_ascii_lowercase();
694            let val = RESPONSES.with(|r| {
695                r.borrow().get(&resid).and_then(|st| {
696                    st.headers
697                        .iter()
698                        .find(|(hk, _)| hk.eq_ignore_ascii_case(&k))
699                        .map(|(_, v)| v.clone())
700                })
701            });
702            Ok(val
703                .map(|v| with_host(|h| h.new_str(v)))
704                .unwrap_or(Value::Undef))
705        }
706        "removeHeader" => {
707            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
708            RESPONSES.with(|r| {
709                if let Some(st) = r.borrow_mut().get_mut(&resid) {
710                    st.headers.retain(|(hk, _)| !hk.eq_ignore_ascii_case(&k));
711                }
712            });
713            Ok(Value::Undef)
714        }
715        "write" => {
716            let bytes = value_bytes(args.first());
717            RESPONSES.with(|r| {
718                if let Some(st) = r.borrow_mut().get_mut(&resid) {
719                    st.body.extend_from_slice(&bytes);
720                }
721            });
722            Ok(Value::Bool(true))
723        }
724        "end" => {
725            if let Some(chunk) = args.first().filter(|v| !matches!(v, Value::Undef)) {
726                let bytes = value_bytes(Some(chunk));
727                RESPONSES.with(|r| {
728                    if let Some(st) = r.borrow_mut().get_mut(&resid) {
729                        st.body.extend_from_slice(&bytes);
730                    }
731                });
732            }
733            finish_response(res, resid)?;
734            Ok(res.clone())
735        }
736        // Advertised in `stdlib::instance_methods` for ServerResponse and
737        // implemented in `https::response_call`, but missing here — so
738        // `res.flushHeaders()` threw "is not a function" over plaintext while
739        // working over TLS. A no-op is the honest implementation either way:
740        // `write` buffers into `ResState.body` and nothing reaches the socket
741        // until `end`, so there is no partial header block to flush.
742        // Advertised in `stdlib::instance_methods` for ServerResponse but never
743        // implemented in either module, so all three threw "is not a function"
744        // on both protocols despite feature-detection saying they exist.
745        // Node lowercases the names it reports, so these do too, while
746        // `setHeader` keeps the caller's spelling on the wire.
747        "hasHeader" => {
748            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
749            let found = RESPONSES.with(|r| {
750                r.borrow()
751                    .get(&resid)
752                    .is_some_and(|st| st.headers.iter().any(|(hk, _)| hk.eq_ignore_ascii_case(&k)))
753            });
754            Ok(Value::Bool(found))
755        }
756        "getHeaderNames" => {
757            let names = RESPONSES.with(|r| {
758                r.borrow()
759                    .get(&resid)
760                    .map(|st| {
761                        st.headers
762                            .iter()
763                            .map(|(k, _)| k.to_ascii_lowercase())
764                            .collect::<Vec<_>>()
765                    })
766                    .unwrap_or_default()
767            });
768            Ok(with_host(|h| {
769                let items = names.into_iter().map(|n| h.new_str(n)).collect::<Vec<_>>();
770                h.new_array(items)
771            }))
772        }
773        "getHeaders" => {
774            let pairs = RESPONSES.with(|r| {
775                r.borrow()
776                    .get(&resid)
777                    .map(|st| {
778                        st.headers
779                            .iter()
780                            .map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))
781                            .collect::<Vec<_>>()
782                    })
783                    .unwrap_or_default()
784            });
785            Ok(with_host(|h| {
786                let mut m = IndexMap::new();
787                for (k, v) in pairs {
788                    m.insert(k, h.new_str(v));
789                }
790                h.new_object(m)
791            }))
792        }
793        "flushHeaders" => Ok(Value::Undef),
794        _ => Err(crate::host::type_error(&format!(
795            "res.{method} is not a function"
796        ))),
797    }
798}
799
800/// Serialize and write the response, then emit `finish`.
801fn finish_response(res: &Value, resid: u64) -> Result<(), String> {
802    // Reconcile status with a possible `res.statusCode = n` assignment, and the
803    // reason phrase with `res.statusMessage = '…'`. Only the code was being
804    // read back, so a custom message set that way was dropped and the default
805    // phrase for the code went out instead.
806    let (js_status, js_message) = with_host(|h| match h.get(res) {
807        Some(JsObj::Object(p)) => (
808            p.get("statusCode").map(|v| h.to_number(v) as u16),
809            p.get("statusMessage")
810                .filter(|v| !matches!(v, Value::Undef))
811                .map(|v| h.str_of(v)),
812        ),
813        _ => (None, None),
814    });
815    let st = RESPONSES.with(|r| r.borrow_mut().remove(&resid));
816    let Some(mut st) = st else { return Ok(()) };
817    if let Some(s) = js_status {
818        st.status = s;
819    }
820    if let Some(m) = js_message {
821        st.message = Some(m);
822    }
823    let payload = serialize_response(&mut st);
824    super::net::socket_write_id(st.sock_id, &payload);
825    super::events::instance_call(res, "emit", vec![with_host(|h| h.new_str("finish"))])?;
826    Ok(())
827}
828
829/// Build the raw HTTP/1.1 response bytes: status line, headers (adding
830/// `Content-Length` and `Connection: keep-alive` if the user did not set framing
831/// headers), CRLFCRLF, then the body.
832fn serialize_response(st: &mut ResState) -> Vec<u8> {
833    let reason = st
834        .message
835        .clone()
836        .unwrap_or_else(|| status_text(st.status).to_string());
837    let mut out = format!("HTTP/1.1 {} {}\r\n", st.status, reason).into_bytes();
838
839    let has = |name: &str| st.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case(name));
840    let chunked = st.headers.iter().any(|(k, v)| {
841        k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked")
842    });
843
844    for (k, v) in &st.headers {
845        out.extend_from_slice(format!("{k}: {v}\r\n").as_bytes());
846    }
847    if !chunked && !has("content-length") {
848        out.extend_from_slice(format!("Content-Length: {}\r\n", st.body.len()).as_bytes());
849    }
850    if !has("connection") {
851        out.extend_from_slice(b"Connection: keep-alive\r\n");
852    }
853    out.extend_from_slice(b"\r\n");
854    // `Transfer-Encoding: chunked` is a promise about the BODY's framing, not
855    // just a header. Writing the bytes raw under it sent, for a handler that
856    // set the header and wrote "one" then "two":
857    //
858    //     Transfer-Encoding: chunked\r\n\r\nonetwo
859    //
860    // which any conforming client reads as a chunk-size line of "onetwo" — not
861    // hex, so the body is lost. Our own client only survived it by falling back
862    // to reading until EOF. `res.write` buffers into one `body` rather than
863    // streaming, so the boundaries between writes are already gone by here;
864    // one chunk carrying the whole body is the honest encoding of what we have,
865    // and chunk boundaries carry no meaning to the receiver.
866    if st.head {
867        // Headers only. `Content-Length`/`Transfer-Encoding` above already
868        // describe the GET body, which is what a HEAD response must advertise.
869    } else if chunked {
870        if !st.body.is_empty() {
871            out.extend_from_slice(format!("{:x}\r\n", st.body.len()).as_bytes());
872            out.extend_from_slice(&st.body);
873            out.extend_from_slice(b"\r\n");
874        }
875        out.extend_from_slice(b"0\r\n\r\n");
876    } else {
877        out.extend_from_slice(&st.body);
878    }
879    out
880}
881
882// ── helpers ──────────────────────────────────────────────────────────────────
883
884/// Insert or replace a header (case-insensitive name match), preserving order.
885fn upsert_header(headers: &mut Vec<(String, String)>, name: &str, value: String) {
886    if let Some(slot) = headers
887        .iter_mut()
888        .find(|(k, _)| k.eq_ignore_ascii_case(name))
889    {
890        slot.1 = value;
891    } else {
892        headers.push((name.to_string(), value));
893    }
894}
895
896/// Enumerable string key/value pairs of a plain object (for the `writeHead`
897/// headers argument).
898fn object_pairs(obj: &Value) -> Vec<(String, String)> {
899    with_host(|h| match h.get(obj) {
900        Some(JsObj::Object(p)) => p
901            .iter()
902            .filter(|(k, _)| !k.starts_with("@@") && !k.starts_with('#'))
903            .map(|(k, v)| (k.clone(), h.str_of(v)))
904            .collect(),
905        _ => Vec::new(),
906    })
907}
908
909/// Set a JS-visible prop on the response object.
910fn set_res_prop(res: &Value, key: &str, val: Value) {
911    with_host(|h| {
912        if let Some(JsObj::Object(p)) = h.get_mut(res) {
913            p.insert(key.to_string(), val);
914        }
915    });
916}
917
918/// Raw bytes of a `write`/`end` argument: a Buffer's bytes, or a string's UTF-8.
919fn value_bytes(v: Option<&Value>) -> Vec<u8> {
920    let Some(v) = v else { return Vec::new() };
921    let is_buffer =
922        with_host(|h| matches!(h.get(v), Some(JsObj::Object(p)) if p.contains_key("@@bytes")));
923    if is_buffer {
924        return with_host(|h| match h.get(v) {
925            Some(JsObj::Object(p)) => crate::stdlib::buffer::window_bytes_h(h, p),
926            _ => Vec::new(),
927        });
928    }
929    with_host(|h| h.str_of(v)).into_bytes()
930}
931
932// ── client: http.request / http.get ──────────────────────────────────────────
933//
934// Mirrors the `https` client (https.rs), but over a plain `TcpStream` on port 80.
935// `.end()` (or `http.get` immediately) spawns a background thread that connects,
936// writes the request, reads the full response to EOF (the request forces
937// `Connection: close`), parses it, and posts an `IoTask` that emits `response`
938// with an `IncomingMessage` (then its body `data`/`end`) on the main thread.
939
940/// State of an in-flight client request until `.end()` dispatches it.
941struct ClientReq {
942    host: String,
943    port: u16,
944    method: String,
945    path: String,
946    headers: Vec<(String, String)>,
947    body: Vec<u8>,
948    /// The `req` object (a `ClientRequest` emitter) for `response`/`error` events.
949    request: Value,
950    sent: bool,
951}
952
953thread_local! {
954    static CLIENT_REQS: std::cell::RefCell<HashMap<u64, ClientReq>> =
955        std::cell::RefCell::new(HashMap::new());
956    static NEXT_REQID: std::cell::Cell<u64> = const { std::cell::Cell::new(1) };
957}
958
959fn next_reqid() -> u64 {
960    NEXT_REQID.with(|c| {
961        let id = c.get();
962        c.set(id + 1);
963        id
964    })
965}
966
967fn get_prop(recv: &Value, key: &str) -> Option<Value> {
968    with_host(|h| match h.get(recv) {
969        Some(JsObj::Object(p)) => p.get(key).cloned(),
970        _ => None,
971    })
972}
973
974fn u64_prop(recv: &Value, key: &str) -> Option<u64> {
975    get_prop(recv, key).map(|v| with_host(|h| h.to_number(&v)) as u64)
976}
977
978/// `http.request(options|url[, cb])` / `http.get(url|options[, cb])`. Returns a
979/// `ClientRequest` (a `ClientRequest` emitter). `get` auto-sends via `.end()`.
980pub fn request(args: &[Value], is_get: bool) -> Result<Value, String> {
981    let mut host = "localhost".to_string();
982    let mut port: u16 = 80;
983    let mut path = "/".to_string();
984    let mut method = "GET".to_string();
985    let mut headers: Vec<(String, String)> = Vec::new();
986    let mut cb: Option<Value> = None;
987
988    for a in args {
989        if with_host(|h| crate::host::is_callable(h, a)) {
990            cb = Some(a.clone());
991        } else if with_host(|h| h.as_str(a)).is_some() {
992            let url = with_host(|h| h.str_of(a));
993            parse_url(&url, &mut host, &mut port, &mut path);
994        } else if matches!(a, Value::Obj(_)) {
995            for key in ["hostname", "host"] {
996                if let Some(v) = get_prop(a, key).filter(|v| with_host(|h| h.as_str(v)).is_some()) {
997                    host = with_host(|h| h.str_of(&v));
998                }
999            }
1000            if let Some(v) = get_prop(a, "port") {
1001                let n = with_host(|h| h.to_number(&v));
1002                if !n.is_nan() {
1003                    port = n as u16;
1004                }
1005            }
1006            if let Some(v) = get_prop(a, "path").filter(|v| with_host(|h| h.as_str(v)).is_some()) {
1007                path = with_host(|h| h.str_of(&v));
1008            }
1009            if let Some(v) = get_prop(a, "method").filter(|v| with_host(|h| h.as_str(v)).is_some())
1010            {
1011                method = with_host(|h| h.str_of(&v));
1012            }
1013            if let Some(hv) = get_prop(a, "headers").filter(|v| matches!(v, Value::Obj(_))) {
1014                for (k, val) in object_pairs(&hv) {
1015                    headers.push((k, val));
1016                }
1017            }
1018        }
1019    }
1020    if is_get {
1021        method = "GET".to_string();
1022    }
1023
1024    let reqid = next_reqid();
1025    let mut extra = IndexMap::new();
1026    extra.insert("@@reqid".into(), Value::Float(reqid as f64));
1027    extra.insert("method".into(), with_host(|h| h.new_str(method.clone())));
1028    extra.insert("path".into(), with_host(|h| h.new_str(path.clone())));
1029    let request = super::net::new_emitter_object("ClientRequest", extra);
1030    // The `cb` is registered as the `response` listener (Node semantics).
1031    if let Some(cb) = cb {
1032        super::events::instance_call(
1033            &request,
1034            "on",
1035            vec![with_host(|h| h.new_str("response")), cb],
1036        )?;
1037    }
1038    CLIENT_REQS.with(|c| {
1039        c.borrow_mut().insert(
1040            reqid,
1041            ClientReq {
1042                host,
1043                port,
1044                method,
1045                path,
1046                headers,
1047                body: Vec::new(),
1048                request: request.clone(),
1049                sent: false,
1050            },
1051        );
1052    });
1053    if is_get {
1054        dispatch_request(reqid)?;
1055    }
1056    Ok(request)
1057}
1058
1059/// Parse an `http://host[:port][/path]` URL into its parts (defaults port 80).
1060fn parse_url(url: &str, host: &mut String, port: &mut u16, path: &mut String) {
1061    let rest = url.strip_prefix("http://").unwrap_or(url);
1062    let (authority, p) = match rest.find('/') {
1063        Some(i) => (&rest[..i], &rest[i..]),
1064        None => (rest, "/"),
1065    };
1066    *path = if p.is_empty() {
1067        "/".to_string()
1068    } else {
1069        p.to_string()
1070    };
1071    if let Some((h, port_str)) = authority.rsplit_once(':') {
1072        *host = h.to_string();
1073        if let Ok(n) = port_str.parse::<u16>() {
1074            *port = n;
1075        }
1076    } else {
1077        *host = authority.to_string();
1078        *port = 80;
1079    }
1080}
1081
1082fn client_request_call(req: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
1083    let reqid = u64_prop(req, "@@reqid");
1084    match method {
1085        "write" => {
1086            if let Some(id) = reqid {
1087                let bytes = value_bytes(args.first());
1088                CLIENT_REQS.with(|c| {
1089                    if let Some(r) = c.borrow_mut().get_mut(&id) {
1090                        r.body.extend_from_slice(&bytes);
1091                    }
1092                });
1093            }
1094            Ok(Value::Bool(true))
1095        }
1096        "end" => {
1097            if let Some(id) = reqid {
1098                if let Some(chunk) = args.first().filter(|v| !matches!(v, Value::Undef)) {
1099                    let bytes = value_bytes(Some(chunk));
1100                    CLIENT_REQS.with(|c| {
1101                        if let Some(r) = c.borrow_mut().get_mut(&id) {
1102                            r.body.extend_from_slice(&bytes);
1103                        }
1104                    });
1105                }
1106                dispatch_request(id)?;
1107            }
1108            Ok(req.clone())
1109        }
1110        "setHeader" => {
1111            if let Some(id) = reqid {
1112                let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
1113                let v = with_host(|h| h.str_of(&args.get(1).cloned().unwrap_or(Value::Undef)));
1114                CLIENT_REQS.with(|c| {
1115                    if let Some(r) = c.borrow_mut().get_mut(&id) {
1116                        upsert_header(&mut r.headers, &k, v);
1117                    }
1118                });
1119            }
1120            Ok(Value::Undef)
1121        }
1122        "getHeader" => {
1123            let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)))
1124                .to_ascii_lowercase();
1125            let val = reqid.and_then(|id| {
1126                CLIENT_REQS.with(|c| {
1127                    c.borrow().get(&id).and_then(|r| {
1128                        r.headers
1129                            .iter()
1130                            .find(|(hk, _)| hk.eq_ignore_ascii_case(&k))
1131                            .map(|(_, v)| v.clone())
1132                    })
1133                })
1134            });
1135            Ok(val
1136                .map(|v| with_host(|h| h.new_str(v)))
1137                .unwrap_or(Value::Undef))
1138        }
1139        "removeHeader" => {
1140            if let Some(id) = reqid {
1141                let k = with_host(|h| h.str_of(&args.first().cloned().unwrap_or(Value::Undef)));
1142                CLIENT_REQS.with(|c| {
1143                    if let Some(r) = c.borrow_mut().get_mut(&id) {
1144                        r.headers.retain(|(hk, _)| !hk.eq_ignore_ascii_case(&k));
1145                    }
1146                });
1147            }
1148            Ok(Value::Undef)
1149        }
1150        "abort" | "destroy" | "setTimeout" | "flushHeaders" => Ok(req.clone()),
1151        _ => Err(crate::host::type_error(&format!(
1152            "req.{method} is not a function"
1153        ))),
1154    }
1155}
1156
1157/// Spawn the blocking HTTP exchange for a client request on a background thread;
1158/// the parsed response is posted back to the main thread.
1159fn dispatch_request(reqid: u64) -> Result<(), String> {
1160    let sent = CLIENT_REQS.with(|c| c.borrow().get(&reqid).map(|r| r.sent).unwrap_or(true));
1161    if sent {
1162        return Ok(());
1163    }
1164    CLIENT_REQS.with(|c| {
1165        if let Some(r) = c.borrow_mut().get_mut(&reqid) {
1166            r.sent = true;
1167        }
1168    });
1169
1170    let (host, port, method, path, headers, body) = CLIENT_REQS.with(|c| {
1171        let b = c.borrow();
1172        let r = b.get(&reqid).unwrap();
1173        (
1174            r.host.clone(),
1175            r.port,
1176            r.method.clone(),
1177            r.path.clone(),
1178            r.headers.clone(),
1179            r.body.clone(),
1180        )
1181    });
1182
1183    let io_tx = with_host(|h| h.io_sender());
1184    with_host(|h| h.incr_handle());
1185
1186    // Build the request bytes (force `Connection: close` for read-to-EOF).
1187    let mut has_host = false;
1188    let mut has_len = false;
1189    let mut header_block = String::new();
1190    for (k, v) in &headers {
1191        if k.eq_ignore_ascii_case("host") {
1192            has_host = true;
1193        }
1194        if k.eq_ignore_ascii_case("content-length") {
1195            has_len = true;
1196        }
1197        if k.eq_ignore_ascii_case("connection") {
1198            continue;
1199        }
1200        header_block.push_str(&format!("{k}: {v}\r\n"));
1201    }
1202    let host_header = if port == 80 {
1203        host.clone()
1204    } else {
1205        format!("{host}:{port}")
1206    };
1207    let mut request_bytes = format!("{method} {path} HTTP/1.1\r\n");
1208    if !has_host {
1209        request_bytes.push_str(&format!("Host: {host_header}\r\n"));
1210    }
1211    request_bytes.push_str(&header_block);
1212    if !has_len && !body.is_empty() {
1213        request_bytes.push_str(&format!("Content-Length: {}\r\n", body.len()));
1214    }
1215    request_bytes.push_str("Connection: close\r\n\r\n");
1216    let mut wire = request_bytes.into_bytes();
1217    wire.extend_from_slice(&body);
1218
1219    std::thread::spawn(move || match exchange(&host, port, &wire) {
1220        Ok(raw) => {
1221            let _ = io_tx.send(Box::new(move || deliver_response(reqid, raw)));
1222        }
1223        Err(msg) => {
1224            let _ = io_tx.send(Box::new(move || deliver_error(reqid, msg)));
1225        }
1226    });
1227    Ok(())
1228}
1229
1230/// The blocking TCP round-trip: connect, write the request, read until the
1231/// response message is COMPLETE — by its own framing when it has one, and only
1232/// then to EOF.
1233///
1234/// Reading unconditionally to EOF made the client depend on the server hanging
1235/// up. Against `http.createServer` it does not: the response carries
1236/// `Content-Length` and `Connection: keep-alive`, and nothing closes the
1237/// connection, so a request served by this runtime's own server deadlocked —
1238/// the caller waiting for a FIN that the server, waiting for the caller, would
1239/// never send. Node's client stops at the end of the message, and so does this
1240/// one now; the EOF path survives only for a response with no framing at all
1241/// (HTTP/1.0 style), which is the one case where EOF *is* the framing.
1242pub(crate) fn exchange(host: &str, port: u16, request: &[u8]) -> Result<Vec<u8>, String> {
1243    let mut stream = TcpStream::connect((host, port))
1244        .map_err(|e| format!("Error: connect ECONNREFUSED {host}:{port}: {e}"))?;
1245    stream
1246        .write_all(request)
1247        .map_err(|e| format!("Error: http write: {e}"))?;
1248    stream
1249        .flush()
1250        .map_err(|e| format!("Error: http flush: {e}"))?;
1251    let head_request = request
1252        .split(|b| *b == b' ')
1253        .next()
1254        .is_some_and(|m| m.eq_ignore_ascii_case(b"HEAD"));
1255    let mut raw = Vec::new();
1256    let mut buf = [0u8; 16384];
1257    loop {
1258        if response_is_complete(&raw, head_request) {
1259            break;
1260        }
1261        match stream.read(&mut buf) {
1262            Ok(0) => break,
1263            Ok(n) => raw.extend_from_slice(&buf[..n]),
1264            Err(ref e) if e.kind() == std::io::ErrorKind::UnexpectedEof => break,
1265            Err(e) => {
1266                if raw.is_empty() {
1267                    return Err(format!("Error: http read: {e}"));
1268                }
1269                break;
1270            }
1271        }
1272    }
1273    Ok(raw)
1274}
1275
1276/// Whether `raw` already holds a whole HTTP/1.1 response, per RFC 9112 §6.3.
1277///
1278/// `false` for anything unframed — a response with neither `Transfer-Encoding:
1279/// chunked` nor `Content-Length`, where the end of the body IS the end of the
1280/// connection — so the caller keeps reading to EOF exactly as it used to.
1281pub(crate) fn response_is_complete(raw: &[u8], head_request: bool) -> bool {
1282    let Some(head_end) = find_subslice(raw, b"\r\n\r\n") else {
1283        return false;
1284    };
1285    let head = String::from_utf8_lossy(&raw[..head_end]);
1286    let mut lines = head.split("\r\n");
1287    let status = lines
1288        .next()
1289        .and_then(|l| l.split(' ').nth(1).and_then(|s| s.parse::<u16>().ok()))
1290        .unwrap_or(0);
1291    // A 1xx is an INTERIM response: the real one follows on the same
1292    // connection, so the message is not finished and reading continues.
1293    if (100..200).contains(&status) {
1294        return false;
1295    }
1296    // These carry no body however they are framed (RFC 9112 §6.3, cases 1-2).
1297    if head_request || status == 204 || status == 304 {
1298        return true;
1299    }
1300    let mut chunked = false;
1301    let mut content_length: Option<usize> = None;
1302    for line in lines {
1303        let Some((k, v)) = line.split_once(':') else {
1304            continue;
1305        };
1306        let name = k.trim().to_ascii_lowercase();
1307        let value = v.trim();
1308        if name == "transfer-encoding" && value.to_ascii_lowercase().contains("chunked") {
1309            chunked = true;
1310        } else if name == "content-length" {
1311            content_length = value.parse().ok();
1312        }
1313    }
1314    let body = &raw[head_end + 4..];
1315    // Chunked wins over Content-Length when both are present (RFC 9112 §6.3).
1316    if chunked {
1317        return chunked_body_is_terminated(body);
1318    }
1319    match content_length {
1320        Some(n) => body.len() >= n,
1321        None => false,
1322    }
1323}
1324
1325/// Whether a chunked body has reached its terminating zero-size chunk and the
1326/// trailer section's closing CRLF.
1327fn chunked_body_is_terminated(mut data: &[u8]) -> bool {
1328    loop {
1329        let Some(nl) = find_subslice(data, b"\r\n") else {
1330            return false;
1331        };
1332        let size_line = String::from_utf8_lossy(&data[..nl]);
1333        let Ok(size) = usize::from_str_radix(size_line.split(';').next().unwrap_or("").trim(), 16)
1334        else {
1335            return false;
1336        };
1337        if size == 0 {
1338            // Trailer section (possibly empty) ends at the next blank line.
1339            return find_subslice(&data[nl + 2..], b"\r\n").is_some();
1340        }
1341        // chunk-data + its trailing CRLF.
1342        let consumed = nl + 2 + size + 2;
1343        if data.len() < consumed {
1344            return false;
1345        }
1346        data = &data[consumed..];
1347    }
1348}
1349
1350/// Parse the raw response and emit `response` (with an `IncomingMessage`), then
1351/// the body `data`/`end`. Runs on the main thread.
1352fn deliver_response(reqid: u64, raw: Vec<u8>) -> Result<(), String> {
1353    let entry = CLIENT_REQS.with(|c| c.borrow_mut().remove(&reqid));
1354    with_host(|h| h.decr_handle());
1355    let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1356    let Some(entry) = entry else { return Ok(()) };
1357
1358    let ParsedRes {
1359        status,
1360        message,
1361        http_version,
1362        headers,
1363        raw_headers: raw_header_pairs,
1364        body,
1365    } = parse_raw_response(&raw);
1366
1367    let headers_obj = with_host(|h| {
1368        let mut m = IndexMap::new();
1369        for (k, v) in &headers {
1370            m.insert(k.clone(), h.new_str(v.clone()));
1371        }
1372        h.new_object(m)
1373    });
1374    // `rawHeaders` is the flat name/value list in WIRE order and case, which
1375    // `headers` (lower-cased and de-duplicated into an object) cannot express.
1376    // It was absent entirely, so a caller needing the original casing or a
1377    // repeated header had nothing to read.
1378    let raw_headers = flat_headers(&raw_header_pairs);
1379    let mut extra = IndexMap::new();
1380    extra.insert("rawHeaders".into(), raw_headers);
1381    extra.insert("statusCode".into(), Value::Float(status as f64));
1382    extra.insert("statusMessage".into(), with_host(|h| h.new_str(message)));
1383    extra.insert("httpVersion".into(), with_host(|h| h.new_str(http_version)));
1384    extra.insert("headers".into(), headers_obj);
1385    let res = super::net::new_emitter_object("IncomingMessage", extra);
1386
1387    super::events::instance_call(
1388        &entry.request,
1389        "emit",
1390        vec![with_host(|h| h.new_str("response")), res.clone()],
1391    )?;
1392    if !body.is_empty() {
1393        let chunk = super::buffer::from_bytes(&body);
1394        super::events::instance_call(&res, "emit", vec![with_host(|h| h.new_str("data")), chunk])?;
1395    }
1396    super::events::instance_call(&res, "emit", vec![with_host(|h| h.new_str("end"))])?;
1397    Ok(())
1398}
1399
1400/// Emit `error` on the request when the exchange fails. Runs on the main thread.
1401fn deliver_error(reqid: u64, msg: String) -> Result<(), String> {
1402    let entry = CLIENT_REQS.with(|c| c.borrow_mut().remove(&reqid));
1403    with_host(|h| h.decr_handle());
1404    let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1405    if let Some(entry) = entry {
1406        let err = with_host(|h| {
1407            let mut m = IndexMap::new();
1408            m.insert("message".into(), h.new_str(msg.clone()));
1409            h.new_object(m)
1410        });
1411        super::events::instance_call(
1412            &entry.request,
1413            "emit",
1414            vec![with_host(|h| h.new_str("error")), err],
1415        )?;
1416    }
1417    Ok(())
1418}
1419
1420/// Parse a raw HTTP/1.1 response into `(status, message, version, headers, body)`.
1421/// Handles `Transfer-Encoding: chunked` and plain (Content-Length / to-EOF) bodies.
1422/// One parsed HTTP response.
1423pub(crate) struct ParsedRes {
1424    pub status: u16,
1425    pub message: String,
1426    pub http_version: String,
1427    /// Lower-cased name → value, for the `headers` object.
1428    pub headers: Vec<(String, String)>,
1429    /// The same headers in wire order and case, for `rawHeaders`.
1430    pub raw_headers: Vec<(String, String)>,
1431    pub body: Vec<u8>,
1432}
1433
1434pub(crate) fn parse_raw_response(raw: &[u8]) -> ParsedRes {
1435    let head_end = find_subslice(raw, b"\r\n\r\n").unwrap_or(raw.len());
1436    let head = String::from_utf8_lossy(&raw[..head_end]);
1437    let body_start = (head_end + 4).min(raw.len());
1438    let mut lines = head.split("\r\n");
1439    let status_line = lines.next().unwrap_or("");
1440    let mut sp = status_line.splitn(3, ' ');
1441    let version = sp
1442        .next()
1443        .unwrap_or("HTTP/1.1")
1444        .strip_prefix("HTTP/")
1445        .unwrap_or("1.1")
1446        .to_string();
1447    let status = sp.next().and_then(|s| s.parse::<u16>().ok()).unwrap_or(0);
1448    let message = sp.next().unwrap_or("").to_string();
1449
1450    let mut headers: Vec<(String, String)> = Vec::new();
1451    let mut raw_headers: Vec<(String, String)> = Vec::new();
1452    let mut chunked = false;
1453    for line in lines {
1454        if line.is_empty() {
1455            continue;
1456        }
1457        if let Some((k, v)) = line.split_once(':') {
1458            let name = k.trim().to_ascii_lowercase();
1459            let value = v.trim().to_string();
1460            if name == "transfer-encoding" && value.to_ascii_lowercase().contains("chunked") {
1461                chunked = true;
1462            }
1463            raw_headers.push((k.trim().to_string(), value.clone()));
1464            headers.push((name, value));
1465        }
1466    }
1467    let raw_body = &raw[body_start..];
1468    let body = if chunked {
1469        decode_chunked(raw_body)
1470    } else {
1471        raw_body.to_vec()
1472    };
1473    ParsedRes {
1474        status,
1475        message,
1476        http_version: version,
1477        headers,
1478        raw_headers,
1479        body,
1480    }
1481}
1482
1483/// Decode an HTTP/1.1 chunked body (best-effort; stops at the terminating
1484/// 0-chunk or when the input is exhausted).
1485fn decode_chunked(mut data: &[u8]) -> Vec<u8> {
1486    let mut out = Vec::new();
1487    while let Some(nl) = find_subslice(data, b"\r\n") {
1488        let size_line = String::from_utf8_lossy(&data[..nl]);
1489        let size_hex = size_line.split(';').next().unwrap_or("").trim();
1490        let size = usize::from_str_radix(size_hex, 16).unwrap_or(0);
1491        if size == 0 {
1492            break;
1493        }
1494        let chunk_start = nl + 2;
1495        let chunk_end = (chunk_start + size).min(data.len());
1496        out.extend_from_slice(&data[chunk_start..chunk_end]);
1497        let next = chunk_end + 2;
1498        if next >= data.len() {
1499            break;
1500        }
1501        data = &data[next..];
1502    }
1503    out
1504}
1505
1506/// Standard reason phrase for common status codes (default `OK`).
1507fn status_text(code: u16) -> &'static str {
1508    match code {
1509        200 => "OK",
1510        201 => "Created",
1511        202 => "Accepted",
1512        204 => "No Content",
1513        301 => "Moved Permanently",
1514        302 => "Found",
1515        304 => "Not Modified",
1516        400 => "Bad Request",
1517        401 => "Unauthorized",
1518        403 => "Forbidden",
1519        404 => "Not Found",
1520        405 => "Method Not Allowed",
1521        409 => "Conflict",
1522        500 => "Internal Server Error",
1523        502 => "Bad Gateway",
1524        503 => "Service Unavailable",
1525        _ => "OK",
1526    }
1527}
1528
1529#[cfg(test)]
1530mod framing_tests {
1531    use super::{response_is_complete, serialize_response, ResState};
1532
1533    /// The shape `http.createServer` writes: `Content-Length` plus
1534    /// `Connection: keep-alive`, and no FIN. Reading to EOF deadlocked here.
1535    #[test]
1536    fn a_keep_alive_content_length_response_is_complete_at_its_last_body_byte() {
1537        let head = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\
1538                     Content-Length: 12\r\nConnection: keep-alive\r\n\r\n";
1539        let mut raw = head.to_vec();
1540        assert!(!response_is_complete(&raw, false), "no body yet");
1541        raw.extend_from_slice(b"hello GET /");
1542        assert!(!response_is_complete(&raw, false), "11 of 12 bytes");
1543        raw.push(b'p');
1544        assert!(response_is_complete(&raw, false), "12 of 12 bytes");
1545    }
1546
1547    /// The encoder's own output must satisfy the decoder. `serialize_response`
1548    /// frames a chunked body and `response_is_complete` decides when one has
1549    /// arrived; if they disagree the client hangs waiting for a terminator the
1550    /// server never wrote, which is what happened when the body went out raw
1551    /// under a `Transfer-Encoding: chunked` header.
1552    #[test]
1553    fn a_chunked_response_this_server_wrote_is_complete_to_this_client() {
1554        let mut st = ResState {
1555            sock_id: 0,
1556            head: false,
1557            status: 200,
1558            message: None,
1559            headers: vec![("Transfer-Encoding".into(), "chunked".into())],
1560            body: b"onetwo".to_vec(),
1561        };
1562        let wire = serialize_response(&mut st);
1563        assert!(
1564            wire.ends_with(b"\r\n\r\n6\r\nonetwo\r\n0\r\n\r\n"),
1565            "unexpected framing: {}",
1566            String::from_utf8_lossy(&wire)
1567        );
1568        assert!(response_is_complete(&wire, false));
1569        // Every prefix short of the terminator must still read as incomplete,
1570        // so the client keeps reading rather than truncating the body.
1571        for cut in 1..wire.len() {
1572            assert!(
1573                !response_is_complete(&wire[..cut], false),
1574                "a {cut}-byte prefix was reported complete"
1575            );
1576        }
1577    }
1578
1579    /// An empty chunked body is still a terminator, not nothing.
1580    #[test]
1581    fn an_empty_chunked_response_is_just_the_zero_chunk() {
1582        let mut st = ResState {
1583            sock_id: 0,
1584            head: false,
1585            status: 200,
1586            message: None,
1587            headers: vec![("Transfer-Encoding".into(), "chunked".into())],
1588            body: Vec::new(),
1589        };
1590        let wire = serialize_response(&mut st);
1591        assert!(
1592            wire.ends_with(b"\r\n\r\n0\r\n\r\n"),
1593            "{}",
1594            String::from_utf8_lossy(&wire)
1595        );
1596        assert!(response_is_complete(&wire, false));
1597    }
1598
1599    /// A HEAD response keeps the headers a GET would send and drops the body.
1600    #[test]
1601    fn a_head_response_advertises_the_get_length_and_sends_no_body() {
1602        let mk = |head: bool| {
1603            let mut st = ResState {
1604                sock_id: 0,
1605                head,
1606                status: 200,
1607                message: None,
1608                headers: vec![("Content-Type".into(), "text/plain".into())],
1609                body: b"body-here".to_vec(),
1610            };
1611            serialize_response(&mut st)
1612        };
1613        let head = mk(true);
1614        let get = mk(false);
1615        let text = String::from_utf8_lossy(&head).into_owned();
1616        assert!(text.contains("Content-Length: 9"), "{text}");
1617        assert!(
1618            text.ends_with("\r\n\r\n"),
1619            "HEAD must stop at the blank line: {text}"
1620        );
1621        assert!(String::from_utf8_lossy(&get).ends_with("body-here"));
1622        // Identical headers, differing only in the body that follows.
1623        let split = |v: &[u8]| {
1624            String::from_utf8_lossy(v)
1625                .split("\r\n\r\n")
1626                .next()
1627                .unwrap()
1628                .to_string()
1629        };
1630        assert_eq!(split(&head), split(&get));
1631    }
1632
1633    #[test]
1634    fn a_partial_header_block_is_never_complete() {
1635        assert!(!response_is_complete(b"", false));
1636        assert!(!response_is_complete(b"HTTP/1.1 200 OK\r\n", false));
1637        assert!(!response_is_complete(
1638            b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n",
1639            false
1640        ));
1641    }
1642
1643    /// No `Content-Length` and no `Transfer-Encoding`: the connection close IS
1644    /// the framing, so the caller must keep reading to EOF.
1645    #[test]
1646    fn an_unframed_response_is_never_reported_complete() {
1647        let raw = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nbody bytes";
1648        assert!(!response_is_complete(raw, false));
1649    }
1650
1651    #[test]
1652    fn a_chunked_body_completes_only_at_its_zero_chunk() {
1653        let head = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n";
1654        let mut raw = head.to_vec();
1655        assert!(!response_is_complete(&raw, false));
1656        raw.extend_from_slice(b"5\r\nhello\r\n");
1657        assert!(
1658            !response_is_complete(&raw, false),
1659            "one chunk, no terminator"
1660        );
1661        raw.extend_from_slice(b"0\r\n");
1662        assert!(
1663            !response_is_complete(&raw, false),
1664            "trailer CRLF still missing"
1665        );
1666        raw.extend_from_slice(b"\r\n");
1667        assert!(response_is_complete(&raw, false));
1668    }
1669
1670    /// A chunk size line may carry extensions, and `Transfer-Encoding` wins
1671    /// over a `Content-Length` that arrives with it (RFC 9112 §6.3).
1672    #[test]
1673    fn chunk_extensions_parse_and_chunked_outranks_content_length() {
1674        let raw = b"HTTP/1.1 200 OK\r\nContent-Length: 99\r\nTransfer-Encoding: chunked\r\n\r\n\
1675                    3;name=v\r\nabc\r\n0\r\n\r\n";
1676        assert!(response_is_complete(raw, false));
1677        let short =
1678            b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nTransfer-Encoding: chunked\r\n\r\nabc";
1679        assert!(
1680            !response_is_complete(short, false),
1681            "Content-Length must not settle a chunked response"
1682        );
1683    }
1684
1685    /// 204 and 304 carry no body whatever the headers claim, and neither does
1686    /// any response to a HEAD.
1687    #[test]
1688    fn bodiless_statuses_and_head_finish_at_the_header_block() {
1689        assert!(response_is_complete(
1690            b"HTTP/1.1 204 No Content\r\nContent-Length: 7\r\n\r\n",
1691            false
1692        ));
1693        assert!(response_is_complete(
1694            b"HTTP/1.1 304 Not Modified\r\nContent-Length: 7\r\n\r\n",
1695            false
1696        ));
1697        assert!(response_is_complete(
1698            b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n",
1699            true
1700        ));
1701        assert!(
1702            !response_is_complete(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n", false),
1703            "the same response to a GET still needs its body"
1704        );
1705    }
1706
1707    /// A 1xx is interim: the real response follows on the same connection.
1708    #[test]
1709    fn an_interim_response_does_not_end_the_read() {
1710        assert!(!response_is_complete(
1711            b"HTTP/1.1 100 Continue\r\n\r\n",
1712            false
1713        ));
1714        assert!(!response_is_complete(
1715            b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\n",
1716            false
1717        ));
1718    }
1719}