1use 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
86pub const METHODS: &[&str] = &[
88 "createSecureServer",
89 "createServer",
90 "connect",
91 "getDefaultSettings",
92 "getPackedSettings",
93 "getUnpackedSettings",
94];
95
96pub 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 "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
125const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
128
129const 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
140const FL_END_STREAM: u8 = 0x1;
142const FL_ACK: u8 = 0x1; const FL_END_HEADERS: u8 = 0x4;
144const FL_PADDED: u8 = 0x8;
145const FL_PRIORITY: u8 = 0x20;
146
147const MAX_FRAME_SIZE: usize = 16384;
149
150static 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
166enum H2Cmd {
170 Respond {
173 stream_id: u32,
174 headers: Vec<(String, String)>,
175 end: bool,
176 },
177 Data {
179 stream_id: u32,
180 data: Vec<u8>,
181 end: bool,
182 },
183 Close { stream_id: u32 },
185 Goaway,
187}
188
189struct H2ServerRec {
192 emitter: Value,
193 stop: Arc<AtomicBool>,
194}
195
196struct H2StreamRec {
197 emitter: Value,
198 tx: Sender<H2Cmd>,
199 stream_id: u32,
200 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 static PENDING_CONFIGS: std::cell::RefCell<Vec<(Value, Arc<ServerConfig>)>> =
222 const { std::cell::RefCell::new(Vec::new()) };
223}
224
225fn 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
246fn 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
253fn 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
267fn 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
280pub 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
303pub fn constant(name: &str) -> Option<Value> {
306 match name {
307 "constants" => Some(constants_object()),
308 "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
320fn 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 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 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 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 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
377fn 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
390fn 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
398fn 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
433fn 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 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 _ => {}
474 }
475 }
476 Ok(with_host(|h| h.new_object(m)))
477}
478
479fn 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 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
516fn 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 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
545pub 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
578fn 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
675fn serve_connection(
681 server_id: u64,
682 mut sock: TcpStream,
683 config: Arc<ServerConfig>,
684 io_tx: Sender<IoTask>,
685) {
686 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 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 stream.conn.send_close_notify();
704 let _ = stream.flush();
705 let _ = stream.sock.shutdown(std::net::Shutdown::Both);
706 return;
707 }
708 let (tx, rx) = std::sync::mpsc::channel::<H2Cmd>();
710
711 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 let mut ok = true;
730 ok &= write_frame(&mut stream, FT_SETTINGS, 0, 0, &[]).is_ok();
731 ok &= stream.flush().is_ok();
732 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 let mut id_to_key: HashMap<u32, u64> = HashMap::new();
746 let mut buf = [0u8; MAX_FRAME_SIZE];
747
748 'conn: loop {
749 if !ok {
753 break;
754 }
755 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 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 if !got_preface {
809 if inbuf.len() < PREFACE.len() {
810 continue;
811 }
812 if &inbuf[..PREFACE.len()] != PREFACE {
813 break; }
815 inbuf.drain(..PREFACE.len());
816 got_preface = true;
817 }
818
819 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; }
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 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 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 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 FT_WINDOW_UPDATE | FT_PRIORITY | FT_RST_STREAM | FT_CONTINUATION => {}
906 _ => {}
908 }
909 }
910 }
911
912 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()); 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 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
933fn 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
943fn 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 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
1000fn 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
1025fn 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
1047fn 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
1056fn 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; }
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
1075fn 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
1088fn 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
1125fn 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 let _ = with_host(|h| h.io_sender()).send(Box::new(|| Ok(())));
1138 Ok(())
1139}
1140
1141fn 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 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 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 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 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 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
1237fn report_handler_error(event: &str, err: &str) {
1242 eprintln!("http2: uncaught error in '{event}' handler: {err}");
1243}
1244
1245fn h2_debug() -> bool {
1248 std::env::var_os("HTTP2_DEBUG").is_some()
1249}
1250
1251fn 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
1288fn 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 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 "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 hdrs.insert(0, (":status".to_string(), status.to_string()));
1323 do_respond(recv, hdrs, false)?;
1324 Ok(recv.clone())
1325 }
1326 "setHeader" => {
1327 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
1388fn 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
1398fn do_respond(recv: &Value, mut headers: Vec<(String, String)>, end: bool) -> Result<(), String> {
1401 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 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 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
1443fn 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
1461fn 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
1476fn 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
1501pub 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}