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, unless it is a `101` or a
411    /// 2xx to `CONNECT`, which hand the connection over.
412    ///
413    /// # Examples
414    ///
415    /// ```
416    /// let r = http_net::Response::new(503).close();
417    /// assert!(r.closes());
418    /// ```
419    #[must_use]
420    pub fn close(mut self) -> Self {
421        self.close = true;
422        self
423    }
424
425    /// Resets the response to `Response::new(status)` while keeping the
426    /// allocation of its field storage, so one `Response` per connection
427    /// can be reused without allocating for every request. An owned body is
428    /// dropped.
429    ///
430    /// # Examples
431    ///
432    /// ```
433    /// use http_net::Response;
434    ///
435    /// let mut r = Response::new(200).header("x-request", "1").close();
436    /// r.clear(204);
437    /// assert_eq!(r.status(), 204);
438    /// assert_eq!(r.header_value("x-request"), None);
439    /// assert!(!r.closes());
440    /// r = r.header("x-request", "2"); // reuses the field storage
441    /// assert_eq!(r.header_value("x-request"), Some(&b"2"[..]));
442    /// ```
443    pub fn clear(&mut self, status: u16) {
444        self.status = status;
445        self.fields.clear();
446        self.body = OutBody::Full(Cow::Borrowed(&[]));
447        self.close = false;
448        self.upgrade = false;
449        self.has_date = false;
450        self.error = None;
451    }
452
453    /// The status code.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// assert_eq!(http_net::Response::new(418).status(), 418);
459    /// ```
460    #[must_use]
461    pub fn status(&self) -> u16 {
462        self.status
463    }
464
465    /// Whether [`close`](Self::close) was requested.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// assert!(!http_net::Response::new(200).closes());
471    /// ```
472    #[must_use]
473    pub fn closes(&self) -> bool {
474        self.close
475    }
476
477    /// The full body, or `None` for a streamed one.
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// assert_eq!(http_net::Response::new(200).body_bytes(), Some(&[][..]));
483    /// ```
484    #[must_use]
485    pub fn body_bytes(&self) -> Option<&[u8]> {
486        match &self.body {
487            OutBody::Full(b) => Some(b),
488            _ => None,
489        }
490    }
491
492    /// The value of the first header named `name` added to this response
493    /// (ASCII case-insensitive), including the `upgrade` of
494    /// [`switching_protocols`](Self::switching_protocols).
495    ///
496    /// # Examples
497    ///
498    /// ```
499    /// let r = http_net::Response::new(200).header("x-id", "7");
500    /// assert_eq!(r.header_value("X-ID"), Some(&b"7"[..]));
501    /// ```
502    #[must_use]
503    pub fn header_value(&self, name: &str) -> Option<&[u8]> {
504        field_value(&self.fields, name)
505    }
506
507    pub(crate) fn error(&self) -> Option<HttpError> {
508        self.error
509    }
510
511    pub(crate) fn fields(&self) -> &[u8] {
512        &self.fields
513    }
514
515    /// The protocol a `101` built with
516    /// [`switching_protocols`](Self::switching_protocols) switches to.
517    pub(crate) fn upgrade_protocol(&self) -> Option<&[u8]> {
518        if self.upgrade {
519            self.header_value("upgrade")
520        } else {
521            None
522        }
523    }
524}
525
526/// Shows status, fields, body size, and flags; the values of credential
527/// fields (`set-cookie` above all) are replaced by `<redacted N bytes>`.
528impl fmt::Debug for Response {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        f.debug_struct("Response")
531            .field("status", &self.status)
532            .field("fields", &SerializedFields(&self.fields))
533            .field("body", &body_debug(&self.body))
534            .field("close", &self.close)
535            .field("error", &self.error)
536            .finish()
537    }
538}
539
540/// A request for a [`ClientConn`](crate::ClientConn) to send.
541///
542/// HTTP/1.1 requires a `Host` field; the connection refuses to send a
543/// request without one. The request line always says HTTP/1.1.
544///
545/// # Examples
546///
547/// ```
548/// use http_net::Request;
549///
550/// let get = Request::get("/index.html").header("host", "example.com");
551/// let post = Request::post("/api")
552///     .header("host", "example.com")
553///     .header("content-type", "application/json")
554///     .body(br#"{"ok":true}"#.to_vec());
555/// assert_eq!(get.method(), "GET");
556/// assert_eq!(post.target(), "/api");
557/// ```
558#[derive(Clone, PartialEq, Eq)]
559pub struct Request {
560    method: Cow<'static, str>,
561    pub(crate) method_kind: Method,
562    target: String,
563    fields: Vec<u8>,
564    pub(crate) body: OutBody,
565    pub(crate) close: bool,
566    pub(crate) upgrade: bool,
567    pub(crate) has_host: bool,
568    pub(crate) expect_continue: bool,
569    error: Option<HttpError>,
570}
571
572impl Request {
573    /// A request with `method` and `target`, validated when it is sent:
574    /// the method must be a token and the target must be in a form the
575    /// method allows (`/path?query`, an absolute URI, `host:port` for
576    /// `CONNECT`, or `*` for `OPTIONS`).
577    ///
578    /// # Examples
579    ///
580    /// ```
581    /// let r = http_net::Request::new("PURGE", "/cache/a");
582    /// assert_eq!(r.method(), "PURGE");
583    /// ```
584    #[must_use]
585    pub fn new(method: &str, target: &str) -> Self {
586        let method_kind = Method::from_bytes(method.as_bytes());
587        let mut error = None;
588        if !is_token(method.as_bytes()) {
589            error = Some(HttpError::InvalidMethod);
590        } else if let Err(e) = check_target(method_kind, target.as_bytes()) {
591            error = Some(e);
592        }
593        Self {
594            method: match method_kind.as_str() {
595                Some(s) => Cow::Borrowed(s),
596                None => Cow::Owned(method.into()),
597            },
598            method_kind,
599            target: target.into(),
600            fields: Vec::new(),
601            body: OutBody::Full(Cow::Borrowed(&[])),
602            close: false,
603            upgrade: false,
604            has_host: false,
605            expect_continue: false,
606            error,
607        }
608    }
609
610    /// A `GET` request.
611    ///
612    /// # Examples
613    ///
614    /// ```
615    /// assert_eq!(http_net::Request::get("/").method(), "GET");
616    /// ```
617    #[must_use]
618    pub fn get(target: &str) -> Self {
619        Self::new("GET", target)
620    }
621
622    /// A `POST` request.
623    ///
624    /// # Examples
625    ///
626    /// ```
627    /// assert_eq!(http_net::Request::post("/").method(), "POST");
628    /// ```
629    #[must_use]
630    pub fn post(target: &str) -> Self {
631        Self::new("POST", target)
632    }
633
634    /// A `HEAD` request: its response carries headers and no body.
635    ///
636    /// # Examples
637    ///
638    /// ```
639    /// assert_eq!(http_net::Request::head("/").method(), "HEAD");
640    /// ```
641    #[must_use]
642    pub fn head(target: &str) -> Self {
643        Self::new("HEAD", target)
644    }
645
646    /// A `PUT` request.
647    ///
648    /// # Examples
649    ///
650    /// ```
651    /// assert_eq!(http_net::Request::put("/files/a").method(), "PUT");
652    /// ```
653    #[must_use]
654    pub fn put(target: &str) -> Self {
655        Self::new("PUT", target)
656    }
657
658    /// A `DELETE` request.
659    ///
660    /// # Examples
661    ///
662    /// ```
663    /// assert_eq!(http_net::Request::delete("/files/a").method(), "DELETE");
664    /// ```
665    #[must_use]
666    pub fn delete(target: &str) -> Self {
667        Self::new("DELETE", target)
668    }
669
670    /// An `OPTIONS` request; `*` asks about the server as a whole.
671    ///
672    /// # Examples
673    ///
674    /// ```
675    /// assert_eq!(http_net::Request::options("*").target(), "*");
676    /// ```
677    #[must_use]
678    pub fn options(target: &str) -> Self {
679        Self::new("OPTIONS", target)
680    }
681
682    /// A request for an upstream server built from a received head, for a
683    /// proxy: the same method and target, every field except the hop-by-hop
684    /// ones (RFC 9110 section 7.6.1: `connection`, `keep-alive`,
685    /// `proxy-connection`, `te`, `transfer-encoding`, `upgrade`, `trailer`,
686    /// and any name the head's `Connection` lists; see
687    /// [`is_hop_by_hop`](crate::is_hop_by_hop)) in their original order,
688    /// except `content-length`, which the connection derives again from
689    /// the body mode of the head's framing: a chunked body stays
690    /// chunked, a length stays that length (stream it with
691    /// [`ClientConn::send_body`](crate::ClientConn::send_body)). The
692    /// connection writes its own framing and connection fields.
693    ///
694    /// The target is copied as received: an absolute-form target (a request
695    /// to a proxy) stays absolute, which an origin server also accepts (RFC
696    /// 9112 section 3.2.2); rewrite it with [`Request::new`] if the upstream
697    /// wants origin form. `Host` is forwarded as a field. Add `via` and
698    /// forwarding fields with [`header`](Self::header); requests are
699    /// re-serialized, never passed through as raw bytes.
700    ///
701    /// Every name the client lists in `Connection` is dropped, as RFC 9110
702    /// section 7.6.1 requires, including end-to-end names such as
703    /// `authorization` or `x-forwarded-for`: a client can strip fields a
704    /// proxy relies on this way. Check
705    /// [`connection_options`](crate::RequestHead::connection_options)
706    /// first if the next hop must see one of them. Listing `host` drops it
707    /// too, and the request then fails closed at send (no `Host`).
708    ///
709    /// # Errors
710    ///
711    /// Recorded and returned by
712    /// [`ClientConn::send_request`](crate::ClientConn::send_request):
713    /// [`HttpError::InvalidState`] for an upgrade request (the upgrade is
714    /// hop-by-hop; a proxy tunnels it instead), and the builder errors of
715    /// [`Request::new`] and [`Request::header`] (for example a missing or
716    /// second `host` surfaces at send).
717    ///
718    /// # Examples
719    ///
720    /// ```
721    /// use http_net::{ClientConn, Request, ServerConn, ServerEvent};
722    ///
723    /// let mut downstream = ServerConn::new();
724    /// 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");
725    /// let ServerEvent::Request(head) = downstream.poll()? else { unreachable!() };
726    /// let upstream_req = Request::forward_from(&head).header("via", "1.1 proxy");
727    ///
728    /// let mut upstream = ClientConn::new();
729    /// let mut out = Vec::new();
730    /// upstream.send_request(&upstream_req, &mut out)?;
731    /// 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");
732    /// # Ok::<(), http_net::HttpError>(())
733    /// ```
734    #[must_use]
735    pub fn forward_from(head: &RequestHead<'_>) -> Self {
736        let mut request = Self::new(head.method_str(), head.target());
737        if head.is_upgrade() {
738            if request.error.is_none() {
739                request.error = Some(HttpError::InvalidState(
740                    "an upgrade request is hop-by-hop; tunnel it instead of forwarding it",
741                ));
742            }
743            return request;
744        }
745        for (name, value) in head.headers() {
746            // `content-length` is end-to-end, but the connection derives it
747            // from the body mode below, so it is not copied as a field.
748            if !is_hop_by_hop(name, head.connection_options())
749                && !name.eq_ignore_ascii_case("content-length")
750            {
751                request = request.header(name, value);
752            }
753        }
754        match head.framing() {
755            BodyFraming::Chunked => request.chunked(),
756            BodyFraming::Length(n) => request.content_length(n),
757            _ => request,
758        }
759    }
760
761    /// Adds a header field, validated as for [`Response::header`], except
762    /// that `te` is allowed on a request. A second `host`, or a `host` value
763    /// that is not `host[:port]`, is refused with [`HttpError::InvalidHost`].
764    ///
765    /// # Examples
766    ///
767    /// ```
768    /// let r = http_net::Request::get("/").header("host", "a").header("accept", "*/*");
769    /// assert_eq!(r.header_value("accept"), Some(&b"*/*"[..]));
770    /// ```
771    #[must_use]
772    pub fn header(mut self, name: &str, value: impl AsRef<[u8]>) -> Self {
773        if self.error.is_none() {
774            let value = value.as_ref();
775            let is_host = name.eq_ignore_ascii_case("host");
776            if is_host && (self.has_host || !crate::scan::is_host_value(value)) {
777                self.error = Some(HttpError::InvalidHost);
778            } else if let Err(e) = push_field(&mut self.fields, name, value, REQUEST_RESERVED) {
779                self.error = Some(e);
780            } else {
781                self.has_host |= is_host;
782            }
783        }
784        self
785    }
786
787    /// Sets the whole body, sent with `content-length`.
788    ///
789    /// # Examples
790    ///
791    /// ```
792    /// let r = http_net::Request::post("/").body(&b"x=1"[..]);
793    /// assert_eq!(r.body_bytes(), Some(&b"x=1"[..]));
794    /// ```
795    #[must_use]
796    pub fn body(mut self, body: impl Into<Cow<'static, [u8]>>) -> Self {
797        self.body = OutBody::Full(body.into());
798        self
799    }
800
801    /// Streams the body with chunked encoding through
802    /// [`ClientConn::send_body`](crate::ClientConn::send_body) and
803    /// [`ClientConn::end_body`](crate::ClientConn::end_body).
804    ///
805    /// # Examples
806    ///
807    /// ```
808    /// assert_eq!(http_net::Request::post("/").chunked().body_bytes(), None);
809    /// ```
810    #[must_use]
811    pub fn chunked(mut self) -> Self {
812        self.body = OutBody::Chunked;
813        self
814    }
815
816    /// Streams a body of exactly `len` bytes.
817    ///
818    /// # Examples
819    ///
820    /// ```
821    /// assert_eq!(http_net::Request::post("/").content_length(4).body_bytes(), None);
822    /// ```
823    #[must_use]
824    pub fn content_length(mut self, len: u64) -> Self {
825        self.body = OutBody::Length(len);
826        self
827    }
828
829    /// Asks the server to close the connection after its response.
830    ///
831    /// # Examples
832    ///
833    /// ```
834    /// let _ = http_net::Request::get("/").header("host", "a").close();
835    /// ```
836    #[must_use]
837    pub fn close(mut self) -> Self {
838        self.close = true;
839        self
840    }
841
842    /// Sends `expect: 100-continue` and holds the body back until the
843    /// server agrees (RFC 9110 section 10.1.1): for large uploads the
844    /// server may refuse from the head alone. The body must be streamed
845    /// ([`content_length`](Self::content_length) or
846    /// [`chunked`](Self::chunked)); send it with
847    /// [`ClientConn::send_body`](crate::ClientConn::send_body) after
848    /// [`ClientEvent::Continue`](crate::ClientEvent::Continue), or after a
849    /// wait of your choosing. A final status instead means the server does
850    /// not want the body: it must not be sent, and the connection closes
851    /// after the response.
852    ///
853    /// # Examples
854    ///
855    /// ```
856    /// use http_net::{ClientConn, ClientEvent, HttpError, Request};
857    ///
858    /// let mut conn = ClientConn::new();
859    /// let mut out = Vec::new();
860    /// let upload = Request::put("/f").header("host", "a").content_length(9).expect_continue();
861    /// conn.send_request(&upload, &mut out)?;
862    /// assert!(out.ends_with(b"expect: 100-continue\r\ncontent-length: 9\r\n\r\n"));
863    /// let _ = conn.feed(b"HTTP/1.1 413 Content Too Large\r\nContent-Length: 0\r\n\r\n");
864    /// assert!(matches!(conn.poll()?, ClientEvent::Response(r) if r.status() == 413));
865    /// assert!(matches!(conn.send_body(b"too large", &mut out), Err(HttpError::InvalidState(_))));
866    /// assert!(matches!(conn.poll()?, ClientEvent::ResponseEnd));
867    /// assert!(matches!(conn.poll()?, ClientEvent::Closed));
868    /// # Ok::<(), http_net::HttpError>(())
869    /// ```
870    #[must_use]
871    pub fn expect_continue(mut self) -> Self {
872        if self.error.is_none() && !self.expect_continue {
873            self.expect_continue = true;
874            self.fields.extend_from_slice(b"expect: 100-continue\r\n");
875        }
876        self
877    }
878
879    /// Asks to switch the connection to `protocol` (writes
880    /// `connection: upgrade` and `upgrade: <protocol>`). A `101` answer
881    /// hands the connection over; see
882    /// [`ClientEvent::Upgraded`](crate::ClientEvent::Upgraded).
883    ///
884    /// `protocol` is a token or a `name/version` product token; anything
885    /// else is refused with [`HttpError::InvalidHeaderValue`]. `h2c` is
886    /// refused with [`HttpError::UpgradeNotOffered`]: RFC 9113 section 3.1
887    /// deprecates the HTTP/2 upgrade.
888    ///
889    /// # Examples
890    ///
891    /// ```
892    /// use http_net::{ClientConn, HttpError, Request};
893    ///
894    /// let r = Request::get("/rpc").header("host", "a").upgrade("websocket");
895    /// assert_eq!(r.header_value("upgrade"), Some(&b"websocket"[..]));
896    ///
897    /// let h2c = Request::get("/").header("host", "a").upgrade("h2c");
898    /// assert_eq!(
899    ///     ClientConn::new().send_request(&h2c, &mut Vec::new()),
900    ///     Err(HttpError::UpgradeNotOffered)
901    /// );
902    /// ```
903    #[must_use]
904    pub fn upgrade(mut self, protocol: &str) -> Self {
905        if self.error.is_none() {
906            if is_h2c(protocol.as_bytes()) {
907                self.error = Some(HttpError::UpgradeNotOffered);
908            } else if is_protocol(protocol.as_bytes()) {
909                self.upgrade = true;
910                self.fields
911                    .extend_from_slice(b"connection: upgrade\r\nupgrade: ");
912                self.fields.extend_from_slice(protocol.as_bytes());
913                self.fields.extend_from_slice(b"\r\n");
914            } else {
915                self.error = Some(HttpError::InvalidHeaderValue);
916            }
917        }
918        self
919    }
920
921    /// The method text.
922    ///
923    /// # Examples
924    ///
925    /// ```
926    /// assert_eq!(http_net::Request::new("OPTIONS", "*").method(), "OPTIONS");
927    /// ```
928    #[must_use]
929    pub fn method(&self) -> &str {
930        &self.method
931    }
932
933    /// The request target.
934    ///
935    /// # Examples
936    ///
937    /// ```
938    /// assert_eq!(http_net::Request::get("/a?b").target(), "/a?b");
939    /// ```
940    #[must_use]
941    pub fn target(&self) -> &str {
942        &self.target
943    }
944
945    /// The full body, or `None` for a streamed one.
946    ///
947    /// # Examples
948    ///
949    /// ```
950    /// assert_eq!(http_net::Request::get("/").body_bytes(), Some(&[][..]));
951    /// ```
952    #[must_use]
953    pub fn body_bytes(&self) -> Option<&[u8]> {
954        match &self.body {
955            OutBody::Full(b) => Some(b),
956            _ => None,
957        }
958    }
959
960    /// The value of the first header named `name` added to this request.
961    ///
962    /// # Examples
963    ///
964    /// ```
965    /// let r = http_net::Request::get("/").header("host", "a");
966    /// assert_eq!(r.header_value("HOST"), Some(&b"a"[..]));
967    /// ```
968    #[must_use]
969    pub fn header_value(&self, name: &str) -> Option<&[u8]> {
970        field_value(&self.fields, name)
971    }
972
973    pub(crate) fn error(&self) -> Option<HttpError> {
974        self.error
975    }
976
977    pub(crate) fn fields(&self) -> &[u8] {
978        &self.fields
979    }
980
981    /// The values of the `upgrade` fields [`upgrade`](Self::upgrade) added
982    /// (`header` refuses the name, so these are the only ones).
983    pub(crate) fn upgrade_offers(&self) -> impl Iterator<Item = &[u8]> {
984        serialized_fields(&self.fields)
985            .filter(|(n, _)| n.eq_ignore_ascii_case(b"upgrade"))
986            .map(|(_, v)| v)
987    }
988}
989
990/// Shows method, target, fields, and body size; the values of credential
991/// fields (`authorization`, `proxy-authorization`, `cookie`) are replaced by
992/// `<redacted N bytes>`.
993impl fmt::Debug for Request {
994    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
995        f.debug_struct("Request")
996            .field("method", &self.method)
997            .field("target", &self.target)
998            .field("fields", &SerializedFields(&self.fields))
999            .field("body", &body_debug(&self.body))
1000            .field("error", &self.error)
1001            .finish()
1002    }
1003}
1004
1005fn body_debug(body: &OutBody) -> String {
1006    match body {
1007        OutBody::Full(b) => format!("{} bytes", b.len()),
1008        OutBody::Length(n) => format!("streamed, {n} bytes"),
1009        OutBody::Chunked => "streamed, chunked".into(),
1010    }
1011}
1012
1013/// Looks a header up in serialized `name: value\r\n` lines.
1014fn field_value<'a>(fields: &'a [u8], name: &str) -> Option<&'a [u8]> {
1015    serialized_fields(fields)
1016        .find(|(n, _)| n.eq_ignore_ascii_case(name.as_bytes()))
1017        .map(|(_, v)| v)
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022    use alloc::string::ToString;
1023
1024    use super::*;
1025
1026    #[test]
1027    fn test_response_refuses_reserved_and_invalid_headers() {
1028        assert_eq!(
1029            Response::new(200)
1030                .header("Transfer-Encoding", "chunked")
1031                .error(),
1032            Some(HttpError::ReservedHeader)
1033        );
1034        assert_eq!(
1035            Response::new(200).header("bad name", "x").error(),
1036            Some(HttpError::InvalidHeaderName)
1037        );
1038        assert_eq!(
1039            Response::new(200).header("x", "a\r\nInjected: 1").error(),
1040            Some(HttpError::BareCr)
1041        );
1042        assert_eq!(
1043            Response::new(200).header("x", " padded").error(),
1044            Some(HttpError::InvalidHeaderValue)
1045        );
1046        // The first error sticks.
1047        let r = Response::new(200)
1048            .header("a b", "1")
1049            .header("connection", "close");
1050        assert_eq!(r.error(), Some(HttpError::InvalidHeaderName));
1051    }
1052
1053    #[test]
1054    fn test_request_validates_method_target_and_host() {
1055        assert_eq!(
1056            Request::new("G T", "/").error(),
1057            Some(HttpError::InvalidMethod)
1058        );
1059        assert_eq!(
1060            Request::get("no-slash").error(),
1061            Some(HttpError::InvalidTarget)
1062        );
1063        assert_eq!(
1064            Request::get("/")
1065                .header("host", "a")
1066                .header("Host", "b")
1067                .error(),
1068            Some(HttpError::InvalidHost)
1069        );
1070        assert_eq!(
1071            Request::get("/").header("host", "a b").error(),
1072            Some(HttpError::InvalidHost)
1073        );
1074        assert!(Request::get("/").header("host", "a").has_host);
1075        assert_eq!(
1076            Request::get("/").upgrade("a b").error(),
1077            Some(HttpError::InvalidHeaderValue)
1078        );
1079    }
1080
1081    #[test]
1082    fn test_from_error_uses_status_text_and_close() {
1083        let r = Response::from_error(&HttpError::UnsupportedTransferEncoding);
1084        assert_eq!(r.status(), 501);
1085        assert!(r.closes());
1086        assert_eq!(
1087            r.header_value("content-type"),
1088            Some(&b"text/plain; charset=utf-8"[..])
1089        );
1090        assert_eq!(
1091            r.body_bytes(),
1092            Some(
1093                HttpError::UnsupportedTransferEncoding
1094                    .to_string()
1095                    .as_bytes()
1096            )
1097        );
1098        // Errors without a request status still get a well-formed 400.
1099        assert_eq!(
1100            Response::from_error(&HttpError::UnexpectedEof).status(),
1101            400
1102        );
1103        assert_eq!(
1104            Response::from_error(&HttpError::InvalidState("x")).error(),
1105            None
1106        );
1107    }
1108
1109    #[test]
1110    fn test_request_shortcuts_set_the_method() {
1111        for (r, m) in [
1112            (Request::head("/"), "HEAD"),
1113            (Request::put("/"), "PUT"),
1114            (Request::delete("/"), "DELETE"),
1115            (Request::options("*"), "OPTIONS"),
1116        ] {
1117            assert_eq!(r.method(), m);
1118            assert_eq!(r.error(), None);
1119        }
1120        assert_eq!(Request::put("*").error(), Some(HttpError::InvalidTarget));
1121        assert_eq!(Request::head("/").method_kind, Method::Head);
1122    }
1123
1124    #[test]
1125    fn test_upgrade_builders_accept_product_tokens_and_refuse_h2c() {
1126        let r = Response::switching_protocols("foo/2");
1127        assert_eq!(r.error(), None);
1128        assert_eq!(r.upgrade_protocol(), Some(&b"foo/2"[..]));
1129        assert_eq!(
1130            Response::switching_protocols("h2c").error(),
1131            Some(HttpError::UpgradeNotOffered)
1132        );
1133        assert_eq!(
1134            Response::switching_protocols("H2C").error(),
1135            Some(HttpError::UpgradeNotOffered)
1136        );
1137        assert_eq!(
1138            Response::switching_protocols("foo/").error(),
1139            Some(HttpError::InvalidHeaderValue)
1140        );
1141        assert_eq!(Response::new(200).upgrade_protocol(), None);
1142        assert_eq!(
1143            Request::get("/").upgrade("h2c").error(),
1144            Some(HttpError::UpgradeNotOffered)
1145        );
1146        assert!(Request::get("/").upgrade("websocket/13").upgrade);
1147    }
1148
1149    /// Threat T-35: credential values never reach `Debug` output.
1150    #[test]
1151    fn test_debug_redacts_credential_fields() {
1152        let r = Response::new(200)
1153            .header("Set-Cookie", "sid=s3cr3t; HttpOnly")
1154            .header("x-trace", "visible");
1155        let shown = alloc::format!("{r:?}");
1156        assert!(!shown.contains("s3cr3t"), "{shown}");
1157        assert!(shown.contains("<redacted 20 bytes>"), "{shown}");
1158        assert!(shown.contains("visible"), "{shown}");
1159        assert_eq!(
1160            r.header_value("set-cookie"),
1161            Some(&b"sid=s3cr3t; HttpOnly"[..])
1162        );
1163
1164        let q = Request::get("/")
1165            .header("host", "a")
1166            .header("Authorization", "Bearer t0k3n")
1167            .header("PROXY-AUTHORIZATION", "Basic cDpx")
1168            .header("cookie", "a=b");
1169        let shown = alloc::format!("{q:?}");
1170        for secret in ["t0k3n", "cDpx", "a=b"] {
1171            assert!(!shown.contains(secret), "{shown}");
1172        }
1173        assert!(shown.contains("\"host\", \"a\""), "{shown}");
1174    }
1175
1176    #[test]
1177    fn test_field_lookup_and_debug() {
1178        let r = Response::switching_protocols("websocket").header("x", "");
1179        assert_eq!(r.header_value("connection"), Some(&b"upgrade"[..]));
1180        assert_eq!(r.header_value("x"), Some(&b""[..]));
1181        assert!(alloc::format!("{r:?}").contains("Response"));
1182        assert_eq!(
1183            Response::switching_protocols("a b").error(),
1184            Some(HttpError::InvalidHeaderValue)
1185        );
1186    }
1187}