hyper/ext/
mod.rs

1//! HTTP extensions.
2
3#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
4use bytes::Bytes;
5#[cfg(any(
6    all(any(feature = "client", feature = "server"), feature = "http1"),
7    feature = "ffi"
8))]
9use http::header::HeaderName;
10#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
11use http::header::{HeaderMap, IntoHeaderName, ValueIter};
12#[cfg(feature = "ffi")]
13use std::collections::HashMap;
14#[cfg(feature = "http2")]
15use std::fmt;
16
17#[cfg(any(feature = "http1", feature = "ffi"))]
18mod h1_reason_phrase;
19#[cfg(any(feature = "http1", feature = "ffi"))]
20pub use h1_reason_phrase::ReasonPhrase;
21
22#[cfg(feature = "http2")]
23/// Represents the `:protocol` pseudo-header used by
24/// the [Extended CONNECT Protocol].
25///
26/// [Extended CONNECT Protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
27#[derive(Clone, Eq, PartialEq)]
28pub struct Protocol {
29    inner: h2::ext::Protocol,
30}
31
32#[cfg(feature = "http2")]
33impl Protocol {
34    /// Converts a static string to a protocol name.
35    pub const fn from_static(value: &'static str) -> Self {
36        Self {
37            inner: h2::ext::Protocol::from_static(value),
38        }
39    }
40
41    /// Returns a str representation of the header.
42    pub fn as_str(&self) -> &str {
43        self.inner.as_str()
44    }
45
46    #[cfg(feature = "server")]
47    pub(crate) fn from_inner(inner: h2::ext::Protocol) -> Self {
48        Self { inner }
49    }
50
51    #[cfg(all(feature = "client", feature = "http2"))]
52    pub(crate) fn into_inner(self) -> h2::ext::Protocol {
53        self.inner
54    }
55}
56
57#[cfg(feature = "http2")]
58impl<'a> From<&'a str> for Protocol {
59    fn from(value: &'a str) -> Self {
60        Self {
61            inner: h2::ext::Protocol::from(value),
62        }
63    }
64}
65
66#[cfg(feature = "http2")]
67impl AsRef<[u8]> for Protocol {
68    fn as_ref(&self) -> &[u8] {
69        self.inner.as_ref()
70    }
71}
72
73#[cfg(feature = "http2")]
74impl fmt::Debug for Protocol {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        self.inner.fmt(f)
77    }
78}
79
80/// A map from header names to their original casing as received in an HTTP message.
81///
82/// If an HTTP/1 response `res` is parsed on a connection whose option
83/// [`preserve_header_case`] was set to true and the response included
84/// the following headers:
85///
86/// ```ignore
87/// x-Bread: Baguette
88/// X-BREAD: Pain
89/// x-bread: Ficelle
90/// ```
91///
92/// Then `res.extensions().get::<HeaderCaseMap>()` will return a map with:
93///
94/// ```ignore
95/// HeaderCaseMap({
96///     "x-bread": ["x-Bread", "X-BREAD", "x-bread"],
97/// })
98/// ```
99///
100/// [`preserve_header_case`]: /client/struct.Client.html#method.preserve_header_case
101#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
102#[derive(Clone, Debug)]
103pub(crate) struct HeaderCaseMap(HeaderMap<Bytes>);
104
105#[cfg(all(any(feature = "client", feature = "server"), feature = "http1"))]
106impl HeaderCaseMap {
107    /// Returns a view of all spellings associated with that header name,
108    /// in the order they were found.
109    #[cfg(feature = "client")]
110    pub(crate) fn get_all<'a>(
111        &'a self,
112        name: &HeaderName,
113    ) -> impl Iterator<Item = impl AsRef<[u8]> + 'a> + 'a {
114        self.get_all_internal(name)
115    }
116
117    /// Returns a view of all spellings associated with that header name,
118    /// in the order they were found.
119    #[cfg(any(feature = "client", feature = "server"))]
120    pub(crate) fn get_all_internal(&self, name: &HeaderName) -> ValueIter<'_, Bytes> {
121        self.0.get_all(name).into_iter()
122    }
123
124    #[cfg(any(feature = "client", feature = "server"))]
125    pub(crate) fn default() -> Self {
126        Self(Default::default())
127    }
128
129    #[cfg(any(test, feature = "ffi"))]
130    pub(crate) fn insert(&mut self, name: HeaderName, orig: Bytes) {
131        self.0.insert(name, orig);
132    }
133
134    #[cfg(any(feature = "client", feature = "server"))]
135    pub(crate) fn append<N>(&mut self, name: N, orig: Bytes)
136    where
137        N: IntoHeaderName,
138    {
139        self.0.append(name, orig);
140    }
141}
142
143#[cfg(feature = "ffi")]
144#[derive(Clone, Debug)]
145/// Hashmap<Headername, numheaders with that name>
146pub(crate) struct OriginalHeaderOrder {
147    /// Stores how many entries a Headername maps to. This is used
148    /// for accounting.
149    num_entries: HashMap<HeaderName, usize>,
150    /// Stores the ordering of the headers. ex: `vec[i] = (headerName, idx)`,
151    /// The vector is ordered such that the ith element
152    /// represents the ith header that came in off the line.
153    /// The `HeaderName` and `idx` are then used elsewhere to index into
154    /// the multi map that stores the header values.
155    entry_order: Vec<(HeaderName, usize)>,
156}
157
158#[cfg(all(feature = "http1", feature = "ffi"))]
159impl OriginalHeaderOrder {
160    pub(crate) fn default() -> Self {
161        OriginalHeaderOrder {
162            num_entries: HashMap::new(),
163            entry_order: Vec::new(),
164        }
165    }
166
167    pub(crate) fn insert(&mut self, name: HeaderName) {
168        if !self.num_entries.contains_key(&name) {
169            let idx = 0;
170            self.num_entries.insert(name.clone(), 1);
171            self.entry_order.push((name, idx));
172        }
173        // Replacing an already existing element does not
174        // change ordering, so we only care if its the first
175        // header name encountered
176    }
177
178    pub(crate) fn append<N>(&mut self, name: N)
179    where
180        N: IntoHeaderName + Into<HeaderName> + Clone,
181    {
182        let name: HeaderName = name.into();
183        let idx;
184        if self.num_entries.contains_key(&name) {
185            idx = self.num_entries[&name];
186            *self.num_entries.get_mut(&name).unwrap() += 1;
187        } else {
188            idx = 0;
189            self.num_entries.insert(name.clone(), 1);
190        }
191        self.entry_order.push((name, idx));
192    }
193
194    // No doc test is run here because `RUSTFLAGS='--cfg hyper_unstable_ffi'`
195    // is needed to compile. Once ffi is stabilized `no_run` should be removed
196    // here.
197    /// This returns an iterator that provides header names and indexes
198    /// in the original order received.
199    ///
200    /// # Examples
201    /// ```no_run
202    /// use hyper::ext::OriginalHeaderOrder;
203    /// use hyper::header::{HeaderName, HeaderValue, HeaderMap};
204    ///
205    /// let mut h_order = OriginalHeaderOrder::default();
206    /// let mut h_map = Headermap::new();
207    ///
208    /// let name1 = b"Set-CookiE";
209    /// let value1 = b"a=b";
210    /// h_map.append(name1);
211    /// h_order.append(name1);
212    ///
213    /// let name2 = b"Content-Encoding";
214    /// let value2 = b"gzip";
215    /// h_map.append(name2, value2);
216    /// h_order.append(name2);
217    ///
218    /// let name3 = b"SET-COOKIE";
219    /// let value3 = b"c=d";
220    /// h_map.append(name3, value3);
221    /// h_order.append(name3)
222    ///
223    /// let mut iter = h_order.get_in_order()
224    ///
225    /// let (name, idx) = iter.next();
226    /// assert_eq!(b"a=b", h_map.get_all(name).nth(idx).unwrap());
227    ///
228    /// let (name, idx) = iter.next();
229    /// assert_eq!(b"gzip", h_map.get_all(name).nth(idx).unwrap());
230    ///
231    /// let (name, idx) = iter.next();
232    /// assert_eq!(b"c=d", h_map.get_all(name).nth(idx).unwrap());
233    /// ```
234    pub(crate) fn get_in_order(&self) -> impl Iterator<Item = &(HeaderName, usize)> {
235        self.entry_order.iter()
236    }
237}