1use 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
31fn 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
45const DOWNLOAD_BUDGET: std::time::Duration = std::time::Duration::from_secs(120);
48
49pub 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 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 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
108fn 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 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 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
169pub fn derive_output_path(url: &str) -> PathBuf {
176 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
192fn 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 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 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}