Skip to main content

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    /// Every name the client lists in `Connection` is dropped, as RFC 9110
701    /// section 7.6.1 requires, including end-to-end names such as
702    /// `authorization` or `x-forwarded-for`: a client can strip fields a
703    /// proxy relies on this way. Check
704    /// [`connection_options`](crate::RequestHead::connection_options)
705    /// first if the next hop must see one of them. Listing `host` drops it
706    /// too, and the request then fails closed at send (no `Host`).
707    ///
708    /// # Errors
709    ///
710    /// Recorded and returned by
711    /// [`ClientConn::send_request`](crate::ClientConn::send_request):
712    /// [`HttpError::InvalidState`] for an upgrade request (the upgrade is
713    /// hop-by-hop; a proxy tunnels it instead), and the builder errors of
714    /// [`Request::new`] and [`Request::header`] (for example a missing or
715    /// second `host` surfaces at send).
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use http_net::{ClientConn, Request, ServerConn, ServerEvent};
721    ///
722    /// let mut downstream = ServerConn::new();
723    /// 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");
724    /// let ServerEvent::Request(head) = downstream.poll()? else { unreachable!() };
725    /// let upstream_req = Request::forward_from(&head).header("via", "1.1 proxy");
726    ///
727    /// let mut upstream = ClientConn::new();
728    /// let mut out = Vec::new();
729    /// upstream.send_request(&upstream_req, &mut out)?;
730    /// 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");
731    /// # Ok::<(), http_net::HttpError>(())
732    /// ```
733    #[must_use]
734    pub fn forward_from(head: &RequestHead<'_>) -> Self {
735        let mut request = Self::new(head.method_str(), head.target());
736        if head.is_upgrade() {
737            if request.error.is_none() {
738                request.error = Some(HttpError::InvalidState(
739                    "an upgrade request is hop-by-hop; tunnel it instead of forwarding it",
740                ));
741            }
742            return request;
743        }
744        for (name, value) in head.headers() {
745            // `content-length` is end-to-end, but the connection derives it
746            // from the body mode below, so it is not copied as a field.
747            if !is_hop_by_hop(name, head.connection_options())
748                && !name.eq_ignore_ascii_case("content-length")
749            {
750                request = request.header(name, value);
751            }
752        }
753        match head.framing() {
754            BodyFraming::Chunked => request.chunked(),
755            BodyFraming::Length(n) => request.content_length(n),
756            _ => request,
757        }
758    }
759
760    /// Adds a header field, validated as for [`Response::header`], except
761    /// that `te` is allowed on a request. A second `host`, or a `host` value
762    /// that is not `host[:port]`, is refused with [`HttpError::InvalidHost`].
763    ///
764    /// # Examples
765    ///
766    /// ```
767    /// let r = http_net::Request::get("/").header("host", "a").header("accept", "*/*");
768    /// assert_eq!(r.header_value("accept"), Some(&b"*/*"[..]));
769    /// ```
770    #[must_use]
771    pub fn header(mut self, name: &str, value: impl AsRef<[u8]>) -> Self {
772        if self.error.is_none() {
773            let value = value.as_ref();
774            let is_host = name.eq_ignore_ascii_case("host");
775            if is_host && (self.has_host || !crate::scan::is_host_value(value)) {
776                self.error = Some(HttpError::InvalidHost);
777            } else if let Err(e) = push_field(&mut self.fields, name, value, REQUEST_RESERVED) {
778                self.error = Some(e);
779            } else {
780                self.has_host |= is_host;
781            }
782        }
783        self
784    }
785
786    /// Sets the whole body, sent with `content-length`.
787    ///
788    /// # Examples
789    ///
790    /// ```
791    /// let r = http_net::Request::post("/").body(&b"x=1"[..]);
792    /// assert_eq!(r.body_bytes(), Some(&b"x=1"[..]));
793    /// ```
794    #[must_use]
795    pub fn body(mut self, body: impl Into<Cow<'static, [u8]>>) -> Self {
796        self.body = OutBody::Full(body.into());
797        self
798    }
799
800    /// Streams the body with chunked encoding through
801    /// [`ClientConn::send_body`](crate::ClientConn::send_body) and
802    /// [`ClientConn::end_body`](crate::ClientConn::end_body).
803    ///
804    /// # Examples
805    ///
806    /// ```
807    /// assert_eq!(http_net::Request::post("/").chunked().body_bytes(), None);
808    /// ```
809    #[must_use]
810    pub fn chunked(mut self) -> Self {
811        self.body = OutBody::Chunked;
812        self
813    }
814
815    /// Streams a body of exactly `len` bytes.
816    ///
817    /// # Examples
818    ///
819    /// ```
820    /// assert_eq!(http_net::Request::post("/").content_length(4).body_bytes(), None);
821    /// ```
822    #[must_use]
823    pub fn content_length(mut self, len: u64) -> Self {
824        self.body = OutBody::Length(len);
825        self
826    }
827
828    /// Asks the server to close the connection after its response.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// let _ = http_net::Request::get("/").header("host", "a").close();
834    /// ```
835    #[must_use]
836    pub fn close(mut self) -> Self {
837        self.close = true;
838        self
839    }
840
841    /// Sends `expect: 100-continue` and holds the body back until the
842    /// server agrees (RFC 9110 section 10.1.1): for large uploads the
843    /// server may refuse from the head alone. The body must be streamed
844    /// ([`content_length`](Self::content_length) or
845    /// [`chunked`](Self::chunked)); send it with
846    /// [`ClientConn::send_body`](crate::ClientConn::send_body) after
847    /// [`ClientEvent::Continue`](crate::ClientEvent::Continue), or after a
848    /// wait of your choosing. A final status instead means the server does
849    /// not want the body: it must not be sent, and the connection closes
850    /// after the response.
851    ///
852    /// # Examples
853    ///
854    /// ```
855    /// use http_net::{ClientConn, ClientEvent, HttpError, Request};
856    ///
857    /// let mut conn = ClientConn::new();
858    /// let mut out = Vec::new();
859    /// let upload = Request::put("/f").header("host", "a").content_length(9).expect_continue();
860    /// conn.send_request(&upload, &mut out)?;
861    /// assert!(out.ends_with(b"expect: 100-continue\r\ncontent-length: 9\r\n\r\n"));
862    /// let _ = conn.feed(b"HTTP/1.1 413 Content Too Large\r\nContent-Length: 0\r\n\r\n");
863    /// assert!(matches!(conn.poll()?, ClientEvent::Response(r) if r.status() == 413));
864    /// assert!(matches!(conn.send_body(b"too large", &mut out), Err(HttpError::InvalidState(_))));
865    /// assert!(matches!(conn.poll()?, ClientEvent::ResponseEnd));
866    /// assert!(matches!(conn.poll()?, ClientEvent::Closed));
867    /// # Ok::<(), http_net::HttpError>(())
868    /// ```
869    #[must_use]
870    pub fn expect_continue(mut self) -> Self {
871        if self.error.is_none() && !self.expect_continue {
872            self.expect_continue = true;
873            self.fields.extend_from_slice(b"expect: 100-continue\r\n");
874        }
875        self
876    }
877
878    /// Asks to switch the connection to `protocol` (writes
879    /// `connection: upgrade` and `upgrade: <protocol>`). A `101` answer
880    /// hands the connection over; see
881    /// [`ClientEvent::Upgraded`](crate::ClientEvent::Upgraded).
882    ///
883    /// `protocol` is a token or a `name/version` product token; anything
884    /// else is refused with [`HttpError::InvalidHeaderValue`]. `h2c` is
885    /// refused with [`HttpError::UpgradeNotOffered`]: RFC 9113 section 3.1
886    /// deprecates the HTTP/2 upgrade.
887    ///
888    /// # Examples
889    ///
890    /// ```
891    /// use http_net::{ClientConn, HttpError, Request};
892    ///
893    /// let r = Request::get("/rpc").header("host", "a").upgrade("websocket");
894    /// assert_eq!(r.header_value("upgrade"), Some(&b"websocket"[..]));
895    ///
896    /// let h2c = Request::get("/").header("host", "a").upgrade("h2c");
897    /// assert_eq!(
898    ///     ClientConn::new().send_request(&h2c, &mut Vec::new()),
899    ///     Err(HttpError::UpgradeNotOffered)
900    /// );
901    /// ```
902    #[must_use]
903    pub fn upgrade(mut self, protocol: &str) -> Self {
904        if self.error.is_none() {
905            if is_h2c(protocol.as_bytes()) {
906                self.error = Some(HttpError::UpgradeNotOffered);
907            } else if is_protocol(protocol.as_bytes()) {
908                self.upgrade = true;
909                self.fields
910                    .extend_from_slice(b"connection: upgrade\r\nupgrade: ");
911                self.fields.extend_from_slice(protocol.as_bytes());
912                self.fields.extend_from_slice(b"\r\n");
913            } else {
914                self.error = Some(HttpError::InvalidHeaderValue);
915            }
916        }
917        self
918    }
919
920    /// The method text.
921    ///
922    /// # Examples
923    ///
924    /// ```
925    /// assert_eq!(http_net::Request::new("OPTIONS", "*").method(), "OPTIONS");
926    /// ```
927    #[must_use]
928    pub fn method(&self) -> &str {
929        &self.method
930    }
931
932    /// The request target.
933    ///
934    /// # Examples
935    ///
936    /// ```
937    /// assert_eq!(http_net::Request::get("/a?b").target(), "/a?b");
938    /// ```
939    #[must_use]
940    pub fn target(&self) -> &str {
941        &self.target
942    }
943
944    /// The full body, or `None` for a streamed one.
945    ///
946    /// # Examples
947    ///
948    /// ```
949    /// assert_eq!(http_net::Request::get("/").body_bytes(), Some(&[][..]));
950    /// ```
951    #[must_use]
952    pub fn body_bytes(&self) -> Option<&[u8]> {
953        match &self.body {
954            OutBody::Full(b) => Some(b),
955            _ => None,
956        }
957    }
958
959    /// The value of the first header named `name` added to this request.
960    ///
961    /// # Examples
962    ///
963    /// ```
964    /// let r = http_net::Request::get("/").header("host", "a");
965    /// assert_eq!(r.header_value("HOST"), Some(&b"a"[..]));
966    /// ```
967    #[must_use]
968    pub fn header_value(&self, name: &str) -> Option<&[u8]> {
969        field_value(&self.fields, name)
970    }
971
972    pub(crate) fn error(&self) -> Option<HttpError> {
973        self.error
974    }
975
976    pub(crate) fn fields(&self) -> &[u8] {
977        &self.fields
978    }
979
980    /// The values of the `upgrade` fields [`upgrade`](Self::upgrade) added
981    /// (`header` refuses the name, so these are the only ones).
982    pub(crate) fn upgrade_offers(&self) -> impl Iterator<Item = &[u8]> {
983        serialized_fields(&self.fields)
984            .filter(|(n, _)| n.eq_ignore_ascii_case(b"upgrade"))
985            .map(|(_, v)| v)
986    }
987}
988
989/// Shows method, target, fields, and body size; the values of credential
990/// fields (`authorization`, `proxy-authorization`, `cookie`) are replaced by
991/// `<redacted N bytes>`.
992impl fmt::Debug for Request {
993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
994        f.debug_struct("Request")
995            .field("method", &self.method)
996            .field("target", &self.target)
997            .field("fields", &SerializedFields(&self.fields))
998            .field("body", &body_debug(&self.body))
999            .field("error", &self.error)
1000            .finish()
1001    }
1002}
1003
1004fn body_debug(body: &OutBody) -> String {
1005    match body {
1006        OutBody::Full(b) => format!("{} bytes", b.len()),
1007        OutBody::Length(n) => format!("streamed, {n} bytes"),
1008        OutBody::Chunked => "streamed, chunked".into(),
1009    }
1010}
1011
1012/// Looks a header up in serialized `name: value\r\n` lines.
1013fn field_value<'a>(fields: &'a [u8], name: &str) -> Option<&'a [u8]> {
1014    serialized_fields(fields)
1015        .find(|(n, _)| n.eq_ignore_ascii_case(name.as_bytes()))
1016        .map(|(_, v)| v)
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use alloc::string::ToString;
1022
1023    use super::*;
1024
1025    #[test]
1026    fn test_response_refuses_reserved_and_invalid_headers() {
1027        assert_eq!(
1028            Response::new(200)
1029                .header("Transfer-Encoding", "chunked")
1030                .error(),
1031            Some(HttpError::ReservedHeader)
1032        );
1033        assert_eq!(
1034            Response::new(200).header("bad name", "x").error(),
1035            Some(HttpError::InvalidHeaderName)
1036        );
1037        assert_eq!(
1038            Response::new(200).header("x", "a\r\nInjected: 1").error(),
1039            Some(HttpError::BareCr)
1040        );
1041        assert_eq!(
1042            Response::new(200).header("x", " padded").error(),
1043            Some(HttpError::InvalidHeaderValue)
1044        );
1045        // The first error sticks.
1046        let r = Response::new(200)
1047            .header("a b", "1")
1048            .header("connection", "close");
1049        assert_eq!(r.error(), Some(HttpError::InvalidHeaderName));
1050    }
1051
1052    #[test]
1053    fn test_request_validates_method_target_and_host() {
1054        assert_eq!(
1055            Request::new("G T", "/").error(),
1056            Some(HttpError::InvalidMethod)
1057        );
1058        assert_eq!(
1059            Request::get("no-slash").error(),
1060            Some(HttpError::InvalidTarget)
1061        );
1062        assert_eq!(
1063            Request::get("/")
1064                .header("host", "a")
1065                .header("Host", "b")
1066                .error(),
1067            Some(HttpError::InvalidHost)
1068        );
1069        assert_eq!(
1070            Request::get("/").header("host", "a b").error(),
1071            Some(HttpError::InvalidHost)
1072        );
1073        assert!(Request::get("/").header("host", "a").has_host);
1074        assert_eq!(
1075            Request::get("/").upgrade("a b").error(),
1076            Some(HttpError::InvalidHeaderValue)
1077        );
1078    }
1079
1080    #[test]
1081    fn test_from_error_uses_status_text_and_close() {
1082        let r = Response::from_error(&HttpError::UnsupportedTransferEncoding);
1083        assert_eq!(r.status(), 501);
1084        assert!(r.closes());
1085        assert_eq!(
1086            r.header_value("content-type"),
1087            Some(&b"text/plain; charset=utf-8"[..])
1088        );
1089        assert_eq!(
1090            r.body_bytes(),
1091            Some(
1092                HttpError::UnsupportedTransferEncoding
1093                    .to_string()
1094                    .as_bytes()
1095            )
1096        );
1097        // Errors without a request status still get a well-formed 400.
1098        assert_eq!(
1099            Response::from_error(&HttpError::UnexpectedEof).status(),
1100            400
1101        );
1102        assert_eq!(
1103            Response::from_error(&HttpError::InvalidState("x")).error(),
1104            None
1105        );
1106    }
1107
1108    #[test]
1109    fn test_request_shortcuts_set_the_method() {
1110        for (r, m) in [
1111            (Request::head("/"), "HEAD"),
1112            (Request::put("/"), "PUT"),
1113            (Request::delete("/"), "DELETE"),
1114            (Request::options("*"), "OPTIONS"),
1115        ] {
1116            assert_eq!(r.method(), m);
1117            assert_eq!(r.error(), None);
1118        }
1119        assert_eq!(Request::put("*").error(), Some(HttpError::InvalidTarget));
1120        assert_eq!(Request::head("/").method_kind, Method::Head);
1121    }
1122
1123    #[test]
1124    fn test_upgrade_builders_accept_product_tokens_and_refuse_h2c() {
1125        let r = Response::switching_protocols("foo/2");
1126        assert_eq!(r.error(), None);
1127        assert_eq!(r.upgrade_protocol(), Some(&b"foo/2"[..]));
1128        assert_eq!(
1129            Response::switching_protocols("h2c").error(),
1130            Some(HttpError::UpgradeNotOffered)
1131        );
1132        assert_eq!(
1133            Response::switching_protocols("H2C").error(),
1134            Some(HttpError::UpgradeNotOffered)
1135        );
1136        assert_eq!(
1137            Response::switching_protocols("foo/").error(),
1138            Some(HttpError::InvalidHeaderValue)
1139        );
1140        assert_eq!(Response::new(200).upgrade_protocol(), None);
1141        assert_eq!(
1142            Request::get("/").upgrade("h2c").error(),
1143            Some(HttpError::UpgradeNotOffered)
1144        );
1145        assert!(Request::get("/").upgrade("websocket/13").upgrade);
1146    }
1147
1148    /// Threat T-35: credential values never reach `Debug` output.
1149    #[test]
1150    fn test_debug_redacts_credential_fields() {
1151        let r = Response::new(200)
1152            .header("Set-Cookie", "sid=s3cr3t; HttpOnly")
1153            .header("x-trace", "visible");
1154        let shown = alloc::format!("{r:?}");
1155        assert!(!shown.contains("s3cr3t"), "{shown}");
1156        assert!(shown.contains("<redacted 20 bytes>"), "{shown}");
1157        assert!(shown.contains("visible"), "{shown}");
1158        assert_eq!(
1159            r.header_value("set-cookie"),
1160            Some(&b"sid=s3cr3t; HttpOnly"[..])
1161        );
1162
1163        let q = Request::get("/")
1164            .header("host", "a")
1165            .header("Authorization", "Bearer t0k3n")
1166            .header("PROXY-AUTHORIZATION", "Basic cDpx")
1167            .header("cookie", "a=b");
1168        let shown = alloc::format!("{q:?}");
1169        for secret in ["t0k3n", "cDpx", "a=b"] {
1170            assert!(!shown.contains(secret), "{shown}");
1171        }
1172        assert!(shown.contains("\"host\", \"a\""), "{shown}");
1173    }
1174
1175    #[test]
1176    fn test_field_lookup_and_debug() {
1177        let r = Response::switching_protocols("websocket").header("x", "");
1178        assert_eq!(r.header_value("connection"), Some(&b"upgrade"[..]));
1179        assert_eq!(r.header_value("x"), Some(&b""[..]));
1180        assert!(alloc::format!("{r:?}").contains("Response"));
1181        assert_eq!(
1182            Response::switching_protocols("a b").error(),
1183            Some(HttpError::InvalidHeaderValue)
1184        );
1185    }
1186}