http_net/message.rs
1//! Outgoing messages: the `Response` a server sends and the `Request` a
2//! client sends.
3//!
4//! Both builders validate as they go and remember the first problem instead
5//! of failing each call, so a message can be built in one chained
6//! expression; the problem surfaces as an error when the connection writes
7//! the message. Framing headers (`content-length`, `transfer-encoding`,
8//! `connection`, `upgrade`) are owned by the connection, which derives them
9//! from the body and the exchange; setting them by hand is refused, which
10//! makes conflicting framing on the way out impossible.
11
12use alloc::{borrow::Cow, format, string::String, vec::Vec};
13use core::fmt;
14
15use crate::{
16 error::HttpError,
17 forward::is_hop_by_hop,
18 head::{BodyFraming, RequestHead, check_target, is_h2c},
19 method::Method,
20 redact::{SerializedFields, serialized_fields},
21 scan::{check_field_value, is_protocol, is_token, trim_ows},
22 write::Output,
23};
24
25/// How an outgoing message's body is supplied.
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub(crate) enum OutBody {
28 /// The whole body, sent with `content-length`.
29 Full(Cow<'static, [u8]>),
30 /// Streamed afterwards with exactly this many bytes.
31 Length(u64),
32 /// Streamed afterwards with chunked encoding.
33 Chunked,
34}
35
36/// Fields RFC 9110 section 6.5.1 keeps out of trailers: those that frame
37/// the message, route or authenticate it, modify the request, control the
38/// response, or describe the content. A recipient may process a trailer
39/// after the body, too late for any of them. Reviewed once per version.
40const TRAILER_FORBIDDEN: &[&str] = &[
41 "content-length",
42 "transfer-encoding",
43 "host",
44 "connection",
45 "keep-alive",
46 "te",
47 "trailer",
48 "upgrade",
49 "proxy-connection",
50 "expect",
51 "max-forwards",
52 "range",
53 "if-match",
54 "if-none-match",
55 "if-modified-since",
56 "if-unmodified-since",
57 "if-range",
58 "authorization",
59 "proxy-authorization",
60 "www-authenticate",
61 "proxy-authenticate",
62 "cookie",
63 "set-cookie",
64 "content-type",
65 "content-encoding",
66 "content-range",
67 "cache-control",
68 "expires",
69 "date",
70 "location",
71 "retry-after",
72 "vary",
73 "age",
74];
75
76/// Validates outgoing trailer fields (all of them, before anything is
77/// written), then appends the last chunk and the trailer section:
78/// `0\r\n`, the fields, and the blank line.
79pub(crate) fn push_last_chunk_with_trailers<O: Output + ?Sized>(
80 out: &mut O,
81 trailers: &[(&str, &[u8])],
82) -> Result<(), HttpError> {
83 check_trailers(trailers)?;
84 out.put(b"0\r\n");
85 for &(name, value) in trailers {
86 write_field(out, name, value);
87 }
88 out.put(b"\r\n");
89 Ok(())
90}
91
92/// Checks the protocol of a `101`: a token or a `name/version` product
93/// token, never `h2c` (RFC 9113 section 3.1).
94pub(crate) fn check_upgrade_protocol(protocol: &[u8]) -> Result<(), HttpError> {
95 if !is_protocol(protocol) {
96 Err(HttpError::InvalidHeaderValue)
97 } else if is_h2c(protocol) {
98 Err(HttpError::UpgradeNotOffered)
99 } else {
100 Ok(())
101 }
102}
103
104/// Checks one outgoing response field with the rules of
105/// [`Response::header`]; returns whether it is the `date` field.
106pub(crate) fn check_response_field(name: &str, value: &[u8]) -> Result<bool, HttpError> {
107 check_field(name, value, RESPONSE_RESERVED)?;
108 Ok(name.eq_ignore_ascii_case("date"))
109}
110
111/// Validates outgoing trailer fields without writing them. Also used for a
112/// body whose trailers are dropped (HTTP/1.0 close-delimited, `HEAD`), so a
113/// call fails the same way whatever framing the peer forced.
114pub(crate) fn check_trailers(trailers: &[(&str, &[u8])]) -> Result<(), HttpError> {
115 for &(name, value) in trailers {
116 if TRAILER_FORBIDDEN
117 .iter()
118 .any(|f| f.eq_ignore_ascii_case(name))
119 {
120 return Err(HttpError::TrailerNotAllowed);
121 }
122 check_field(name, value, &[])?;
123 }
124 Ok(())
125}
126
127/// Checks one outgoing field: a token name that is not `reserved`, and a
128/// value without control bytes or surrounding whitespace.
129fn check_field(name: &str, value: &[u8], reserved: &[&str]) -> Result<(), HttpError> {
130 if !is_token(name.as_bytes()) {
131 return Err(HttpError::InvalidHeaderName);
132 }
133 if reserved.iter().any(|r| r.eq_ignore_ascii_case(name)) {
134 return Err(HttpError::ReservedHeader);
135 }
136 if trim_ows(value).len() != value.len() {
137 // Surrounding whitespace would be stripped by the recipient; refusing
138 // it keeps what is sent equal to what is received.
139 return Err(HttpError::InvalidHeaderValue);
140 }
141 check_field_value(value)
142}
143
144pub(crate) fn write_field<O: Output + ?Sized>(out: &mut O, name: &str, value: &[u8]) {
145 out.put(name.as_bytes());
146 out.put(b": ");
147 out.put(value);
148 out.put(b"\r\n");
149}
150
151/// Validates a field and appends `name: value\r\n`.
152fn push_field(
153 fields: &mut Vec<u8>,
154 name: &str,
155 value: &[u8],
156 reserved: &[&str],
157) -> Result<(), HttpError> {
158 check_field(name, value, reserved)?;
159 write_field(fields, name, value);
160 Ok(())
161}
162
163/// Fields the connection owns: framing, connection management, and the
164/// hop-by-hop fields of RFC 9110 section 7.6.1. A response also may not set
165/// `te`, which only a request can carry (section 10.1.4).
166const RESPONSE_RESERVED: &[&str] = &[
167 "content-length",
168 "transfer-encoding",
169 "connection",
170 "upgrade",
171 "trailer",
172 "keep-alive",
173 "proxy-connection",
174 "te",
175];
176const REQUEST_RESERVED: &[&str] = &[
177 "content-length",
178 "transfer-encoding",
179 "connection",
180 "upgrade",
181 "trailer",
182 "keep-alive",
183 "proxy-connection",
184];
185
186/// A response for a [`ServerConn`](crate::ServerConn) to send.
187///
188/// The status line, `content-length` / `transfer-encoding`, and
189/// `connection` are written by the connection, which knows the request's
190/// method and version: a `HEAD` request gets the headers without the body,
191/// an HTTP/1.0 client never gets chunked encoding, and `connection: close`
192/// is added whenever the connection will close.
193///
194/// # Examples
195///
196/// ```
197/// use http_net::Response;
198///
199/// let ok = Response::text(200, "hello");
200/// assert_eq!(ok.status(), 200);
201///
202/// let asset = Response::new(200)
203/// .header("content-type", "text/css")
204/// .header("cache-control", "max-age=31536000, immutable")
205/// .body(&b"body { margin: 0 }"[..]);
206/// assert_eq!(asset.header_value("content-type"), Some(&b"text/css"[..]));
207/// ```
208#[derive(Clone, PartialEq, Eq)]
209pub struct Response {
210 status: u16,
211 fields: Vec<u8>,
212 pub(crate) body: OutBody,
213 pub(crate) close: bool,
214 pub(crate) upgrade: bool,
215 pub(crate) has_date: bool,
216 error: Option<HttpError>,
217}
218
219impl Response {
220 /// A response with this status, no extra headers, and an empty body.
221 ///
222 /// The status is validated when the response is written (`100..=599`,
223 /// and only `101` among the 1xx codes).
224 ///
225 /// # Examples
226 ///
227 /// ```
228 /// let r = http_net::Response::new(204);
229 /// assert_eq!(r.status(), 204);
230 /// ```
231 #[must_use]
232 pub fn new(status: u16) -> Self {
233 Self {
234 status,
235 fields: Vec::new(),
236 body: OutBody::Full(Cow::Borrowed(&[])),
237 close: false,
238 upgrade: false,
239 has_date: false,
240 error: None,
241 }
242 }
243
244 /// A `text/plain; charset=utf-8` response with `text` as its body.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// let r = http_net::Response::text(404, "no such page");
250 /// assert_eq!(r.body_bytes(), Some(&b"no such page"[..]));
251 /// ```
252 #[must_use]
253 pub fn text(status: u16, text: &str) -> Self {
254 Self::new(status)
255 .header("content-type", "text/plain; charset=utf-8")
256 .body(text.as_bytes().to_vec())
257 }
258
259 /// The response a server sends after [`ServerConn::poll`](crate::ServerConn::poll)
260 /// returned a parse error: the status from [`HttpError::status`] (400
261 /// when it has none), a short `text/plain` body with the error's
262 /// one-line description, and [`close`](Self::close). The text is static
263 /// and never includes the bytes that were refused.
264 ///
265 /// # Examples
266 ///
267 /// ```
268 /// use http_net::{HttpError, Response, ServerConn};
269 ///
270 /// let r = Response::from_error(&HttpError::HeadersTooLarge);
271 /// assert_eq!(r.status(), 431);
272 /// assert!(r.closes());
273 ///
274 /// let mut conn = ServerConn::new();
275 /// let _ = conn.feed(b"GET / HTTP/1.1\r\n\r\n");
276 /// let err = conn.poll().unwrap_err();
277 /// let mut out = Vec::new();
278 /// conn.respond(&Response::from_error(&err), &mut out).unwrap();
279 /// assert!(out.starts_with(b"HTTP/1.1 400 Bad Request\r\n"));
280 /// ```
281 #[must_use]
282 pub fn from_error(error: &HttpError) -> Self {
283 Self::new(error.status().unwrap_or(400))
284 .header("content-type", "text/plain; charset=utf-8")
285 .body(format!("{error}").into_bytes())
286 .close()
287 }
288
289 /// A `101 Switching Protocols` response handing the connection to
290 /// `protocol` (for example `websocket`, or a `name/version` product
291 /// token). The connection writes `connection: upgrade` and
292 /// `upgrade: <protocol>`; add any protocol-specific headers (such as
293 /// `sec-websocket-accept`) with [`header`](Self::header).
294 ///
295 /// The protocol must be one the request offered (RFC 9110 section 7.8),
296 /// compared ASCII case-insensitively; a name without a version matches
297 /// an offer of that name with any version. Otherwise, and always for
298 /// `h2c` (RFC 9113 section 3.1), writing it fails with
299 /// [`HttpError::UpgradeNotOffered`]. Writing it fails with
300 /// [`HttpError::InvalidState`] when the request is not a complete
301 /// upgrade request ([`RequestHead::is_upgrade`](crate::RequestHead::is_upgrade)
302 /// false, or its body not yet read), and with
303 /// [`HttpError::InvalidHeaderValue`] when `protocol` is not a token.
304 ///
305 /// # Examples
306 ///
307 /// ```
308 /// let r = http_net::Response::switching_protocols("websocket")
309 /// .header("sec-websocket-accept", "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
310 /// assert_eq!(r.status(), 101);
311 /// assert_eq!(r.header_value("upgrade"), Some(&b"websocket"[..]));
312 /// ```
313 #[must_use]
314 pub fn switching_protocols(protocol: &str) -> Self {
315 let mut r = Self::new(101);
316 r.upgrade = true;
317 if let Err(e) = check_upgrade_protocol(protocol.as_bytes()) {
318 r.error = Some(e);
319 return r;
320 }
321 r.fields
322 .extend_from_slice(b"connection: upgrade\r\nupgrade: ");
323 r.fields.extend_from_slice(protocol.as_bytes());
324 r.fields.extend_from_slice(b"\r\n");
325 r
326 }
327
328 /// Adds a header field. The name must be a token and the value may not
329 /// contain control characters other than tab, nor leading or trailing
330 /// whitespace. The framing and hop-by-hop fields (`content-length`,
331 /// `transfer-encoding`, `connection`, `upgrade`, `trailer`, `keep-alive`,
332 /// `proxy-connection`, and `te`) are refused with
333 /// [`HttpError::ReservedHeader`]; the first problem is reported when the
334 /// response is written.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use http_net::{HttpError, Response, ServerConn};
340 ///
341 /// let bad = Response::new(200).header("content-length", "5");
342 /// let mut conn = ServerConn::new();
343 /// let _ = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\n\r\n");
344 /// let _ = conn.poll();
345 /// assert_eq!(conn.respond(&bad, &mut Vec::new()), Err(HttpError::ReservedHeader));
346 /// ```
347 #[must_use]
348 pub fn header(mut self, name: &str, value: impl AsRef<[u8]>) -> Self {
349 if self.error.is_none() {
350 let value = value.as_ref();
351 if let Err(e) = push_field(&mut self.fields, name, value, RESPONSE_RESERVED) {
352 self.error = Some(e);
353 } else if name.eq_ignore_ascii_case("date") {
354 self.has_date = true;
355 }
356 }
357 self
358 }
359
360 /// Sets the whole body; it is sent with `content-length`. Static data
361 /// (an embedded asset) is borrowed rather than copied.
362 ///
363 /// # Examples
364 ///
365 /// ```
366 /// static PAGE: &[u8] = b"<!doctype html><title>x</title>";
367 /// let r = http_net::Response::new(200).body(PAGE);
368 /// assert_eq!(r.body_bytes(), Some(PAGE));
369 /// ```
370 #[must_use]
371 pub fn body(mut self, body: impl Into<Cow<'static, [u8]>>) -> Self {
372 self.body = OutBody::Full(body.into());
373 self
374 }
375
376 /// Streams the body with chunked encoding: after
377 /// [`ServerConn::respond`](crate::ServerConn::respond), send data with
378 /// [`ServerConn::send_body`](crate::ServerConn::send_body) and end it
379 /// with [`ServerConn::end_body`](crate::ServerConn::end_body). For an
380 /// HTTP/1.0 client the connection falls back to closing the connection
381 /// to end the body.
382 ///
383 /// # Examples
384 ///
385 /// ```
386 /// let r = http_net::Response::new(200).chunked();
387 /// assert_eq!(r.body_bytes(), None);
388 /// ```
389 #[must_use]
390 pub fn chunked(mut self) -> Self {
391 self.body = OutBody::Chunked;
392 self
393 }
394
395 /// Streams a body of exactly `len` bytes, sent with `content-length`;
396 /// sending more or fewer is [`HttpError::BodyLengthMismatch`].
397 ///
398 /// # Examples
399 ///
400 /// ```
401 /// let r = http_net::Response::new(200).content_length(1 << 20);
402 /// assert_eq!(r.body_bytes(), None);
403 /// ```
404 #[must_use]
405 pub fn content_length(mut self, len: u64) -> Self {
406 self.body = OutBody::Length(len);
407 self
408 }
409
410 /// Closes the connection after this response.
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// let r = http_net::Response::new(503).close();
416 /// assert!(r.closes());
417 /// ```
418 #[must_use]
419 pub fn close(mut self) -> Self {
420 self.close = true;
421 self
422 }
423
424 /// Resets the response to `Response::new(status)` while keeping the
425 /// allocation of its field storage, so one `Response` per connection
426 /// can be reused without allocating for every request. An owned body is
427 /// dropped.
428 ///
429 /// # Examples
430 ///
431 /// ```
432 /// use http_net::Response;
433 ///
434 /// let mut r = Response::new(200).header("x-request", "1").close();
435 /// r.clear(204);
436 /// assert_eq!(r.status(), 204);
437 /// assert_eq!(r.header_value("x-request"), None);
438 /// assert!(!r.closes());
439 /// r = r.header("x-request", "2"); // reuses the field storage
440 /// assert_eq!(r.header_value("x-request"), Some(&b"2"[..]));
441 /// ```
442 pub fn clear(&mut self, status: u16) {
443 self.status = status;
444 self.fields.clear();
445 self.body = OutBody::Full(Cow::Borrowed(&[]));
446 self.close = false;
447 self.upgrade = false;
448 self.has_date = false;
449 self.error = None;
450 }
451
452 /// The status code.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// assert_eq!(http_net::Response::new(418).status(), 418);
458 /// ```
459 #[must_use]
460 pub fn status(&self) -> u16 {
461 self.status
462 }
463
464 /// Whether [`close`](Self::close) was requested.
465 ///
466 /// # Examples
467 ///
468 /// ```
469 /// assert!(!http_net::Response::new(200).closes());
470 /// ```
471 #[must_use]
472 pub fn closes(&self) -> bool {
473 self.close
474 }
475
476 /// The full body, or `None` for a streamed one.
477 ///
478 /// # Examples
479 ///
480 /// ```
481 /// assert_eq!(http_net::Response::new(200).body_bytes(), Some(&[][..]));
482 /// ```
483 #[must_use]
484 pub fn body_bytes(&self) -> Option<&[u8]> {
485 match &self.body {
486 OutBody::Full(b) => Some(b),
487 _ => None,
488 }
489 }
490
491 /// The value of the first header named `name` added to this response
492 /// (ASCII case-insensitive), including the `upgrade` of
493 /// [`switching_protocols`](Self::switching_protocols).
494 ///
495 /// # Examples
496 ///
497 /// ```
498 /// let r = http_net::Response::new(200).header("x-id", "7");
499 /// assert_eq!(r.header_value("X-ID"), Some(&b"7"[..]));
500 /// ```
501 #[must_use]
502 pub fn header_value(&self, name: &str) -> Option<&[u8]> {
503 field_value(&self.fields, name)
504 }
505
506 pub(crate) fn error(&self) -> Option<HttpError> {
507 self.error
508 }
509
510 pub(crate) fn fields(&self) -> &[u8] {
511 &self.fields
512 }
513
514 /// The protocol a `101` built with
515 /// [`switching_protocols`](Self::switching_protocols) switches to.
516 pub(crate) fn upgrade_protocol(&self) -> Option<&[u8]> {
517 if self.upgrade {
518 self.header_value("upgrade")
519 } else {
520 None
521 }
522 }
523}
524
525/// Shows status, fields, body size, and flags; the values of credential
526/// fields (`set-cookie` above all) are replaced by `<redacted N bytes>`.
527impl fmt::Debug for Response {
528 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529 f.debug_struct("Response")
530 .field("status", &self.status)
531 .field("fields", &SerializedFields(&self.fields))
532 .field("body", &body_debug(&self.body))
533 .field("close", &self.close)
534 .field("error", &self.error)
535 .finish()
536 }
537}
538
539/// A request for a [`ClientConn`](crate::ClientConn) to send.
540///
541/// HTTP/1.1 requires a `Host` field; the connection refuses to send a
542/// request without one. The request line always says HTTP/1.1.
543///
544/// # Examples
545///
546/// ```
547/// use http_net::Request;
548///
549/// let get = Request::get("/index.html").header("host", "example.com");
550/// let post = Request::post("/api")
551/// .header("host", "example.com")
552/// .header("content-type", "application/json")
553/// .body(br#"{"ok":true}"#.to_vec());
554/// assert_eq!(get.method(), "GET");
555/// assert_eq!(post.target(), "/api");
556/// ```
557#[derive(Clone, PartialEq, Eq)]
558pub struct Request {
559 method: Cow<'static, str>,
560 pub(crate) method_kind: Method,
561 target: String,
562 fields: Vec<u8>,
563 pub(crate) body: OutBody,
564 pub(crate) close: bool,
565 pub(crate) upgrade: bool,
566 pub(crate) has_host: bool,
567 pub(crate) expect_continue: bool,
568 error: Option<HttpError>,
569}
570
571impl Request {
572 /// A request with `method` and `target`, validated when it is sent:
573 /// the method must be a token and the target must be in a form the
574 /// method allows (`/path?query`, an absolute URI, `host:port` for
575 /// `CONNECT`, or `*` for `OPTIONS`).
576 ///
577 /// # Examples
578 ///
579 /// ```
580 /// let r = http_net::Request::new("PURGE", "/cache/a");
581 /// assert_eq!(r.method(), "PURGE");
582 /// ```
583 #[must_use]
584 pub fn new(method: &str, target: &str) -> Self {
585 let method_kind = Method::from_bytes(method.as_bytes());
586 let mut error = None;
587 if !is_token(method.as_bytes()) {
588 error = Some(HttpError::InvalidMethod);
589 } else if let Err(e) = check_target(method_kind, target.as_bytes()) {
590 error = Some(e);
591 }
592 Self {
593 method: match method_kind.as_str() {
594 Some(s) => Cow::Borrowed(s),
595 None => Cow::Owned(method.into()),
596 },
597 method_kind,
598 target: target.into(),
599 fields: Vec::new(),
600 body: OutBody::Full(Cow::Borrowed(&[])),
601 close: false,
602 upgrade: false,
603 has_host: false,
604 expect_continue: false,
605 error,
606 }
607 }
608
609 /// A `GET` request.
610 ///
611 /// # Examples
612 ///
613 /// ```
614 /// assert_eq!(http_net::Request::get("/").method(), "GET");
615 /// ```
616 #[must_use]
617 pub fn get(target: &str) -> Self {
618 Self::new("GET", target)
619 }
620
621 /// A `POST` request.
622 ///
623 /// # Examples
624 ///
625 /// ```
626 /// assert_eq!(http_net::Request::post("/").method(), "POST");
627 /// ```
628 #[must_use]
629 pub fn post(target: &str) -> Self {
630 Self::new("POST", target)
631 }
632
633 /// A `HEAD` request: its response carries headers and no body.
634 ///
635 /// # Examples
636 ///
637 /// ```
638 /// assert_eq!(http_net::Request::head("/").method(), "HEAD");
639 /// ```
640 #[must_use]
641 pub fn head(target: &str) -> Self {
642 Self::new("HEAD", target)
643 }
644
645 /// A `PUT` request.
646 ///
647 /// # Examples
648 ///
649 /// ```
650 /// assert_eq!(http_net::Request::put("/files/a").method(), "PUT");
651 /// ```
652 #[must_use]
653 pub fn put(target: &str) -> Self {
654 Self::new("PUT", target)
655 }
656
657 /// A `DELETE` request.
658 ///
659 /// # Examples
660 ///
661 /// ```
662 /// assert_eq!(http_net::Request::delete("/files/a").method(), "DELETE");
663 /// ```
664 #[must_use]
665 pub fn delete(target: &str) -> Self {
666 Self::new("DELETE", target)
667 }
668
669 /// An `OPTIONS` request; `*` asks about the server as a whole.
670 ///
671 /// # Examples
672 ///
673 /// ```
674 /// assert_eq!(http_net::Request::options("*").target(), "*");
675 /// ```
676 #[must_use]
677 pub fn options(target: &str) -> Self {
678 Self::new("OPTIONS", target)
679 }
680
681 /// A request for an upstream server built from a received head, for a
682 /// proxy: the same method and target, every field except the hop-by-hop
683 /// ones (RFC 9110 section 7.6.1: `connection`, `keep-alive`,
684 /// `proxy-connection`, `te`, `transfer-encoding`, `upgrade`, `trailer`,
685 /// and any name the head's `Connection` lists; see
686 /// [`is_hop_by_hop`](crate::is_hop_by_hop)) in their original order,
687 /// except `content-length`, which the connection derives again from
688 /// the body mode of the head's framing: a chunked body stays
689 /// chunked, a length stays that length (stream it with
690 /// [`ClientConn::send_body`](crate::ClientConn::send_body)). The
691 /// connection writes its own framing and connection fields.
692 ///
693 /// The target is copied as received: an absolute-form target (a request
694 /// to a proxy) stays absolute, which an origin server also accepts (RFC
695 /// 9112 section 3.2.2); rewrite it with [`Request::new`] if the upstream
696 /// wants origin form. `Host` is forwarded as a field. Add `via` and
697 /// forwarding fields with [`header`](Self::header); requests are
698 /// re-serialized, never passed through as raw bytes.
699 ///
700 /// # Errors
701 ///
702 /// Recorded and returned by
703 /// [`ClientConn::send_request`](crate::ClientConn::send_request):
704 /// [`HttpError::InvalidState`] for an upgrade request (the upgrade is
705 /// hop-by-hop; a proxy tunnels it instead), and the builder errors of
706 /// [`Request::new`] and [`Request::header`] (for example a missing or
707 /// second `host` surfaces at send).
708 ///
709 /// # Examples
710 ///
711 /// ```
712 /// use http_net::{ClientConn, Request, ServerConn, ServerEvent};
713 ///
714 /// let mut downstream = ServerConn::new();
715 /// let _ = downstream.feed(b"POST /api HTTP/1.1\r\nHost: app\r\nConnection: X-Hop\r\nX-Hop: 1\r\nKeep-Alive: timeout=5\r\nAccept: */*\r\nContent-Length: 2\r\n\r\nhi");
716 /// let ServerEvent::Request(head) = downstream.poll()? else { unreachable!() };
717 /// let upstream_req = Request::forward_from(&head).header("via", "1.1 proxy");
718 ///
719 /// let mut upstream = ClientConn::new();
720 /// let mut out = Vec::new();
721 /// upstream.send_request(&upstream_req, &mut out)?;
722 /// assert_eq!(out, b"POST /api HTTP/1.1\r\nHost: app\r\nAccept: */*\r\nvia: 1.1 proxy\r\ncontent-length: 2\r\n\r\n");
723 /// # Ok::<(), http_net::HttpError>(())
724 /// ```
725 #[must_use]
726 pub fn forward_from(head: &RequestHead<'_>) -> Self {
727 let mut request = Self::new(head.method_str(), head.target());
728 if head.is_upgrade() {
729 if request.error.is_none() {
730 request.error = Some(HttpError::InvalidState(
731 "an upgrade request is hop-by-hop; tunnel it instead of forwarding it",
732 ));
733 }
734 return request;
735 }
736 for (name, value) in head.headers() {
737 // `content-length` is end-to-end, but the connection derives it
738 // from the body mode below, so it is not copied as a field.
739 if !is_hop_by_hop(name, head.connection_options())
740 && !name.eq_ignore_ascii_case("content-length")
741 {
742 request = request.header(name, value);
743 }
744 }
745 match head.framing() {
746 BodyFraming::Chunked => request.chunked(),
747 BodyFraming::Length(n) => request.content_length(n),
748 _ => request,
749 }
750 }
751
752 /// Adds a header field, validated as for [`Response::header`], except
753 /// that `te` is allowed on a request. A second `host`, or a `host` value
754 /// that is not `host[:port]`, is refused with [`HttpError::InvalidHost`].
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// let r = http_net::Request::get("/").header("host", "a").header("accept", "*/*");
760 /// assert_eq!(r.header_value("accept"), Some(&b"*/*"[..]));
761 /// ```
762 #[must_use]
763 pub fn header(mut self, name: &str, value: impl AsRef<[u8]>) -> Self {
764 if self.error.is_none() {
765 let value = value.as_ref();
766 let is_host = name.eq_ignore_ascii_case("host");
767 if is_host && (self.has_host || !crate::scan::is_host_value(value)) {
768 self.error = Some(HttpError::InvalidHost);
769 } else if let Err(e) = push_field(&mut self.fields, name, value, REQUEST_RESERVED) {
770 self.error = Some(e);
771 } else {
772 self.has_host |= is_host;
773 }
774 }
775 self
776 }
777
778 /// Sets the whole body, sent with `content-length`.
779 ///
780 /// # Examples
781 ///
782 /// ```
783 /// let r = http_net::Request::post("/").body(&b"x=1"[..]);
784 /// assert_eq!(r.body_bytes(), Some(&b"x=1"[..]));
785 /// ```
786 #[must_use]
787 pub fn body(mut self, body: impl Into<Cow<'static, [u8]>>) -> Self {
788 self.body = OutBody::Full(body.into());
789 self
790 }
791
792 /// Streams the body with chunked encoding through
793 /// [`ClientConn::send_body`](crate::ClientConn::send_body) and
794 /// [`ClientConn::end_body`](crate::ClientConn::end_body).
795 ///
796 /// # Examples
797 ///
798 /// ```
799 /// assert_eq!(http_net::Request::post("/").chunked().body_bytes(), None);
800 /// ```
801 #[must_use]
802 pub fn chunked(mut self) -> Self {
803 self.body = OutBody::Chunked;
804 self
805 }
806
807 /// Streams a body of exactly `len` bytes.
808 ///
809 /// # Examples
810 ///
811 /// ```
812 /// assert_eq!(http_net::Request::post("/").content_length(4).body_bytes(), None);
813 /// ```
814 #[must_use]
815 pub fn content_length(mut self, len: u64) -> Self {
816 self.body = OutBody::Length(len);
817 self
818 }
819
820 /// Asks the server to close the connection after its response.
821 ///
822 /// # Examples
823 ///
824 /// ```
825 /// let _ = http_net::Request::get("/").header("host", "a").close();
826 /// ```
827 #[must_use]
828 pub fn close(mut self) -> Self {
829 self.close = true;
830 self
831 }
832
833 /// Sends `expect: 100-continue` and holds the body back until the
834 /// server agrees (RFC 9110 section 10.1.1): for large uploads the
835 /// server may refuse from the head alone. The body must be streamed
836 /// ([`content_length`](Self::content_length) or
837 /// [`chunked`](Self::chunked)); send it with
838 /// [`ClientConn::send_body`](crate::ClientConn::send_body) after
839 /// [`ClientEvent::Continue`](crate::ClientEvent::Continue), or after a
840 /// wait of your choosing. A final status instead means the server does
841 /// not want the body: it must not be sent, and the connection closes
842 /// after the response.
843 ///
844 /// # Examples
845 ///
846 /// ```
847 /// use http_net::{ClientConn, ClientEvent, HttpError, Request};
848 ///
849 /// let mut conn = ClientConn::new();
850 /// let mut out = Vec::new();
851 /// let upload = Request::put("/f").header("host", "a").content_length(9).expect_continue();
852 /// conn.send_request(&upload, &mut out)?;
853 /// assert!(out.ends_with(b"expect: 100-continue\r\ncontent-length: 9\r\n\r\n"));
854 /// let _ = conn.feed(b"HTTP/1.1 413 Content Too Large\r\nContent-Length: 0\r\n\r\n");
855 /// assert!(matches!(conn.poll()?, ClientEvent::Response(r) if r.status() == 413));
856 /// assert!(matches!(conn.send_body(b"too large", &mut out), Err(HttpError::InvalidState(_))));
857 /// assert!(matches!(conn.poll()?, ClientEvent::ResponseEnd));
858 /// assert!(matches!(conn.poll()?, ClientEvent::Closed));
859 /// # Ok::<(), http_net::HttpError>(())
860 /// ```
861 #[must_use]
862 pub fn expect_continue(mut self) -> Self {
863 if self.error.is_none() && !self.expect_continue {
864 self.expect_continue = true;
865 self.fields.extend_from_slice(b"expect: 100-continue\r\n");
866 }
867 self
868 }
869
870 /// Asks to switch the connection to `protocol` (writes
871 /// `connection: upgrade` and `upgrade: <protocol>`). A `101` answer
872 /// hands the connection over; see
873 /// [`ClientEvent::Upgraded`](crate::ClientEvent::Upgraded).
874 ///
875 /// `protocol` is a token or a `name/version` product token; anything
876 /// else is refused with [`HttpError::InvalidHeaderValue`]. `h2c` is
877 /// refused with [`HttpError::UpgradeNotOffered`]: RFC 9113 section 3.1
878 /// deprecates the HTTP/2 upgrade.
879 ///
880 /// # Examples
881 ///
882 /// ```
883 /// use http_net::{ClientConn, HttpError, Request};
884 ///
885 /// let r = Request::get("/rpc").header("host", "a").upgrade("websocket");
886 /// assert_eq!(r.header_value("upgrade"), Some(&b"websocket"[..]));
887 ///
888 /// let h2c = Request::get("/").header("host", "a").upgrade("h2c");
889 /// assert_eq!(
890 /// ClientConn::new().send_request(&h2c, &mut Vec::new()),
891 /// Err(HttpError::UpgradeNotOffered)
892 /// );
893 /// ```
894 #[must_use]
895 pub fn upgrade(mut self, protocol: &str) -> Self {
896 if self.error.is_none() {
897 if is_h2c(protocol.as_bytes()) {
898 self.error = Some(HttpError::UpgradeNotOffered);
899 } else if is_protocol(protocol.as_bytes()) {
900 self.upgrade = true;
901 self.fields
902 .extend_from_slice(b"connection: upgrade\r\nupgrade: ");
903 self.fields.extend_from_slice(protocol.as_bytes());
904 self.fields.extend_from_slice(b"\r\n");
905 } else {
906 self.error = Some(HttpError::InvalidHeaderValue);
907 }
908 }
909 self
910 }
911
912 /// The method text.
913 ///
914 /// # Examples
915 ///
916 /// ```
917 /// assert_eq!(http_net::Request::new("OPTIONS", "*").method(), "OPTIONS");
918 /// ```
919 #[must_use]
920 pub fn method(&self) -> &str {
921 &self.method
922 }
923
924 /// The request target.
925 ///
926 /// # Examples
927 ///
928 /// ```
929 /// assert_eq!(http_net::Request::get("/a?b").target(), "/a?b");
930 /// ```
931 #[must_use]
932 pub fn target(&self) -> &str {
933 &self.target
934 }
935
936 /// The full body, or `None` for a streamed one.
937 ///
938 /// # Examples
939 ///
940 /// ```
941 /// assert_eq!(http_net::Request::get("/").body_bytes(), Some(&[][..]));
942 /// ```
943 #[must_use]
944 pub fn body_bytes(&self) -> Option<&[u8]> {
945 match &self.body {
946 OutBody::Full(b) => Some(b),
947 _ => None,
948 }
949 }
950
951 /// The value of the first header named `name` added to this request.
952 ///
953 /// # Examples
954 ///
955 /// ```
956 /// let r = http_net::Request::get("/").header("host", "a");
957 /// assert_eq!(r.header_value("HOST"), Some(&b"a"[..]));
958 /// ```
959 #[must_use]
960 pub fn header_value(&self, name: &str) -> Option<&[u8]> {
961 field_value(&self.fields, name)
962 }
963
964 pub(crate) fn error(&self) -> Option<HttpError> {
965 self.error
966 }
967
968 pub(crate) fn fields(&self) -> &[u8] {
969 &self.fields
970 }
971
972 /// The values of the `upgrade` fields [`upgrade`](Self::upgrade) added
973 /// (`header` refuses the name, so these are the only ones).
974 pub(crate) fn upgrade_offers(&self) -> impl Iterator<Item = &[u8]> {
975 serialized_fields(&self.fields)
976 .filter(|(n, _)| n.eq_ignore_ascii_case(b"upgrade"))
977 .map(|(_, v)| v)
978 }
979}
980
981/// Shows method, target, fields, and body size; the values of credential
982/// fields (`authorization`, `proxy-authorization`, `cookie`) are replaced by
983/// `<redacted N bytes>`.
984impl fmt::Debug for Request {
985 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
986 f.debug_struct("Request")
987 .field("method", &self.method)
988 .field("target", &self.target)
989 .field("fields", &SerializedFields(&self.fields))
990 .field("body", &body_debug(&self.body))
991 .field("error", &self.error)
992 .finish()
993 }
994}
995
996fn body_debug(body: &OutBody) -> String {
997 match body {
998 OutBody::Full(b) => format!("{} bytes", b.len()),
999 OutBody::Length(n) => format!("streamed, {n} bytes"),
1000 OutBody::Chunked => "streamed, chunked".into(),
1001 }
1002}
1003
1004/// Looks a header up in serialized `name: value\r\n` lines.
1005fn field_value<'a>(fields: &'a [u8], name: &str) -> Option<&'a [u8]> {
1006 serialized_fields(fields)
1007 .find(|(n, _)| n.eq_ignore_ascii_case(name.as_bytes()))
1008 .map(|(_, v)| v)
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013 use alloc::string::ToString;
1014
1015 use super::*;
1016
1017 #[test]
1018 fn test_response_refuses_reserved_and_invalid_headers() {
1019 assert_eq!(
1020 Response::new(200)
1021 .header("Transfer-Encoding", "chunked")
1022 .error(),
1023 Some(HttpError::ReservedHeader)
1024 );
1025 assert_eq!(
1026 Response::new(200).header("bad name", "x").error(),
1027 Some(HttpError::InvalidHeaderName)
1028 );
1029 assert_eq!(
1030 Response::new(200).header("x", "a\r\nInjected: 1").error(),
1031 Some(HttpError::BareCr)
1032 );
1033 assert_eq!(
1034 Response::new(200).header("x", " padded").error(),
1035 Some(HttpError::InvalidHeaderValue)
1036 );
1037 // The first error sticks.
1038 let r = Response::new(200)
1039 .header("a b", "1")
1040 .header("connection", "close");
1041 assert_eq!(r.error(), Some(HttpError::InvalidHeaderName));
1042 }
1043
1044 #[test]
1045 fn test_request_validates_method_target_and_host() {
1046 assert_eq!(
1047 Request::new("G T", "/").error(),
1048 Some(HttpError::InvalidMethod)
1049 );
1050 assert_eq!(
1051 Request::get("no-slash").error(),
1052 Some(HttpError::InvalidTarget)
1053 );
1054 assert_eq!(
1055 Request::get("/")
1056 .header("host", "a")
1057 .header("Host", "b")
1058 .error(),
1059 Some(HttpError::InvalidHost)
1060 );
1061 assert_eq!(
1062 Request::get("/").header("host", "a b").error(),
1063 Some(HttpError::InvalidHost)
1064 );
1065 assert!(Request::get("/").header("host", "a").has_host);
1066 assert_eq!(
1067 Request::get("/").upgrade("a b").error(),
1068 Some(HttpError::InvalidHeaderValue)
1069 );
1070 }
1071
1072 #[test]
1073 fn test_from_error_uses_status_text_and_close() {
1074 let r = Response::from_error(&HttpError::UnsupportedTransferEncoding);
1075 assert_eq!(r.status(), 501);
1076 assert!(r.closes());
1077 assert_eq!(
1078 r.header_value("content-type"),
1079 Some(&b"text/plain; charset=utf-8"[..])
1080 );
1081 assert_eq!(
1082 r.body_bytes(),
1083 Some(
1084 HttpError::UnsupportedTransferEncoding
1085 .to_string()
1086 .as_bytes()
1087 )
1088 );
1089 // Errors without a request status still get a well-formed 400.
1090 assert_eq!(
1091 Response::from_error(&HttpError::UnexpectedEof).status(),
1092 400
1093 );
1094 assert_eq!(
1095 Response::from_error(&HttpError::InvalidState("x")).error(),
1096 None
1097 );
1098 }
1099
1100 #[test]
1101 fn test_request_shortcuts_set_the_method() {
1102 for (r, m) in [
1103 (Request::head("/"), "HEAD"),
1104 (Request::put("/"), "PUT"),
1105 (Request::delete("/"), "DELETE"),
1106 (Request::options("*"), "OPTIONS"),
1107 ] {
1108 assert_eq!(r.method(), m);
1109 assert_eq!(r.error(), None);
1110 }
1111 assert_eq!(Request::put("*").error(), Some(HttpError::InvalidTarget));
1112 assert_eq!(Request::head("/").method_kind, Method::Head);
1113 }
1114
1115 #[test]
1116 fn test_upgrade_builders_accept_product_tokens_and_refuse_h2c() {
1117 let r = Response::switching_protocols("foo/2");
1118 assert_eq!(r.error(), None);
1119 assert_eq!(r.upgrade_protocol(), Some(&b"foo/2"[..]));
1120 assert_eq!(
1121 Response::switching_protocols("h2c").error(),
1122 Some(HttpError::UpgradeNotOffered)
1123 );
1124 assert_eq!(
1125 Response::switching_protocols("H2C").error(),
1126 Some(HttpError::UpgradeNotOffered)
1127 );
1128 assert_eq!(
1129 Response::switching_protocols("foo/").error(),
1130 Some(HttpError::InvalidHeaderValue)
1131 );
1132 assert_eq!(Response::new(200).upgrade_protocol(), None);
1133 assert_eq!(
1134 Request::get("/").upgrade("h2c").error(),
1135 Some(HttpError::UpgradeNotOffered)
1136 );
1137 assert!(Request::get("/").upgrade("websocket/13").upgrade);
1138 }
1139
1140 /// Threat T-35: credential values never reach `Debug` output.
1141 #[test]
1142 fn test_debug_redacts_credential_fields() {
1143 let r = Response::new(200)
1144 .header("Set-Cookie", "sid=s3cr3t; HttpOnly")
1145 .header("x-trace", "visible");
1146 let shown = alloc::format!("{r:?}");
1147 assert!(!shown.contains("s3cr3t"), "{shown}");
1148 assert!(shown.contains("<redacted 20 bytes>"), "{shown}");
1149 assert!(shown.contains("visible"), "{shown}");
1150 assert_eq!(
1151 r.header_value("set-cookie"),
1152 Some(&b"sid=s3cr3t; HttpOnly"[..])
1153 );
1154
1155 let q = Request::get("/")
1156 .header("host", "a")
1157 .header("Authorization", "Bearer t0k3n")
1158 .header("PROXY-AUTHORIZATION", "Basic cDpx")
1159 .header("cookie", "a=b");
1160 let shown = alloc::format!("{q:?}");
1161 for secret in ["t0k3n", "cDpx", "a=b"] {
1162 assert!(!shown.contains(secret), "{shown}");
1163 }
1164 assert!(shown.contains("\"host\", \"a\""), "{shown}");
1165 }
1166
1167 #[test]
1168 fn test_field_lookup_and_debug() {
1169 let r = Response::switching_protocols("websocket").header("x", "");
1170 assert_eq!(r.header_value("connection"), Some(&b"upgrade"[..]));
1171 assert_eq!(r.header_value("x"), Some(&b""[..]));
1172 assert!(alloc::format!("{r:?}").contains("Response"));
1173 assert_eq!(
1174 Response::switching_protocols("a b").error(),
1175 Some(HttpError::InvalidHeaderValue)
1176 );
1177 }
1178}