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