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
31const DOWNLOAD_BUDGET: std::time::Duration = std::time::Duration::from_secs(120);
34
35pub 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 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 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
89fn 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 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 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
150pub fn derive_output_path(url: &str) -> PathBuf {
157 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
173fn 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 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 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}