Skip to main content

panoramic_courier/
http.rs

1use std::time::Duration;
2
3use snafu::ResultExt as _;
4use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
5
6use crate::{net, Address, Error, InvalidPathSnafu, MalformedResponseSnafu, TargetSnafu, UnsupportedSnafu};
7
8/// The largest response head the courier reads before giving up on finding its end.
9const MAX_HEAD_LEN: usize = 64 * 1024;
10
11/// The largest response body the courier reads.
12///
13/// Readiness and status checks answer with far less. The cap bounds the memory a server that never stops sending can
14/// take.
15pub(crate) const MAX_BODY_LEN: usize = 4 * 1024 * 1024;
16
17/// A response to [`http_get`].
18#[derive(Clone, Debug, Eq, PartialEq)]
19pub struct HttpResponse {
20    /// The status code.
21    pub status: u16,
22
23    /// The body, exactly as received.
24    pub body: Vec<u8>,
25}
26
27/// Makes one plain-HTTP `GET` request for `path` at an `http` address.
28///
29/// The request is HTTP/1.0, so the server answers without chunked encoding and closes the connection after the
30/// response. The body ends at `Content-Length` when the response has one, at the head for a 204 or 304, and at the end
31/// of the connection otherwise. A response with a `Transfer-Encoding` other than `identity`, or with a body over the courier's limit of a few MiB,
32/// is malformed.
33///
34/// `limit` bounds the call, but a name lookup it cuts short keeps running on its blocking thread until the resolver
35/// answers.
36///
37/// # Errors
38///
39/// Fails with [`Error::Unsupported`] for any address but `http`, and [`Error::InvalidPath`] for a path that does not
40/// start with `/` or holds whitespace. Fails with [`Error::Target`] when the connection, the write or a read fails,
41/// [`Error::MalformedResponse`] when the answer is not an HTTP/1 response, and [`Error::TimedOut`] when `limit`
42/// passes.
43pub async fn http_get(address: &Address, path: &str, limit: Duration) -> Result<HttpResponse, Error> {
44    let Address::Http(host_port) = address else {
45        return UnsupportedSnafu {
46            operation: "http",
47            address: address.clone(),
48            reason: "http requests go to http addresses only",
49        }
50        .fail();
51    };
52    if !path.starts_with('/') || path.contains(char::is_whitespace) {
53        return InvalidPathSnafu { path }.fail();
54    }
55    let context = |action| TargetSnafu {
56        action,
57        target: address.to_string(),
58    };
59    net::within("http", address, limit, async {
60        let mut stream = net::connect_tcp(host_port).await?;
61        let request =
62            format!("GET {path} HTTP/1.0\r\nHost: {host_port}\r\nUser-Agent: panoramic-courier\r\nAccept: */*\r\n\r\n");
63        stream
64            .write_all(request.as_bytes())
65            .await
66            .with_context(|_| context("send a request to"))?;
67
68        let mut received = Vec::new();
69        let mut head: Option<Head> = None;
70        loop {
71            received.reserve(8 * 1024);
72            let n = stream
73                .read_buf(&mut received)
74                .await
75                .with_context(|_| context("read a response from"))?;
76            if head.is_none() {
77                head = Head::parse(&received).map_err(|reason| malformed(address, reason))?;
78            }
79            match &head {
80                None if n == 0 => return Err(malformed(address, "the connection closed inside the response head")),
81                None if received.len() > MAX_HEAD_LEN => {
82                    return Err(malformed(address, "the response head is longer than 64 KiB"))
83                }
84                None => {}
85                Some(head) if matches!(head.status, 204 | 304) => {
86                    received.truncate(head.len);
87                    break;
88                }
89                Some(head) => {
90                    let body_len = received.len() - head.len;
91                    match head.content_length {
92                        Some(content_length) if content_length > MAX_BODY_LEN => {
93                            return Err(malformed(
94                                address,
95                                format!(
96                                    "Content-Length {content_length} is over the {} MiB limit",
97                                    MAX_BODY_LEN >> 20
98                                ),
99                            ))
100                        }
101                        Some(content_length) if body_len >= content_length => {
102                            received.truncate(head.len + content_length);
103                            break;
104                        }
105                        Some(content_length) if n == 0 => {
106                            return Err(malformed(
107                                address,
108                                format!("the body ended after {body_len} of {content_length} bytes"),
109                            ))
110                        }
111                        None if body_len > MAX_BODY_LEN => {
112                            return Err(malformed(
113                                address,
114                                format!("the body is over the {} MiB limit", MAX_BODY_LEN >> 20),
115                            ))
116                        }
117                        None if n == 0 => break,
118                        Some(_) | None => {}
119                    }
120                }
121            }
122        }
123        let head = head.expect("the loop ends only once the head is parsed");
124        Ok(HttpResponse {
125            status: head.status,
126            body: received.split_off(head.len),
127        })
128    })
129    .await
130}
131
132fn malformed(address: &Address, reason: impl Into<String>) -> Error {
133    MalformedResponseSnafu {
134        address: address.clone(),
135        reason: reason.into(),
136    }
137    .build()
138}
139
140/// The parts of a response head the courier uses.
141struct Head {
142    /// The length of the head, including the blank line that ends it.
143    len: usize,
144    status: u16,
145    content_length: Option<usize>,
146}
147
148impl Head {
149    /// Parses the head at the start of `received`, or returns `None` if it has not ended yet.
150    fn parse(received: &[u8]) -> Result<Option<Self>, String> {
151        let Some(end) = received.windows(4).position(|window| window == b"\r\n\r\n") else {
152            return Ok(None);
153        };
154        let text = String::from_utf8_lossy(&received[..end]);
155        let mut lines = text.split("\r\n");
156        let status_line = lines.next().unwrap_or_default();
157        let mut parts = status_line.split(' ');
158        let status = match (parts.next(), parts.next()) {
159            (Some(version), Some(code))
160                if version.len() == 8
161                    && version.starts_with("HTTP/1.")
162                    && version.as_bytes()[7].is_ascii_digit()
163                    && code.len() == 3
164                    && code.bytes().all(|byte| byte.is_ascii_digit()) =>
165            {
166                code.parse::<u16>().ok().filter(|code| (100..=599).contains(code))
167            }
168            _ => None,
169        }
170        .ok_or_else(|| format!("'{status_line}' is not an HTTP/1 status line"))?;
171
172        let mut content_length = None;
173        for line in lines {
174            let (name, value) = line
175                .split_once(':')
176                .ok_or_else(|| format!("'{line}' is not a header"))?;
177            if name.eq_ignore_ascii_case("content-length") {
178                let value = value.trim();
179                let length = value
180                    .parse::<usize>()
181                    .map_err(|_| format!("Content-Length '{value}' is not a number"))?;
182                if content_length.is_some_and(|previous| previous != length) {
183                    return Err("conflicting Content-Length headers".to_string());
184                }
185                content_length = Some(length);
186            } else if name.eq_ignore_ascii_case("transfer-encoding") && !value.trim().eq_ignore_ascii_case("identity") {
187                return Err(format!("Transfer-Encoding '{}' is not supported", value.trim()));
188            }
189        }
190        Ok(Some(Self {
191            len: end + 4,
192            status,
193            content_length,
194        }))
195    }
196}