1use std::fs::{File, OpenOptions};
2use std::io::{Read, Seek, SeekFrom};
3use std::os::unix::fs::FileExt;
4use std::path::Path;
5use std::sync::Arc;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use crate::checksum::calc_sha1_stream;
9use crate::control::ControlFile;
10use crate::http::{
11 DEFAULT_RANGE_GAP_THRESHOLD, HttpClient, byte_ranges_from_block_ranges, merge_byte_ranges,
12};
13use crate::matcher::BlockMatcher;
14use crate::matcher::MatchError;
15
16const STREAM_CHUNK_SIZE: usize = 1024 * 1024;
17
18#[derive(Debug, thiserror::Error)]
19pub enum AssemblyError {
20 #[error("IO error: {0}")]
21 Io(#[from] std::io::Error),
22 #[error("HTTP error: {0}")]
23 Http(#[from] crate::http::HttpError),
24 #[error("Matcher error: {0}")]
25 Matcher(#[from] MatchError),
26 #[error("Control file error: {0}")]
27 Control(String),
28 #[error("Checksum mismatch: expected {expected}, got {actual}")]
29 ChecksumMismatch { expected: String, actual: String },
30 #[error("No URLs available")]
31 NoUrls,
32 #[error("Aborted")]
33 Aborted,
34}
35
36fn aborted(flag: &Option<Arc<AtomicBool>>) -> bool {
41 flag.as_ref().is_some_and(|f| f.load(Ordering::Relaxed))
42}
43
44pub type ProgressCallback = Box<dyn Fn(u64, u64) + Send + Sync>;
45
46pub struct ZsyncAssembly {
47 control: ControlFile,
48 base_url: Option<String>,
49 matcher: BlockMatcher,
50 http: HttpClient,
51 output_path: std::path::PathBuf,
52 temp_path: std::path::PathBuf,
53 file: Option<File>,
54 range_gap_threshold: u64,
55 progress_callback: Option<ProgressCallback>,
56 abort_flag: Option<Arc<AtomicBool>>,
57}
58
59impl ZsyncAssembly {
60 pub fn new(control: ControlFile, output_path: &Path) -> Result<Self, AssemblyError> {
61 Self::with_base_url(control, output_path, None)
62 }
63
64 pub fn with_base_url(
65 control: ControlFile,
66 output_path: &Path,
67 base_url: Option<&str>,
68 ) -> Result<Self, AssemblyError> {
69 Self::with_client(control, output_path, base_url, HttpClient::new())
70 }
71
72 pub fn with_client(
78 control: ControlFile,
79 output_path: &Path,
80 base_url: Option<&str>,
81 http: HttpClient,
82 ) -> Result<Self, AssemblyError> {
83 let matcher = BlockMatcher::new(&control);
84 let temp_path = output_path.with_extension("zsync-tmp");
85
86 Ok(Self {
87 control,
88 base_url: base_url.map(|s| s.to_string()),
89 matcher,
90 http,
91 output_path: output_path.to_path_buf(),
92 temp_path,
93 file: None,
94 range_gap_threshold: DEFAULT_RANGE_GAP_THRESHOLD,
95 progress_callback: None,
96 abort_flag: None,
97 })
98 }
99
100 pub fn from_url(control_url: &str, output_path: &Path) -> Result<Self, AssemblyError> {
101 Self::from_url_with_client(control_url, output_path, HttpClient::new())
102 }
103
104 pub fn from_url_with_client(
109 control_url: &str,
110 output_path: &Path,
111 http: HttpClient,
112 ) -> Result<Self, AssemblyError> {
113 let control = http.fetch_control_file(control_url)?;
114 let base_url = extract_base_url(control_url);
115 Self::with_client(control, output_path, Some(&base_url), http)
116 }
117
118 pub fn set_range_gap_threshold(&mut self, threshold: u64) {
119 self.range_gap_threshold = threshold;
120 }
121
122 pub fn set_abort_flag(&mut self, flag: Arc<AtomicBool>) {
128 self.abort_flag = Some(flag);
129 }
130
131 pub fn set_progress_callback<F>(&mut self, callback: F)
132 where
133 F: Fn(u64, u64) + Send + Sync + 'static,
134 {
135 self.progress_callback = Some(Box::new(callback));
136 }
137
138 fn report_progress(&self) {
139 if let Some(ref cb) = self.progress_callback {
140 let (done, total) = self.progress();
141 cb(done, total);
142 }
143 }
144
145 pub fn progress(&self) -> (u64, u64) {
146 let total = self.control.length;
147 let got = self.matcher.blocks_todo();
148 let blocks_done = self.matcher.total_blocks() - got;
149 let done_bytes = (blocks_done * self.control.blocksize) as u64;
150 (done_bytes.min(total), total)
151 }
152
153 pub fn is_complete(&self) -> bool {
154 self.matcher.is_complete()
155 }
156
157 pub fn block_stats(&self) -> (usize, usize) {
158 let total = self.matcher.total_blocks();
159 let todo = self.matcher.blocks_todo();
160 (total - todo, total)
161 }
162
163 pub fn submit_source_file(&mut self, path: &Path) -> Result<usize, AssemblyError> {
164 let file = File::open(path)?;
165 let file_size = file.metadata()?.len() as usize;
166
167 let blocksize = self.control.blocksize;
168 let context = blocksize * self.control.hash_lengths.seq_matches as usize;
169
170 if file_size < context {
171 return Ok(0);
172 }
173
174 let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
175 let mut total_matched = 0;
176 let mut buf = vec![0u8; chunk_size + 2 * context];
177 let mut file_offset = 0usize;
178
179 let abort_flag = self.abort_flag.clone();
180
181 loop {
182 if aborted(&abort_flag) {
183 return Err(AssemblyError::Aborted);
184 }
185
186 let overlap_start = file_offset.saturating_sub(context);
187 let overlap_len = file_offset - overlap_start;
188
189 if overlap_len > 0 {
190 file.read_at(&mut buf[..overlap_len], overlap_start as u64)?;
191 }
192
193 let read_start = overlap_len;
194 let read_len = chunk_size;
195
196 let bytes_read = file.read_at(
197 &mut buf[read_start..read_start + read_len],
198 file_offset as u64,
199 )?;
200 if bytes_read == 0 {
201 break;
202 }
203
204 let data_len = read_start + bytes_read;
205 let chunk_context = if file_offset + bytes_read < file_size {
206 let context_start = file_offset + bytes_read;
207 let context_available = file_size.saturating_sub(context_start).min(context);
208 file.read_at(
209 &mut buf[data_len..data_len + context_available],
210 context_start as u64,
211 )?;
212 if context_available < context {
213 buf[data_len + context_available..data_len + context].fill(0);
214 }
215 data_len + context
216 } else {
217 buf[data_len..data_len + context].fill(0);
218 data_len + context
219 };
220
221 let matched_blocks = self
222 .matcher
223 .submit_source_data(&buf[..chunk_context], overlap_start as u64);
224
225 for (block_id, source_offset) in &matched_blocks {
226 let file_handle = self.ensure_file()?;
227 let offset = (block_id * blocksize) as u64;
228 let buf_offset = source_offset.saturating_sub(overlap_start);
229 debug_assert!(
230 buf_offset + blocksize <= chunk_context,
231 "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
232 buf_offset,
233 blocksize,
234 chunk_context,
235 source_offset,
236 overlap_start
237 );
238 let block_data = &buf[buf_offset..buf_offset + blocksize];
239 Self::write_at_offset(file_handle, block_data, offset)?;
240 }
241
242 total_matched += matched_blocks.len();
243 file_offset += bytes_read;
244
245 if bytes_read < read_len {
246 break;
247 }
248 }
249
250 Ok(total_matched)
251 }
252
253 pub fn submit_self_referential(&mut self) -> Result<usize, AssemblyError> {
254 if self.file.is_none() {
255 return Ok(0);
256 }
257
258 let file = self.file.as_mut().unwrap();
259 file.sync_all()?;
260
261 let file_size = file.metadata()?.len() as usize;
262
263 let blocksize = self.control.blocksize;
264 let context = blocksize * self.control.hash_lengths.seq_matches as usize;
265
266 if file_size < context {
267 return Ok(0);
268 }
269
270 let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
271 let mut total_matched = 0;
272 let mut buf = vec![0u8; chunk_size + 2 * context];
273 let mut file_offset = 0usize;
274
275 let abort_flag = self.abort_flag.clone();
276
277 loop {
278 if aborted(&abort_flag) {
279 return Err(AssemblyError::Aborted);
280 }
281
282 let overlap_start = file_offset.saturating_sub(context);
283 let overlap_len = file_offset - overlap_start;
284
285 if overlap_len > 0 {
286 file.read_at(&mut buf[..overlap_len], overlap_start as u64)?;
287 }
288
289 let read_start = overlap_len;
290 let read_len = chunk_size;
291
292 let bytes_read = file.read_at(
293 &mut buf[read_start..read_start + read_len],
294 file_offset as u64,
295 )?;
296 if bytes_read == 0 {
297 break;
298 }
299
300 let data_len = read_start + bytes_read;
301 let chunk_context = if file_offset + bytes_read < file_size {
302 let context_start = file_offset + bytes_read;
303 let context_available = file_size.saturating_sub(context_start).min(context);
304 file.read_at(
305 &mut buf[data_len..data_len + context_available],
306 context_start as u64,
307 )?;
308 if context_available < context {
309 buf[data_len + context_available..data_len + context].fill(0);
310 }
311 data_len + context
312 } else {
313 buf[data_len..data_len + context].fill(0);
314 data_len + context
315 };
316
317 let matched_blocks = self
318 .matcher
319 .submit_source_data(&buf[..chunk_context], overlap_start as u64);
320
321 for (block_id, source_offset) in &matched_blocks {
322 let offset = (block_id * blocksize) as u64;
323 let buf_offset = source_offset.saturating_sub(overlap_start);
324 debug_assert!(
325 buf_offset + blocksize <= chunk_context,
326 "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
327 buf_offset,
328 blocksize,
329 chunk_context,
330 source_offset,
331 overlap_start
332 );
333 let block_data = &buf[buf_offset..buf_offset + blocksize];
334 Self::write_at_offset(file, block_data, offset)?;
335 }
336
337 total_matched += matched_blocks.len();
338 file_offset += bytes_read;
339
340 if bytes_read < read_len {
341 break;
342 }
343 }
344
345 Ok(total_matched)
346 }
347
348 fn write_at_offset(file: &File, data: &[u8], offset: u64) -> Result<(), AssemblyError> {
349 file.write_all_at(data, offset)?;
350 Ok(())
351 }
352
353 fn ensure_file(&mut self) -> Result<&mut File, AssemblyError> {
354 if self.file.is_none() {
355 let file = OpenOptions::new()
356 .read(true)
357 .write(true)
358 .create(true)
359 .truncate(false)
360 .open(&self.temp_path)?;
361 self.file = Some(file);
362 }
363 Ok(self.file.as_mut().unwrap())
364 }
365
366 pub fn download_missing_blocks(&mut self) -> Result<usize, AssemblyError> {
367 let relative_url = self
368 .control
369 .urls
370 .first()
371 .ok_or(AssemblyError::NoUrls)?
372 .clone();
373
374 let url = self
375 .base_url
376 .as_ref()
377 .map(|base| resolve_url(base, &relative_url))
378 .unwrap_or(relative_url);
379
380 let block_ranges = self.matcher.needed_block_ranges();
381 if block_ranges.is_empty() {
382 return Ok(0);
383 }
384
385 let byte_ranges = byte_ranges_from_block_ranges(
386 &block_ranges,
387 self.control.blocksize,
388 self.control.length,
389 );
390 let merged_ranges = merge_byte_ranges(&byte_ranges, self.range_gap_threshold);
391 let mut downloaded_blocks = 0;
392 let blocksize = self.control.blocksize;
393 let total_blocks = self.matcher.total_blocks();
394 let mut padded_buf = vec![0u8; blocksize];
395
396 let abort_flag = self.abort_flag.clone();
397
398 for (range_start, range_end) in merged_ranges {
399 if aborted(&abort_flag) {
400 return Err(AssemblyError::Aborted);
401 }
402
403 let mut reader = self.http.fetch_range_reader(&url, range_start, range_end)?;
404 let block_start = (range_start / blocksize as u64) as usize;
405 let initial_offset = (range_start % blocksize as u64) as usize;
406
407 let mut buf = vec![0u8; blocksize + 64 * 1024];
408 buf[..initial_offset].fill(0);
409 let mut buf_len = initial_offset;
410 let mut current_block_id = block_start;
411
412 let mut read_buf = [0u8; 64 * 1024];
413 loop {
414 if aborted(&abort_flag) {
415 return Err(AssemblyError::Aborted);
416 }
417
418 let n = reader.read(&mut read_buf)?;
419 if n == 0 {
420 break;
421 }
422
423 if buf_len + n > buf.len() {
424 buf.resize(buf_len + n, 0);
425 }
426 buf[buf_len..buf_len + n].copy_from_slice(&read_buf[..n]);
427 buf_len += n;
428
429 while buf_len >= blocksize {
430 if current_block_id >= total_blocks {
431 break;
432 }
433
434 if !self.matcher.is_block_known(current_block_id) {
435 let block_data_end = if current_block_id == total_blocks - 1 {
436 let last_block_size = (self.control.length as usize) % blocksize;
437 if last_block_size == 0 {
438 blocksize
439 } else {
440 last_block_size
441 }
442 } else {
443 blocksize
444 };
445
446 let block_data = &buf[..block_data_end];
447 padded_buf[..block_data_end].copy_from_slice(block_data);
448 if block_data_end < blocksize {
449 padded_buf[block_data_end..].fill(0);
450 }
451
452 if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
453 let file = self.ensure_file()?;
454 let file_offset = (current_block_id * blocksize) as u64;
455 Self::write_at_offset(file, block_data, file_offset)?;
456 downloaded_blocks += 1;
457 self.report_progress();
458 }
459 }
460
461 current_block_id += 1;
462 buf.copy_within(blocksize..buf_len, 0);
463 buf_len -= blocksize;
464 }
465 }
466
467 if buf_len > 0
468 && current_block_id < total_blocks
469 && !self.matcher.is_block_known(current_block_id)
470 {
471 let block_data = &buf[..buf_len];
472 padded_buf[..buf_len].copy_from_slice(block_data);
473 padded_buf[buf_len..].fill(0);
474
475 if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
476 let file = self.ensure_file()?;
477 let file_offset = (current_block_id * blocksize) as u64;
478 Self::write_at_offset(file, block_data, file_offset)?;
479 downloaded_blocks += 1;
480 self.report_progress();
481 }
482 }
483 }
484
485 Ok(downloaded_blocks)
486 }
487
488 pub fn complete(mut self) -> Result<(), AssemblyError> {
489 if !self.matcher.is_complete() {
490 return Err(AssemblyError::Control(
491 "Not all blocks downloaded".to_string(),
492 ));
493 }
494
495 let file_length = self.control.length;
496 let expected_sha1 = self.control.sha1.clone();
497
498 let file = self.ensure_file()?;
499 file.set_len(file_length)?;
500
501 if let Some(ref expected) = expected_sha1 {
502 file.seek(SeekFrom::Start(0))?;
503 let actual_checksum = calc_sha1_stream(file)?;
504 let actual_hex = hex_encode(&actual_checksum);
505
506 if !actual_hex.eq_ignore_ascii_case(expected) {
507 return Err(AssemblyError::ChecksumMismatch {
508 expected: expected.clone(),
509 actual: actual_hex,
510 });
511 }
512 }
513
514 self.file.take();
515 std::fs::rename(&self.temp_path, &self.output_path)?;
516
517 Ok(())
518 }
519
520 pub fn abort(self) {}
524}
525
526impl Drop for ZsyncAssembly {
527 fn drop(&mut self) {
534 let _ = std::fs::remove_file(&self.temp_path);
535 }
536}
537
538fn hex_encode(bytes: &[u8]) -> String {
539 bytes.iter().map(|b| format!("{:02x}", b)).collect()
540}
541
542fn extract_base_url(url: &str) -> String {
543 url.rfind('/')
544 .map(|i| url[..=i].to_string())
545 .unwrap_or_default()
546}
547
548fn resolve_url(base: &str, relative: &str) -> String {
549 if relative.contains("://") {
550 return relative.to_string();
551 }
552 if relative.starts_with('/') {
553 let scheme_end = base.find("://").map(|i| i + 3).unwrap_or(0);
554 let host_end = base[scheme_end..]
555 .find('/')
556 .map(|i| scheme_end + i)
557 .unwrap_or(base.len());
558 format!("{}{}", &base[..host_end], relative)
559 } else {
560 format!("{}{}", base, relative)
561 }
562}
563
564#[cfg(test)]
565mod tests {
566 use super::*;
567
568 #[test]
569 fn test_hex_encode() {
570 assert_eq!(hex_encode(&[0x00, 0xff, 0x10]), "00ff10");
571 }
572
573 #[test]
574 fn test_extract_base_url() {
575 assert_eq!(
576 extract_base_url("https://example.com/path/file.zsync"),
577 "https://example.com/path/"
578 );
579 assert_eq!(
580 extract_base_url("https://example.com/file.zsync"),
581 "https://example.com/"
582 );
583 }
584
585 #[test]
586 fn test_resolve_url() {
587 assert_eq!(
588 resolve_url("https://example.com/path/", "file.bin"),
589 "https://example.com/path/file.bin"
590 );
591 assert_eq!(
592 resolve_url("https://example.com/path/", "/file.bin"),
593 "https://example.com/file.bin"
594 );
595 assert_eq!(
596 resolve_url("https://example.com/path/", "https://other.com/file.bin"),
597 "https://other.com/file.bin"
598 );
599 }
600}