viaduct/
headers.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4pub use name::{HeaderName, InvalidHeaderName};
5use std::collections::HashMap;
6use std::iter::FromIterator;
7use std::str::FromStr;
8mod name;
9
10/// A single header. Headers have a name (case insensitive) and a value. The
11/// character set for header and values are both restrictive.
12/// - Names must only contain a-zA-Z0-9 and and ('!' | '#' | '$' | '%' | '&' |
13///   '\'' | '*' | '+' | '-' | '.' | '^' | '_' | '`' | '|' | '~') characters
14///   (the field-name token production defined at
15///   https://tools.ietf.org/html/rfc7230#section-3.2).
16///   For request headers, we expect these to all be specified statically,
17///   and so we panic if you provide an invalid one. (For response headers, we
18///   ignore headers with invalid names, but emit a warning).
19///
20///   Header names are case insensitive, and we have several pre-defined ones in
21///   the [`header_names`] module.
22///
23/// - Values may only contain printable ascii characters, and may not contain
24///   \r or \n. Strictly speaking, HTTP is more flexible for header values,
25///   however we don't need to support binary header values, and so we do not.
26///
27/// Note that typically you should not interact with this directly, and instead
28/// use the methods on [`Request`] or [`Headers`] to manipulate these.
29#[derive(Clone, Debug, PartialEq, PartialOrd, Hash, Eq, Ord)]
30pub struct Header {
31    pub(crate) name: HeaderName,
32    pub(crate) value: String,
33}
34
35// Trim `s` without copying if it can be avoided.
36fn trim_string<S: AsRef<str> + Into<String>>(s: S) -> String {
37    let sr = s.as_ref();
38    let trimmed = sr.trim();
39    if sr.len() != trimmed.len() {
40        trimmed.into()
41    } else {
42        s.into()
43    }
44}
45
46fn is_valid_header_value(value: &str) -> bool {
47    value.bytes().all(|b| (32..127).contains(&b) || b == b'\t')
48}
49
50impl Header {
51    pub fn new<Name, Value>(name: Name, value: Value) -> Result<Self, crate::Error>
52    where
53        Name: Into<HeaderName>,
54        Value: AsRef<str> + Into<String>,
55    {
56        let name = name.into();
57        let value = trim_string(value);
58        if !is_valid_header_value(&value) {
59            return Err(crate::Error::RequestHeaderError(name));
60        }
61        Ok(Self { name, value })
62    }
63
64    pub fn new_unchecked<Value>(name: HeaderName, value: Value) -> Self
65    where
66        Value: AsRef<str> + Into<String>,
67    {
68        Self {
69            name,
70            value: value.into(),
71        }
72    }
73
74    #[inline]
75    pub fn name(&self) -> &HeaderName {
76        &self.name
77    }
78
79    #[inline]
80    pub fn value(&self) -> &str {
81        &self.value
82    }
83
84    #[inline]
85    fn set_value<V: AsRef<str>>(&mut self, s: V) -> Result<(), crate::Error> {
86        let value = s.as_ref();
87        if !is_valid_header_value(value) {
88            Err(crate::Error::RequestHeaderError(self.name.clone()))
89        } else {
90            self.value.clear();
91            self.value.push_str(s.as_ref().trim());
92            Ok(())
93        }
94    }
95}
96
97impl std::fmt::Display for Header {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        write!(f, "{}: {}", self.name, self.value)
100    }
101}
102
103/// A list of headers.
104#[derive(Clone, Debug, PartialEq, Eq, Default)]
105pub struct Headers {
106    headers: Vec<Header>,
107}
108
109impl Headers {
110    /// Initialize an empty list of headers.
111    #[inline]
112    pub fn new() -> Self {
113        Default::default()
114    }
115
116    /// Initialize an empty list of headers backed by a vector with the provided
117    /// capacity.
118    pub fn with_capacity(c: usize) -> Self {
119        Self {
120            headers: Vec::with_capacity(c),
121        }
122    }
123
124    /// Convert this list of headers to a Vec<Header>
125    #[inline]
126    pub fn into_vec(self) -> Vec<Header> {
127        self.headers
128    }
129
130    /// Returns the number of headers.
131    #[inline]
132    pub fn len(&self) -> usize {
133        self.headers.len()
134    }
135
136    /// Returns true if `len()` is zero.
137    #[inline]
138    pub fn is_empty(&self) -> bool {
139        self.headers.is_empty()
140    }
141    /// Clear this set of headers.
142    #[inline]
143    pub fn clear(&mut self) {
144        self.headers.clear();
145    }
146
147    /// Insert or update a new header.
148    ///
149    /// This returns an error if you attempt to specify a header with an
150    /// invalid value (values must be printable ASCII and may not contain
151    /// \r or \n)
152    ///
153    /// ## Example
154    /// ```
155    /// # use viaduct::Headers;
156    /// # fn main() -> Result<(), viaduct::Error> {
157    /// let mut h = Headers::new();
158    /// h.insert("My-Cool-Header", "example")?;
159    /// assert_eq!(h.get("My-Cool-Header"), Some("example"));
160    ///
161    /// // Note: names are sensitive
162    /// assert_eq!(h.get("my-cool-header"), Some("example"));
163    ///
164    /// // Also note, constants for headers are in `viaduct::header_names`, and
165    /// // you can chain the result of this function.
166    /// h.insert(viaduct::header_names::CONTENT_TYPE, "something...")?
167    ///  .insert("Something-Else", "etc")?;
168    /// # Ok(())
169    /// # }
170    /// ```
171    pub fn insert<N, V>(&mut self, name: N, value: V) -> Result<&mut Self, crate::Error>
172    where
173        N: Into<HeaderName> + PartialEq<HeaderName>,
174        V: Into<String> + AsRef<str>,
175    {
176        if let Some(entry) = self.headers.iter_mut().find(|h| name == h.name) {
177            entry.set_value(value)?;
178        } else {
179            self.headers.push(Header::new(name, value)?);
180        }
181        Ok(self)
182    }
183
184    /// Insert the provided header unless a header is already specified.
185    /// Mostly used internally, e.g. to set "Content-Type: application/json"
186    /// in `Request::json()` unless it has been set specifically.
187    pub fn insert_if_missing<N, V>(&mut self, name: N, value: V) -> Result<&mut Self, crate::Error>
188    where
189        N: Into<HeaderName> + PartialEq<HeaderName>,
190        V: Into<String> + AsRef<str>,
191    {
192        if !self.headers.iter_mut().any(|h| name == h.name) {
193            self.headers.push(Header::new(name, value)?);
194        }
195        Ok(self)
196    }
197
198    /// Insert or update a header directly. Typically you will want to use
199    /// `insert` over this, as it performs less work if the header needs
200    /// updating instead of insertion.
201    pub fn insert_header(&mut self, new: Header) -> &mut Self {
202        if let Some(entry) = self.headers.iter_mut().find(|h| h.name == new.name) {
203            entry.value = new.value;
204        } else {
205            self.headers.push(new);
206        }
207        self
208    }
209
210    /// Add all the headers in the provided iterator to this list of headers.
211    pub fn extend<I>(&mut self, iter: I) -> &mut Self
212    where
213        I: IntoIterator<Item = Header>,
214    {
215        let it = iter.into_iter();
216        self.headers.reserve(it.size_hint().0);
217        for h in it {
218            self.insert_header(h);
219        }
220        self
221    }
222
223    /// Add all the headers in the provided iterator, unless any of them are Err.
224    pub fn try_extend<I, E>(&mut self, iter: I) -> Result<&mut Self, E>
225    where
226        I: IntoIterator<Item = Result<Header, E>>,
227    {
228        // Not the most efficient but avoids leaving us in an unspecified state
229        // if one returns Err.
230        self.extend(iter.into_iter().collect::<Result<Vec<_>, E>>()?);
231        Ok(self)
232    }
233
234    /// Get the header object with the requested name. Usually, you will
235    /// want to use `get()` or `get_as::<T>()` instead.
236    pub fn get_header<S>(&self, name: S) -> Option<&Header>
237    where
238        S: PartialEq<HeaderName>,
239    {
240        self.headers.iter().find(|h| name == h.name)
241    }
242
243    /// Get the value of the header with the provided name.
244    ///
245    /// See also `get_as`.
246    ///
247    /// ## Example
248    /// ```
249    /// # use viaduct::{Headers, header_names::CONTENT_TYPE};
250    /// # fn main() -> Result<(), viaduct::Error> {
251    /// let mut h = Headers::new();
252    /// h.insert(CONTENT_TYPE, "application/json")?;
253    /// assert_eq!(h.get(CONTENT_TYPE), Some("application/json"));
254    /// assert_eq!(h.get("Something-Else"), None);
255    /// # Ok(())
256    /// # }
257    /// ```
258    pub fn get<S>(&self, name: S) -> Option<&str>
259    where
260        S: PartialEq<HeaderName>,
261    {
262        self.get_header(name).map(|h| h.value.as_str())
263    }
264
265    /// Get the value of the header with the provided name, and
266    /// attempt to parse it using [`std::str::FromStr`].
267    ///
268    /// - If the header is missing, it returns None.
269    /// - If the header is present but parsing failed, returns
270    ///   `Some(Err(<error returned by parsing>))`.
271    /// - Otherwise, returns `Some(Ok(result))`.
272    ///
273    /// Note that if `Option<Result<T, E>>` is inconvenient for you,
274    /// and you wish this returned `Result<Option<T>, E>`, you may use
275    /// the built-in `transpose()` method to convert between them.
276    ///
277    /// ```
278    /// # use viaduct::Headers;
279    /// # fn main() -> Result<(), viaduct::Error> {
280    /// let mut h = Headers::new();
281    /// h.insert("Example", "1234")?.insert("Illegal", "abcd")?;
282    /// let v: Option<Result<i64, _>> = h.get_as("Example");
283    /// assert_eq!(v, Some(Ok(1234)));
284    /// assert_eq!(h.get_as::<i64, _>("Example"), Some(Ok(1234)));
285    /// assert_eq!(h.get_as::<i64, _>("Illegal"), Some("abcd".parse::<i64>()));
286    /// assert_eq!(h.get_as::<i64, _>("Something-Else"), None);
287    /// # Ok(())
288    /// # }
289    /// ```
290    pub fn get_as<T, S>(&self, name: S) -> Option<Result<T, <T as FromStr>::Err>>
291    where
292        T: FromStr,
293        S: PartialEq<HeaderName>,
294    {
295        self.get(name).map(str::parse)
296    }
297    /// Get the value of the header with the provided name, and
298    /// attempt to parse it using [`std::str::FromStr`].
299    ///
300    /// This is a variant of `get_as` that returns None on error,
301    /// intended to be used for cases where missing and invalid
302    /// headers should be treated the same. (With `get_as` this
303    /// requires `h.get_as(...).and_then(|r| r.ok())`, which is
304    /// somewhat opaque.
305    pub fn try_get<T, S>(&self, name: S) -> Option<T>
306    where
307        T: FromStr,
308        S: PartialEq<HeaderName>,
309    {
310        self.get(name).and_then(|val| val.parse::<T>().ok())
311    }
312
313    /// Get an iterator over the headers in no particular order.
314    ///
315    /// Note that we also implement IntoIterator.
316    pub fn iter(&self) -> <&Headers as IntoIterator>::IntoIter {
317        self.into_iter()
318    }
319}
320
321impl std::iter::IntoIterator for Headers {
322    type IntoIter = <Vec<Header> as IntoIterator>::IntoIter;
323    type Item = Header;
324    fn into_iter(self) -> Self::IntoIter {
325        self.headers.into_iter()
326    }
327}
328
329impl<'a> std::iter::IntoIterator for &'a Headers {
330    type IntoIter = <&'a [Header] as IntoIterator>::IntoIter;
331    type Item = &'a Header;
332    fn into_iter(self) -> Self::IntoIter {
333        self.headers[..].iter()
334    }
335}
336
337impl FromIterator<Header> for Headers {
338    fn from_iter<T>(iter: T) -> Self
339    where
340        T: IntoIterator<Item = Header>,
341    {
342        let mut v = iter.into_iter().collect::<Vec<Header>>();
343        v.sort_by(|a, b| a.name.cmp(&b.name));
344        v.reverse();
345        v.dedup_by(|a, b| a.name == b.name);
346        Headers { headers: v }
347    }
348}
349
350#[allow(clippy::implicit_hasher)] // https://github.com/rust-lang/rust-clippy/issues/3899
351impl From<Headers> for HashMap<String, String> {
352    fn from(headers: Headers) -> HashMap<String, String> {
353        headers
354            .into_iter()
355            .map(|h| (String::from(h.name), h.value))
356            .collect()
357    }
358}
359
360pub mod consts {
361    use super::name::HeaderName;
362    macro_rules! def_header_consts {
363        ($(($NAME:ident, $string:literal)),* $(,)?) => {
364            $(pub const $NAME: HeaderName = HeaderName(std::borrow::Cow::Borrowed($string));)*
365        };
366    }
367
368    macro_rules! headers {
369        ($(($NAME:ident, $string:literal)),* $(,)?) => {
370            def_header_consts!($(($NAME, $string)),*);
371            // Unused except for tests.
372            const _ALL: &[&str] = &[$($string),*];
373        };
374    }
375
376    // Predefined header names, for convenience.
377    // Feel free to add to these.
378    headers!(
379        (ACCEPT_ENCODING, "accept-encoding"),
380        (ACCEPT, "accept"),
381        (AUTHORIZATION, "authorization"),
382        (CONTENT_TYPE, "content-type"),
383        (ETAG, "etag"),
384        (IF_NONE_MATCH, "if-none-match"),
385        (USER_AGENT, "user-agent"),
386        // non-standard, but it's convenient to have these.
387        (RETRY_AFTER, "retry-after"),
388        (X_IF_UNMODIFIED_SINCE, "x-if-unmodified-since"),
389        (X_KEYID, "x-keyid"),
390        (X_LAST_MODIFIED, "x-last-modified"),
391        (X_TIMESTAMP, "x-timestamp"),
392        (X_WEAVE_NEXT_OFFSET, "x-weave-next-offset"),
393        (X_WEAVE_RECORDS, "x-weave-records"),
394        (X_WEAVE_TIMESTAMP, "x-weave-timestamp"),
395        (X_WEAVE_BACKOFF, "x-weave-backoff"),
396    );
397
398    #[test]
399    fn test_predefined() {
400        for &name in _ALL {
401            assert!(
402                HeaderName::new(name).is_ok(),
403                "Invalid header name in predefined header constants: {}",
404                name
405            );
406            assert_eq!(
407                name.to_ascii_lowercase(),
408                name,
409                "Non-lowercase name in predefined header constants: {}",
410                name
411            );
412        }
413    }
414}