panoramic_courier/
http.rs1use 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
8const MAX_HEAD_LEN: usize = 64 * 1024;
10
11pub(crate) const MAX_BODY_LEN: usize = 4 * 1024 * 1024;
16
17#[derive(Clone, Debug, Eq, PartialEq)]
19pub struct HttpResponse {
20 pub status: u16,
22
23 pub body: Vec<u8>,
25}
26
27pub 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
140struct Head {
142 len: usize,
144 status: u16,
145 content_length: Option<usize>,
146}
147
148impl Head {
149 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}