Skip to main content

zsync_rs/
http.rs

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