Skip to main content

hyper/
headers.rs

1#[cfg(all(feature = "client", feature = "http1"))]
2use bytes::BytesMut;
3use http::header::HeaderValue;
4#[cfg(all(feature = "http2", feature = "client"))]
5use http::Method;
6#[cfg(any(feature = "client", all(feature = "server", feature = "http2")))]
7use http::{
8    header::{ValueIter, CONTENT_LENGTH},
9    HeaderMap,
10};
11
12#[cfg(feature = "http1")]
13pub(super) fn connection_keep_alive(value: &HeaderValue) -> bool {
14    connection_has(value, "keep-alive")
15}
16
17#[cfg(feature = "http1")]
18pub(super) fn connection_close(value: &HeaderValue) -> bool {
19    connection_has(value, "close")
20}
21
22#[cfg(feature = "http1")]
23fn connection_has(value: &HeaderValue, needle: &str) -> bool {
24    if let Ok(s) = value.to_str() {
25        for val in s.split(',') {
26            if val.trim().eq_ignore_ascii_case(needle) {
27                return true;
28            }
29        }
30    }
31    false
32}
33
34#[cfg(all(feature = "http1", feature = "server"))]
35pub(super) fn content_length_parse(value: &HeaderValue) -> Option<u64> {
36    from_digits(value.as_bytes())
37}
38
39#[cfg(any(feature = "client", all(feature = "server", feature = "http2")))]
40pub(super) fn content_length_parse_all(headers: &HeaderMap) -> Option<u64> {
41    content_length_parse_all_values(headers.get_all(CONTENT_LENGTH).into_iter())
42}
43
44#[cfg(any(feature = "client", all(feature = "server", feature = "http2")))]
45pub(super) fn content_length_parse_all_values(values: ValueIter<'_, HeaderValue>) -> Option<u64> {
46    // If multiple Content-Length headers were sent, everything can still
47    // be alright if they all contain the same value, and all parse
48    // correctly. If not, then it's an error.
49
50    let mut content_length: Option<u64> = None;
51    for h in values {
52        if let Ok(line) = h.to_str() {
53            for v in line.split(',') {
54                let n = from_digits(v.trim().as_bytes())?;
55
56                if content_length.is_none() {
57                    content_length = Some(n);
58                } else if content_length != Some(n) {
59                    return None;
60                }
61            }
62        } else {
63            return None;
64        }
65    }
66
67    content_length
68}
69
70fn from_digits(bytes: &[u8]) -> Option<u64> {
71    // cannot use FromStr for u64, since it allows a signed prefix
72    let mut result = 0u64;
73    const RADIX: u64 = 10;
74
75    if bytes.is_empty() {
76        return None;
77    }
78
79    for &b in bytes {
80        // can't use char::to_digit, since we haven't verified these bytes
81        // are utf-8.
82        match b {
83            b'0'..=b'9' => {
84                result = result.checked_mul(RADIX)?;
85                result = result.checked_add(u64::from(b - b'0'))?;
86            }
87            _ => {
88                // not a DIGIT, get outta here!
89                return None;
90            }
91        }
92    }
93
94    Some(result)
95}
96
97#[cfg(all(feature = "http2", feature = "client"))]
98pub(super) fn method_has_defined_payload_semantics(method: &Method) -> bool {
99    !matches!(
100        *method,
101        Method::GET | Method::HEAD | Method::DELETE | Method::CONNECT
102    )
103}
104
105#[cfg(feature = "http2")]
106pub(super) fn set_content_length_if_missing(headers: &mut HeaderMap, len: u64) {
107    headers
108        .entry(CONTENT_LENGTH)
109        .or_insert_with(|| HeaderValue::from(len));
110}
111
112#[cfg(all(feature = "client", feature = "http1"))]
113pub(super) fn transfer_encoding_is_chunked(headers: &HeaderMap) -> bool {
114    is_chunked(headers.get_all(http::header::TRANSFER_ENCODING).into_iter())
115}
116
117#[cfg(all(feature = "client", feature = "http1"))]
118pub(super) fn is_chunked(mut encodings: ValueIter<'_, HeaderValue>) -> bool {
119    // chunked must always be the last encoding, according to spec
120    if let Some(line) = encodings.next_back() {
121        return is_chunked_(line);
122    }
123
124    false
125}
126
127#[cfg(feature = "http1")]
128pub(super) fn is_chunked_(value: &HeaderValue) -> bool {
129    // chunked must always be the last encoding, according to spec
130    if let Ok(s) = value.to_str() {
131        if let Some(encoding) = s.rsplit(',').next() {
132            return encoding.trim().eq_ignore_ascii_case("chunked");
133        }
134    }
135
136    false
137}
138
139#[cfg(all(feature = "client", feature = "http1"))]
140pub(super) fn add_chunked(mut entry: http::header::OccupiedEntry<'_, HeaderValue>) {
141    const CHUNKED: &str = "chunked";
142
143    if let Some(line) = entry.iter_mut().next_back() {
144        // + 2 for ", "
145        let new_cap = line.as_bytes().len() + CHUNKED.len() + 2;
146        let mut buf = BytesMut::with_capacity(new_cap);
147        buf.extend_from_slice(line.as_bytes());
148        buf.extend_from_slice(b", ");
149        buf.extend_from_slice(CHUNKED.as_bytes());
150
151        *line = HeaderValue::from_maybe_shared(buf.freeze())
152            .expect("original header value plus ascii is valid");
153        return;
154    }
155
156    entry.insert(HeaderValue::from_static(CHUNKED));
157}