1use 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
19pub const MODULE_METHODS: &[&str] = &[
21 "createServer",
22 "request",
23 "get",
24 "validateHeaderName",
25 "validateHeaderValue",
26 "setMaxIdleHTTPParsers",
27 "setGlobalProxyFromEnv",
28];
29
30pub 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
44const 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
84pub 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 "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 "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 "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
137pub fn construct(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
139 match name {
140 "Agent" => Some(Ok(construct_agent(args))),
141 "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
151pub 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
187struct HttpConn {
191 socket: Value,
193 listener: Value,
195 buf: Vec<u8>,
197}
198
199struct ResState {
202 sock_id: u64,
204 head: bool,
209 status: u16,
211 message: Option<String>,
213 headers: Vec<(String, String)>,
216 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
236pub 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 "setMaxIdleHTTPParsers" | "setGlobalProxyFromEnv" => Some(Ok(Value::Undef)),
248 _ => None,
249 }
250}
251
252fn 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
267fn 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
291fn 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
316pub 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
339pub 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
371pub fn drop_conn(sock_id: u64) {
373 CONNS.with(|c| {
374 c.borrow_mut().remove(&sock_id);
375 });
376}
377
378pub 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 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 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; }
439 Ok(())
440}
441
442struct ParsedReq {
444 method: String,
445 url: String,
446 http_version: String,
447 headers: Vec<(String, String)>,
449 raw_headers: Vec<(String, String)>,
453 body: Vec<u8>,
454}
455
456fn parse_request(buf: &[u8]) -> Option<(ParsedReq, usize)> {
459 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 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
513fn 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
550fn incoming_call(recv: &Value, method: &str, args: Vec<Value>) -> Result<Value, String> {
557 match method {
558 "pause" | "resume" | "unpipe" | "destroy" => Ok(recv.clone()),
562 "isPaused" => Ok(Value::Bool(false)),
563 "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
580fn 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
610pub fn instance_call(
613 tag: &str,
614 recv: &Value,
615 method: &str,
616 args: Vec<Value>,
617) -> Result<Value, String> {
618 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 "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 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 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 "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
800fn finish_response(res: &Value, resid: u64) -> Result<(), String> {
802 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
829fn 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 if st.head {
867 } 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
882fn 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
896fn 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
909fn 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
918fn 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
932struct ClientReq {
942 host: String,
943 port: u16,
944 method: String,
945 path: String,
946 headers: Vec<(String, String)>,
947 body: Vec<u8>,
948 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
978pub 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 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
1059fn 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
1157fn 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 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
1230pub(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
1276pub(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 if (100..200).contains(&status) {
1294 return false;
1295 }
1296 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 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
1325fn 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 return find_subslice(&data[nl + 2..], b"\r\n").is_some();
1340 }
1341 let consumed = nl + 2 + size + 2;
1343 if data.len() < consumed {
1344 return false;
1345 }
1346 data = &data[consumed..];
1347 }
1348}
1349
1350fn 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 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
1400fn 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
1420pub(crate) struct ParsedRes {
1424 pub status: u16,
1425 pub message: String,
1426 pub http_version: String,
1427 pub headers: Vec<(String, String)>,
1429 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
1483fn 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
1506fn 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 #[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 #[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 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 #[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 #[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 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 #[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 #[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 #[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 #[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}