Skip to main content

zsync_rs/
http.rs

1//! HTTP transport: control files, byte ranges, and planning range requests.
2//!
3//! [`HttpClient`] fetches a control file and the byte ranges of a target. The
4//! free functions turn the block ranges a matcher still needs into byte
5//! ranges, and merge ranges separated by small gaps, since one request that
6//! re-downloads a few known bytes is usually cheaper than another round trip.
7
8use std::io::Read;
9use std::time::Duration;
10
11use crate::control::ControlFile;
12
13/// Why a fetch failed.
14#[derive(Debug, thiserror::Error)]
15pub enum HttpError {
16    /// The request failed, the server answered with an unexpected status, or
17    /// a fetched control file did not parse. The message says which.
18    #[error("HTTP error: {0}")]
19    Http(String),
20    /// Reading a response body failed.
21    #[error("IO error: {0}")]
22    Io(#[from] std::io::Error),
23    /// A URL could not be used. Not currently returned by this crate.
24    #[error("Invalid URL: {0}")]
25    InvalidUrl(String),
26    /// There was no URL to fetch from. Not currently returned by this crate.
27    #[error("No URLs available")]
28    NoUrls,
29}
30
31/// The body of one range response, capped at the length requested.
32///
33/// Returned by [`HttpClient::fetch_range_reader`].
34pub struct HttpRangeReader {
35    reader: Box<dyn std::io::Read + Send + Sync>,
36}
37
38impl std::io::Read for HttpRangeReader {
39    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
40        self.reader.read(buf)
41    }
42}
43
44/// Cap on establishing a connection, covering the TCP handshake and TLS
45/// setup but never the transfer that follows.
46///
47/// ureq applies no connect timeout of its own, which leaves an address that
48/// silently drops SYNs costing the kernel's full retry schedule, around two
49/// minutes each. A mirror redirect that lands on a host with several such
50/// addresses stalls for as long as it takes to exhaust them all, and the
51/// error raised at the end is an unhelpful synthetic "connection refused".
52/// ureq divides this budget across the resolved addresses, so the cap is
53/// generous enough that a distant mirror still gets several seconds.
54pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
55
56/// Cap on the DNS lookup, for the same reason as [`CONNECT_TIMEOUT`].
57///
58/// Deliberately the longer of the two. ureq attributes a timeout to whichever
59/// phase would have expired first, so an equal pair reports a connect failure
60/// as a resolve one and points whoever reads the error at the wrong thing.
61pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(30);
62
63/// HTTP transport for fetching control files and byte ranges.
64pub struct HttpClient {
65    agent: ureq::Agent,
66}
67
68impl Default for HttpClient {
69    fn default() -> Self {
70        Self::new()
71    }
72}
73
74impl HttpClient {
75    /// A client permitting plain HTTP, with a bound on reaching a host.
76    ///
77    /// zsync is routinely served over HTTP and across mirror redirects, so
78    /// the scheme policy is permissive on purpose. An embedder with a
79    /// stricter one, such as one that must refuse a downgrade to HTTP or
80    /// pin its own trust roots, should build an agent and pass it to
81    /// [`HttpClient::with_agent`] rather than relying on these.
82    ///
83    /// [`CONNECT_TIMEOUT`] and [`RESOLVE_TIMEOUT`] apply. Neither bounds the
84    /// transfer itself, so a mirror that trickles bytes for an hour is left
85    /// alone; they only cap how long a host that never answers can cost.
86    pub fn new() -> Self {
87        Self {
88            agent: ureq::Agent::config_builder()
89                .https_only(false)
90                .timeout_connect(Some(CONNECT_TIMEOUT))
91                .timeout_resolve(Some(RESOLVE_TIMEOUT))
92                .build()
93                .new_agent(),
94        }
95    }
96
97    /// A client using a caller-supplied agent.
98    ///
99    /// The agent carries the whole transport policy: TLS roots, whether a
100    /// redirect may downgrade to HTTP, timeouts and proxies. Supplying one
101    /// keeps that decision with the embedder, which is the only place that
102    /// knows what the transferred bytes are trusted for.
103    pub fn with_agent(agent: ureq::Agent) -> Self {
104        Self { agent }
105    }
106
107    /// Fetches and parses the control file at `url`.
108    ///
109    /// # Errors
110    ///
111    /// Returns [`HttpError::Http`] when the request fails or the response
112    /// does not parse as a control file.
113    pub fn fetch_control_file(&self, url: &str) -> Result<ControlFile, HttpError> {
114        let response = self
115            .agent
116            .get(url)
117            .call()
118            .map_err(|e| HttpError::Http(e.to_string()))?;
119
120        let mut reader = response.into_body().into_reader();
121        ControlFile::parse(&mut reader).map_err(|e| HttpError::Http(e.to_string()))
122    }
123
124    /// A reader over `start..=end` of `url`.
125    ///
126    /// The reader is capped at the requested length. Without that cap the
127    /// origin decides how much the client reads: a response longer than
128    /// the range is consumed in full, and callers that accumulate it, such
129    /// as block assembly, grow a buffer to match. Bytes past the range
130    /// were never asked for and are of no use, so they are not read.
131    ///
132    /// A `200 OK` is accepted as well as `206 Partial Content`. A server that
133    /// ignores `Range` sends the file from its first byte, so for a range
134    /// that does not start at zero the reader yields the wrong bytes, and it
135    /// falls to the caller's block checksums to reject them.
136    ///
137    /// # Errors
138    ///
139    /// Returns [`HttpError::Http`] when the request fails or the status is
140    /// neither 200 nor 206.
141    pub fn fetch_range_reader(
142        &self,
143        url: &str,
144        start: u64,
145        end: u64,
146    ) -> Result<HttpRangeReader, HttpError> {
147        let range_header = format!("bytes={}-{}", start, end);
148        let requested = end.saturating_sub(start).saturating_add(1);
149
150        let response = self
151            .agent
152            .get(url)
153            .header("Range", &range_header)
154            .call()
155            .map_err(|e| HttpError::Http(e.to_string()))?;
156
157        let status = response.status();
158        if status != 206 && status != 200 {
159            return Err(HttpError::Http(format!(
160                "Expected 206 Partial Content, got {}",
161                status
162            )));
163        }
164
165        Ok(HttpRangeReader {
166            reader: Box::new(response.into_body().into_reader().take(requested)),
167        })
168    }
169
170    /// Fetches `start..=end` of `url` into memory.
171    ///
172    /// The same cap and status handling as [`Self::fetch_range_reader`]
173    /// apply.
174    ///
175    /// # Errors
176    ///
177    /// Returns [`HttpError::Http`] when the request fails and
178    /// [`HttpError::Io`] when reading the body fails.
179    pub fn fetch_range(&self, url: &str, start: u64, end: u64) -> Result<Vec<u8>, HttpError> {
180        let mut reader = self.fetch_range_reader(url, start, end)?;
181        let mut buf = Vec::new();
182        reader.read_to_end(&mut buf)?;
183        Ok(buf)
184    }
185
186    /// Fetches each inclusive range in `ranges`, one request at a time.
187    ///
188    /// Each body is paired with its start offset rounded down to a multiple
189    /// of `blocksize`. The ranges are expected to start on a block boundary,
190    /// as those from [`byte_ranges_from_block_ranges`] do; otherwise the
191    /// offset names a point before the body's first byte.
192    ///
193    /// # Errors
194    ///
195    /// Stops at and returns the first error from [`Self::fetch_range`].
196    pub fn fetch_ranges(
197        &self,
198        url: &str,
199        ranges: &[(u64, u64)],
200        blocksize: usize,
201    ) -> Result<Vec<(u64, Vec<u8>)>, HttpError> {
202        let mut results = Vec::new();
203
204        for &(start, end) in ranges {
205            let data = self.fetch_range(url, start, end)?;
206            let aligned_start = (start / blocksize as u64) * blocksize as u64;
207            results.push((aligned_start, data));
208        }
209
210        Ok(results)
211    }
212}
213
214/// Default gap threshold for range merging (256 KiB, same as zsync2).
215pub const DEFAULT_RANGE_GAP_THRESHOLD: u64 = 256 * 1024;
216
217/// Merge byte ranges to minimize HTTP requests.
218///
219/// `ranges` are inclusive and sorted by start, without overlap. Two neighbours
220/// separated by at most `gap_threshold` bytes become one range that also
221/// covers the gap, so a threshold of zero merges only ranges that touch.
222pub fn merge_byte_ranges(ranges: &[(u64, u64)], gap_threshold: u64) -> Vec<(u64, u64)> {
223    if ranges.len() <= 1 {
224        return ranges.to_vec();
225    }
226
227    let mut merged = vec![ranges[0]];
228    for &(start, end) in &ranges[1..] {
229        let last = merged.last_mut().unwrap();
230        let gap = start.saturating_sub(last.1 + 1);
231        if gap <= gap_threshold {
232            last.1 = end;
233        } else {
234            merged.push((start, end));
235        }
236    }
237    merged
238}
239
240/// Converts block ranges into the byte ranges that hold them.
241///
242/// Each block range is half-open, from its first block to one past its last,
243/// as [`BlockMatcher::needed_block_ranges`](crate::BlockMatcher::needed_block_ranges)
244/// returns them. Each byte range is inclusive, ready for a `Range` header, and
245/// the last one is clamped to `file_length` so a short final block is not
246/// requested past the end of the file.
247pub fn byte_ranges_from_block_ranges(
248    block_ranges: &[(usize, usize)],
249    blocksize: usize,
250    file_length: u64,
251) -> Vec<(u64, u64)> {
252    block_ranges
253        .iter()
254        .map(|&(start_block, end_block)| {
255            let start = start_block as u64 * blocksize as u64;
256            let end =
257                ((end_block as u64 * blocksize as u64).saturating_sub(1)).min(file_length - 1);
258            (start, end)
259        })
260        .collect()
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    /// A server that answers any request with far more data than asked
268    /// for, which is what a hostile or broken origin does.
269    fn overlong_server(body_len: usize) -> String {
270        use std::io::Write;
271        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
272        let addr = listener.local_addr().unwrap();
273        std::thread::spawn(move || {
274            if let Ok((mut sock, _)) = listener.accept() {
275                let mut req = [0u8; 1024];
276                let _ = std::io::Read::read(&mut sock, &mut req);
277                let hdr = format!(
278                    "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-1023/{}\r\nContent-Length: {}\r\n\r\n",
279                    body_len, body_len
280                );
281                let _ = sock.write_all(hdr.as_bytes());
282                let chunk = vec![0u8; 64 * 1024];
283                let mut sent = 0;
284                while sent < body_len {
285                    let n = chunk.len().min(body_len - sent);
286                    if sock.write_all(&chunk[..n]).is_err() {
287                        break;
288                    }
289                    sent += n;
290                }
291            }
292        });
293        format!("http://{}/f", addr)
294    }
295
296    #[test]
297    fn a_range_response_is_capped_at_what_was_requested() {
298        // 1 KiB asked for, 8 MiB offered. Accepting the surplus lets any
299        // origin decide how much memory the client spends.
300        let url = overlong_server(8 * 1024 * 1024);
301        let client = HttpClient::new();
302        let data = client.fetch_range(&url, 0, 1023).expect("fetch");
303        assert_eq!(
304            data.len(),
305            1024,
306            "a range response must be capped at the requested length"
307        );
308    }
309
310    #[test]
311    fn the_default_client_bounds_reaching_a_host_but_not_the_transfer() {
312        let timeouts = HttpClient::new().agent.config().timeouts();
313
314        // Unbounded, a host that drops SYNs costs the kernel's full retry
315        // schedule per resolved address, minutes at a time.
316        assert_eq!(timeouts.connect, Some(CONNECT_TIMEOUT));
317        assert_eq!(timeouts.resolve, Some(RESOLVE_TIMEOUT));
318
319        // Deliberately unbounded: mirrors serving a multi-hundred-megabyte
320        // image are often slow, and a cap here would abort a healthy but
321        // sluggish transfer.
322        assert_eq!(timeouts.global, None);
323        assert_eq!(timeouts.per_call, None);
324        assert_eq!(timeouts.recv_body, None);
325    }
326
327    #[test]
328    fn a_supplied_agent_carries_its_own_policy() {
329        // The point of `with_agent` is that the embedder's policy reaches
330        // the transfer. A client built with an HTTPS-only agent must refuse
331        // a plain-HTTP URL, where the default client would allow it.
332        let strict = HttpClient::with_agent(
333            ureq::Agent::config_builder()
334                .https_only(true)
335                .build()
336                .new_agent(),
337        );
338        let err = strict
339            .fetch_control_file("http://127.0.0.1:1/nothing.zsync")
340            .expect_err("an HTTPS-only agent must refuse a plain-HTTP URL");
341        let msg = err.to_string();
342        assert!(
343            msg.to_lowercase().contains("http"),
344            "expected a scheme rejection, got: {msg}"
345        );
346    }
347
348    #[test]
349    fn test_byte_ranges_from_block_ranges() {
350        let block_ranges = vec![(0, 2), (4, 6)];
351        let byte_ranges = byte_ranges_from_block_ranges(&block_ranges, 1024, 10000);
352        assert_eq!(byte_ranges, vec![(0, 2047), (4096, 6143)]);
353    }
354
355    #[test]
356    fn test_byte_ranges_clamped_to_file_length() {
357        let block_ranges = vec![(9, 10)];
358        let byte_ranges = byte_ranges_from_block_ranges(&block_ranges, 1024, 9500);
359        assert_eq!(byte_ranges, vec![(9216, 9499)]);
360    }
361}