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