Skip to main content

utf8_forge/
fetcher.rs

1// Copyright 2026 houseme
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Optional remote download.
16//!
17//! Compiled only with the `remote` feature (default). Reuses the exact same
18//! `detect()` / `transcode()` pipeline as the local path — only the source of
19//! `raw_bytes` changes. Downloaded content is treated as untrusted text:
20//! strict decoding rejects malformed byte sequences, no shell is executed,
21//! no recursive link following.
22
23use std::fs;
24use std::io::{Read, Seek, Write};
25use std::path::{Path, PathBuf};
26use std::time::Duration;
27
28use crate::error::ForgeError;
29use crate::writer::unique_suffix;
30
31/// Wall-clock budget for the whole download body. The client timeout fires
32/// per read, so a slow-but-steady trickle would otherwise never trip it.
33const DOWNLOAD_BUDGET: std::time::Duration = std::time::Duration::from_secs(120);
34
35/// Fetch `url`, capped by `max_size`, streaming the body to a temp file.
36///
37/// `Content-Length` is checked before reading when present; the cap is then
38/// enforced per chunk while streaming, so an oversized body is aborted
39/// mid-download (temp deleted) instead of being buffered in full. At most
40/// `max_size` bytes are ever held in memory (the final read-back). Redirects
41/// are limited to 5; the connect timeout is 30 s and the whole download must
42/// finish within a 120 s wall-clock budget (enforced here, because the
43/// client's timeout applies per read). Bodyless success responses
44/// (204/304/3xx without a location) are refused.
45pub fn fetch_bytes(url: &str, max_size: u64) -> Result<Vec<u8>, ForgeError> {
46    let client = reqwest::blocking::Client::builder()
47        .connect_timeout(Duration::from_secs(30))
48        .timeout(Duration::from_secs(120))
49        .redirect(reqwest::redirect::Policy::limited(5))
50        .build()
51        .map_err(|e| ForgeError::Fetch(format!("client build failed: {e}")))?;
52
53    let mut resp = client
54        .get(url)
55        .send()
56        .map_err(|e| ForgeError::Fetch(format!("request failed: {e}")))?
57        .error_for_status()
58        .map_err(|e| ForgeError::Fetch(format!("http status: {e}")))?;
59
60    if let Some(len) = resp.content_length()
61        && len > max_size
62    {
63        return Err(ForgeError::TooLarge {
64            size: len,
65            max: max_size,
66        });
67    }
68
69    // A bodyless success carries no content to transcode — materializing it
70    // would silently truncate the output with a zero-byte file. reqwest only
71    // rejects 4xx/5xx, and a 3xx without a Location header lands here as a
72    // final response.
73    let status = resp.status();
74    if status.is_redirection()
75        || status == reqwest::StatusCode::NO_CONTENT
76        || status == reqwest::StatusCode::NOT_MODIFIED
77    {
78        return Err(ForgeError::Fetch(format!(
79            "response has no body (HTTP {status}); nothing to fetch"
80        )));
81    }
82
83    // Stream the body into a unique temp file, enforcing the cap per chunk:
84    // an oversized payload never accumulates in memory.
85    let tmp: PathBuf = std::env::temp_dir().join(format!(".utf8-forge-fetch-{}", unique_suffix()));
86    read_body_to_temp(&mut resp, max_size, &tmp)
87}
88
89/// Spool a bounded body through an exclusively created temporary file.
90/// Creation failures preserve any existing path. Once created, the file is
91/// closed before cleanup on both success and error, including on Windows.
92fn read_body_to_temp(
93    reader: &mut impl Read,
94    max_size: u64,
95    tmp: &Path,
96) -> Result<Vec<u8>, ForgeError> {
97    let file = fs::OpenOptions::new()
98        .read(true)
99        .write(true)
100        .create_new(true)
101        .open(tmp)
102        .map_err(|e| ForgeError::Fetch(format!("create temp file failed: {e}")))?;
103
104    let result = (|| {
105        // Move the handle into this scope so every return closes it before
106        // removal. Reading back through this handle avoids reopening a path
107        // that another process could have replaced after creation.
108        let mut file = file;
109        let started = std::time::Instant::now();
110        let mut total: u64 = 0;
111        let mut buf = [0u8; 8192];
112        loop {
113            // The client timeout fires per read (a slow-but-steady trickle
114            // never trips it), so the tool enforces its own wall-clock
115            // budget on the whole body.
116            if started.elapsed() > DOWNLOAD_BUDGET {
117                return Err(ForgeError::Fetch(format!(
118                    "download exceeded the {} s budget",
119                    DOWNLOAD_BUDGET.as_secs()
120                )));
121            }
122            let n = reader
123                .read(&mut buf)
124                .map_err(|e| ForgeError::Fetch(format!("read body failed: {e}")))?;
125            if n == 0 {
126                break;
127            }
128            total += n as u64;
129            if total > max_size {
130                return Err(ForgeError::TooLarge {
131                    size: total,
132                    max: max_size,
133                });
134            }
135            file.write_all(&buf[..n])
136                .map_err(|e| ForgeError::Fetch(format!("write temp file failed: {e}")))?;
137        }
138        file.rewind()
139            .map_err(|e| ForgeError::Fetch(format!("read temp file failed: {e}")))?;
140        let mut body = Vec::new();
141        file.take(total)
142            .read_to_end(&mut body)
143            .map_err(|e| ForgeError::Fetch(format!("read temp file failed: {e}")))?;
144        Ok(body)
145    })();
146    let _ = fs::remove_file(tmp);
147    result
148}
149
150/// Derive the output path from the URL when `--output` is omitted:
151///
152/// - last non-empty path segment with an extension is kept verbatim
153///   (`.../legacy.cpp` → `legacy.cpp`);
154/// - a segment without an extension gets `.utf8` appended (`.../foo` → `foo.utf8`);
155/// - no usable segment → `download.utf8`.
156pub fn derive_output_path(url: &str) -> PathBuf {
157    // Scan backwards so a trailing slash (`.../dir/`) cannot shadow the real
158    // last segment with an empty one.
159    let segment = reqwest::Url::parse(url).ok().and_then(|u| {
160        u.path_segments()?
161            .rev()
162            .find(|s| !s.is_empty())
163            .map(str::to_owned)
164    });
165
166    match segment {
167        Some(seg) if has_extension(&seg) => PathBuf::from(seg),
168        Some(seg) => PathBuf::from(format!("{seg}.utf8")),
169        None => PathBuf::from("download.utf8"),
170    }
171}
172
173/// True when the last URL segment looks like a filename with an extension.
174fn has_extension(segment: &str) -> bool {
175    std::path::Path::new(segment)
176        .extension()
177        .map(|e| !e.is_empty())
178        .unwrap_or(false)
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use std::io;
185
186    #[test]
187    fn streaming_temp_is_removed_after_exact_limit_readback() {
188        let dir = tempfile::tempdir().unwrap();
189        let tmp = dir.path().join("fetch.tmp");
190        let body = vec![b'x'; 8192 + 13];
191        assert_eq!(
192            read_body_to_temp(&mut body.as_slice(), body.len() as u64, &tmp).unwrap(),
193            body
194        );
195        assert!(!tmp.exists());
196    }
197
198    #[test]
199    fn streaming_temp_is_removed_after_size_limit_failure() {
200        let dir = tempfile::tempdir().unwrap();
201        let tmp = dir.path().join("fetch.tmp");
202        // The first chunk is persisted before the second exceeds the cap.
203        let body = vec![b'x'; 8193];
204        assert!(matches!(
205            read_body_to_temp(&mut body.as_slice(), 8192, &tmp),
206            Err(ForgeError::TooLarge {
207                size: 8193,
208                max: 8192
209            })
210        ));
211        assert!(!tmp.exists());
212    }
213
214    #[test]
215    fn streaming_temp_accepts_empty_body_with_zero_limit() {
216        let dir = tempfile::tempdir().unwrap();
217        let tmp = dir.path().join("fetch.tmp");
218        assert!(
219            read_body_to_temp(&mut b"".as_slice(), 0, &tmp)
220                .unwrap()
221                .is_empty()
222        );
223        assert!(!tmp.exists());
224        assert!(matches!(
225            read_body_to_temp(&mut b"x".as_slice(), 0, &tmp),
226            Err(ForgeError::TooLarge { size: 1, max: 0 })
227        ));
228        assert!(!tmp.exists());
229    }
230
231    #[test]
232    fn streaming_temp_is_removed_after_body_read_failure() {
233        struct FailingReader;
234
235        impl Read for FailingReader {
236            fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
237                Err(io::Error::other("injected body read failure"))
238            }
239        }
240
241        let dir = tempfile::tempdir().unwrap();
242        let tmp = dir.path().join("fetch.tmp");
243        let mut reader = b"partial body".as_slice().chain(FailingReader);
244        let error = read_body_to_temp(&mut reader, 1024, &tmp).unwrap_err();
245        assert!(
246            matches!(error, ForgeError::Fetch(ref message) if message.starts_with("read body failed:"))
247        );
248        assert!(!tmp.exists());
249    }
250
251    #[test]
252    fn streaming_temp_collision_preserves_existing_file() {
253        let dir = tempfile::tempdir().unwrap();
254        let tmp = dir.path().join("fetch.tmp");
255        fs::write(&tmp, b"original").unwrap();
256        let mut reader = b"download".as_slice();
257        let error = read_body_to_temp(&mut reader, 1024, &tmp).unwrap_err();
258        assert!(
259            matches!(error, ForgeError::Fetch(ref message) if message.starts_with("create temp file failed:"))
260        );
261        assert_eq!(fs::read(&tmp).unwrap(), b"original");
262        assert_eq!(
263            reader, b"download",
264            "the body must not be read after creation fails"
265        );
266    }
267
268    #[cfg(unix)]
269    #[test]
270    fn streaming_temp_collision_preserves_symlink_and_target() {
271        let dir = tempfile::tempdir().unwrap();
272        let tmp = dir.path().join("fetch.tmp");
273        let target = dir.path().join("original.cpp");
274        fs::write(&target, b"original").unwrap();
275        std::os::unix::fs::symlink(&target, &tmp).unwrap();
276        assert!(read_body_to_temp(&mut b"download".as_slice(), 1024, &tmp).is_err());
277        assert!(fs::symlink_metadata(&tmp).unwrap().file_type().is_symlink());
278        assert_eq!(fs::read(&target).unwrap(), b"original");
279    }
280
281    #[test]
282    fn derive_keeps_extensioned_segments() {
283        assert_eq!(
284            derive_output_path("https://example.com/data/legacy.cpp"),
285            PathBuf::from("legacy.cpp")
286        );
287    }
288
289    #[test]
290    fn derive_appends_utf8_without_extension() {
291        assert_eq!(
292            derive_output_path("https://example.com/foo"),
293            PathBuf::from("foo.utf8")
294        );
295    }
296
297    #[test]
298    fn derive_falls_back_when_no_segment() {
299        assert_eq!(
300            derive_output_path("https://example.com/"),
301            PathBuf::from("download.utf8")
302        );
303        assert_eq!(
304            derive_output_path("not a url"),
305            PathBuf::from("download.utf8")
306        );
307    }
308
309    #[test]
310    fn derive_ignores_query_string() {
311        assert_eq!(
312            derive_output_path("https://example.com/a.cpp?raw=1"),
313            PathBuf::from("a.cpp")
314        );
315    }
316
317    #[test]
318    fn derive_treats_trailing_dot_as_missing_extension() {
319        assert_eq!(
320            derive_output_path("https://example.com/foo."),
321            PathBuf::from("foo..utf8")
322        );
323    }
324
325    #[test]
326    fn derive_skips_trailing_slash_segments() {
327        // A trailing slash yields an empty last segment; the real last
328        // non-empty segment wins instead of falling through to the fallback.
329        assert_eq!(
330            derive_output_path("https://example.com/a/dir.txt/"),
331            PathBuf::from("dir.txt")
332        );
333        assert_eq!(
334            derive_output_path("https://example.com/a/noext/"),
335            PathBuf::from("noext.utf8")
336        );
337    }
338}