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, 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    let cleanup = |p: &Path| {
67        let _ = fs::remove_file(p);
68    };
69    let mut file = fs::File::create(&tmp)
70        .map_err(|e| ForgeError::Fetch(format!("create temp file failed: {e}")))?;
71    let mut total: u64 = 0;
72    let mut buf = [0u8; 8192];
73    loop {
74        match resp.read(&mut buf) {
75            Ok(0) => break,
76            Ok(n) => {
77                total += n as u64;
78                if total > max_size {
79                    cleanup(&tmp);
80                    return Err(ForgeError::TooLarge {
81                        size: total,
82                        max: max_size,
83                    });
84                }
85                if let Err(e) = file.write_all(&buf[..n]) {
86                    cleanup(&tmp);
87                    return Err(ForgeError::Fetch(format!("write temp file failed: {e}")));
88                }
89            }
90            Err(e) => {
91                cleanup(&tmp);
92                return Err(ForgeError::Fetch(format!("read body failed: {e}")));
93            }
94        }
95    }
96    // Defense-in-depth: the per-chunk check already guarantees this.
97    if total > max_size {
98        cleanup(&tmp);
99        return Err(ForgeError::TooLarge {
100            size: total,
101            max: max_size,
102        });
103    }
104    let body = match fs::read(&tmp) {
105        Ok(bytes) => bytes,
106        Err(e) => {
107            cleanup(&tmp);
108            return Err(ForgeError::Fetch(format!("read temp file failed: {e}")));
109        }
110    };
111    cleanup(&tmp);
112    Ok(body)
113}
114
115/// Derive the output path from the URL when `--output` is omitted:
116///
117/// - last non-empty path segment with an extension is kept verbatim
118///   (`.../legacy.cpp` → `legacy.cpp`);
119/// - a segment without an extension gets `.utf8` appended (`.../foo` → `foo.utf8`);
120/// - no usable segment → `download.utf8`.
121pub fn derive_output_path(url: &str) -> PathBuf {
122    let segment = reqwest::Url::parse(url).ok().and_then(|u| {
123        u.path_segments()?
124            .next_back()
125            .map(str::to_owned)
126            .filter(|s| !s.is_empty())
127    });
128
129    match segment {
130        Some(seg) if has_extension(&seg) => PathBuf::from(seg),
131        Some(seg) => PathBuf::from(format!("{seg}.utf8")),
132        None => PathBuf::from("download.utf8"),
133    }
134}
135
136/// True when the last URL segment looks like a filename with an extension.
137fn has_extension(segment: &str) -> bool {
138    std::path::Path::new(segment)
139        .extension()
140        .map(|e| !e.is_empty())
141        .unwrap_or(false)
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn derive_keeps_extensioned_segments() {
150        assert_eq!(
151            derive_output_path("https://example.com/data/legacy.cpp"),
152            PathBuf::from("legacy.cpp")
153        );
154    }
155
156    #[test]
157    fn derive_appends_utf8_without_extension() {
158        assert_eq!(
159            derive_output_path("https://example.com/foo"),
160            PathBuf::from("foo.utf8")
161        );
162    }
163
164    #[test]
165    fn derive_falls_back_when_no_segment() {
166        assert_eq!(
167            derive_output_path("https://example.com/"),
168            PathBuf::from("download.utf8")
169        );
170        assert_eq!(
171            derive_output_path("not a url"),
172            PathBuf::from("download.utf8")
173        );
174    }
175
176    #[test]
177    fn derive_ignores_query_string() {
178        assert_eq!(
179            derive_output_path("https://example.com/a.cpp?raw=1"),
180            PathBuf::from("a.cpp")
181        );
182    }
183
184    #[test]
185    fn derive_treats_trailing_dot_as_missing_extension() {
186        assert_eq!(
187            derive_output_path("https://example.com/foo."),
188            PathBuf::from("foo..utf8")
189        );
190    }
191}