1use std::fs::{File, OpenOptions};
14use std::io::{Read, Seek, SeekFrom, Write};
15use std::path::Path;
16use std::sync::Arc;
17use std::sync::atomic::{AtomicBool, Ordering};
18
19use crate::checksum::calc_sha1_stream;
20use crate::control::ControlFile;
21use crate::http::{
22 DEFAULT_RANGE_GAP_THRESHOLD, HttpClient, byte_ranges_from_block_ranges, merge_byte_ranges,
23};
24use crate::matcher::BlockMatcher;
25use crate::matcher::MatchError;
26
27const STREAM_CHUNK_SIZE: usize = 1024 * 1024;
28
29#[derive(Debug, thiserror::Error)]
31pub enum AssemblyError {
32 #[error("IO error: {0}")]
35 Io(#[from] std::io::Error),
36 #[error("HTTP error: {0}")]
38 Http(#[from] crate::http::HttpError),
39 #[error("Matcher error: {0}")]
41 Matcher(#[from] MatchError),
42 #[error("Control file error: {0}")]
45 Control(String),
46 #[error("Checksum mismatch: expected {expected}, got {actual}")]
48 ChecksumMismatch {
49 expected: String,
51 actual: String,
53 },
54 #[error("No URLs available")]
56 NoUrls,
57 #[error("Aborted")]
59 Aborted,
60}
61
62fn aborted(flag: &Option<Arc<AtomicBool>>) -> bool {
67 flag.as_ref().is_some_and(|f| f.load(Ordering::Relaxed))
68}
69
70pub type ProgressCallback = Box<dyn Fn(u64, u64) + Send + Sync>;
73
74pub struct ZsyncAssembly {
76 control: ControlFile,
77 base_url: Option<String>,
78 matcher: BlockMatcher,
79 http: HttpClient,
80 output_path: std::path::PathBuf,
81 temp_path: std::path::PathBuf,
82 file: Option<File>,
83 range_gap_threshold: u64,
84 progress_callback: Option<ProgressCallback>,
85 abort_flag: Option<Arc<AtomicBool>>,
86}
87
88impl ZsyncAssembly {
89 pub fn new(control: ControlFile, output_path: &Path) -> Result<Self, AssemblyError> {
94 Self::with_base_url(control, output_path, None)
95 }
96
97 pub fn with_base_url(
101 control: ControlFile,
102 output_path: &Path,
103 base_url: Option<&str>,
104 ) -> Result<Self, AssemblyError> {
105 Self::with_client(control, output_path, base_url, HttpClient::new())
106 }
107
108 pub fn with_client(
114 control: ControlFile,
115 output_path: &Path,
116 base_url: Option<&str>,
117 http: HttpClient,
118 ) -> Result<Self, AssemblyError> {
119 let matcher = BlockMatcher::new(&control);
120 let temp_path = output_path.with_extension("zsync-tmp");
121
122 Ok(Self {
123 control,
124 base_url: base_url.map(|s| s.to_string()),
125 matcher,
126 http,
127 output_path: output_path.to_path_buf(),
128 temp_path,
129 file: None,
130 range_gap_threshold: DEFAULT_RANGE_GAP_THRESHOLD,
131 progress_callback: None,
132 abort_flag: None,
133 })
134 }
135
136 pub fn from_url(control_url: &str, output_path: &Path) -> Result<Self, AssemblyError> {
147 Self::from_url_with_client(control_url, output_path, HttpClient::new())
148 }
149
150 pub fn from_url_with_client(
155 control_url: &str,
156 output_path: &Path,
157 http: HttpClient,
158 ) -> Result<Self, AssemblyError> {
159 let control = http.fetch_control_file(control_url)?;
160 let base_url = extract_base_url(control_url);
161 Self::with_client(control, output_path, Some(&base_url), http)
162 }
163
164 pub fn set_range_gap_threshold(&mut self, threshold: u64) {
171 self.range_gap_threshold = threshold;
172 }
173
174 pub fn set_abort_flag(&mut self, flag: Arc<AtomicBool>) {
180 self.abort_flag = Some(flag);
181 }
182
183 pub fn set_progress_callback<F>(&mut self, callback: F)
190 where
191 F: Fn(u64, u64) + Send + Sync + 'static,
192 {
193 self.progress_callback = Some(Box::new(callback));
194 }
195
196 fn report_progress(&self) {
197 if let Some(ref cb) = self.progress_callback {
198 let (done, total) = self.progress();
199 cb(done, total);
200 }
201 }
202
203 pub fn progress(&self) -> (u64, u64) {
207 let total = self.control.length;
208 let got = self.matcher.blocks_todo();
209 let blocks_done = self.matcher.total_blocks() - got;
210 let done_bytes = (blocks_done * self.control.blocksize) as u64;
211 (done_bytes.min(total), total)
212 }
213
214 pub fn is_complete(&self) -> bool {
216 self.matcher.is_complete()
217 }
218
219 pub fn blocksize(&self) -> usize {
224 self.control.blocksize
225 }
226
227 pub fn block_stats(&self) -> (usize, usize) {
229 let total = self.matcher.total_blocks();
230 let todo = self.matcher.blocks_todo();
231 (total - todo, total)
232 }
233
234 pub fn submit_source_file(&mut self, path: &Path) -> Result<usize, AssemblyError> {
247 let mut file = File::open(path)?;
248 let file_size = file.metadata()?.len() as usize;
249
250 let blocksize = self.control.blocksize;
251 let context = blocksize * self.control.hash_lengths.seq_matches as usize;
252
253 if file_size < context {
254 return Ok(0);
255 }
256
257 let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
258 let mut total_matched = 0;
259 let mut buf = vec![0u8; chunk_size + 2 * context];
260 let mut file_offset = 0usize;
261
262 let abort_flag = self.abort_flag.clone();
263
264 loop {
265 if aborted(&abort_flag) {
266 return Err(AssemblyError::Aborted);
267 }
268
269 let overlap_start = file_offset.saturating_sub(context);
270 let overlap_len = file_offset - overlap_start;
271
272 if overlap_len > 0 {
273 Self::read_at_offset(&mut file, &mut buf[..overlap_len], overlap_start as u64)?;
274 }
275
276 let read_start = overlap_len;
277 let read_len = chunk_size;
278
279 let bytes_read = Self::read_at_offset(
280 &mut file,
281 &mut buf[read_start..read_start + read_len],
282 file_offset as u64,
283 )?;
284 if bytes_read == 0 {
285 break;
286 }
287
288 let data_len = read_start + bytes_read;
289 let chunk_context = if file_offset + bytes_read < file_size {
290 let context_start = file_offset + bytes_read;
291 let context_available = file_size.saturating_sub(context_start).min(context);
292 Self::read_at_offset(
293 &mut file,
294 &mut buf[data_len..data_len + context_available],
295 context_start as u64,
296 )?;
297 if context_available < context {
298 buf[data_len + context_available..data_len + context].fill(0);
299 }
300 data_len + context
301 } else {
302 buf[data_len..data_len + context].fill(0);
303 data_len + context
304 };
305
306 let matched_blocks = self
307 .matcher
308 .submit_source_data(&buf[..chunk_context], overlap_start as u64);
309
310 for (block_id, source_offset) in &matched_blocks {
311 let file_handle = self.ensure_file()?;
312 let offset = (block_id * blocksize) as u64;
313 let buf_offset = source_offset.saturating_sub(overlap_start);
314 debug_assert!(
315 buf_offset + blocksize <= chunk_context,
316 "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
317 buf_offset,
318 blocksize,
319 chunk_context,
320 source_offset,
321 overlap_start
322 );
323 let block_data = &buf[buf_offset..buf_offset + blocksize];
324 Self::write_at_offset(file_handle, block_data, offset)?;
325 }
326
327 total_matched += matched_blocks.len();
328 file_offset += bytes_read;
329
330 if bytes_read < read_len {
331 break;
332 }
333 }
334
335 Ok(total_matched)
336 }
337
338 pub fn submit_self_referential(&mut self) -> Result<usize, AssemblyError> {
351 if self.file.is_none() {
352 return Ok(0);
353 }
354
355 let file = self.file.as_mut().unwrap();
356 file.sync_all()?;
357
358 let file_size = file.metadata()?.len() as usize;
359
360 let blocksize = self.control.blocksize;
361 let context = blocksize * self.control.hash_lengths.seq_matches as usize;
362
363 if file_size < context {
364 return Ok(0);
365 }
366
367 let chunk_size = STREAM_CHUNK_SIZE.max(context * 2);
368 let mut total_matched = 0;
369 let mut buf = vec![0u8; chunk_size + 2 * context];
370 let mut file_offset = 0usize;
371
372 let abort_flag = self.abort_flag.clone();
373
374 loop {
375 if aborted(&abort_flag) {
376 return Err(AssemblyError::Aborted);
377 }
378
379 let overlap_start = file_offset.saturating_sub(context);
380 let overlap_len = file_offset - overlap_start;
381
382 if overlap_len > 0 {
383 Self::read_at_offset(file, &mut buf[..overlap_len], overlap_start as u64)?;
384 }
385
386 let read_start = overlap_len;
387 let read_len = chunk_size;
388
389 let bytes_read = Self::read_at_offset(
390 file,
391 &mut buf[read_start..read_start + read_len],
392 file_offset as u64,
393 )?;
394 if bytes_read == 0 {
395 break;
396 }
397
398 let data_len = read_start + bytes_read;
399 let chunk_context = if file_offset + bytes_read < file_size {
400 let context_start = file_offset + bytes_read;
401 let context_available = file_size.saturating_sub(context_start).min(context);
402 Self::read_at_offset(
403 file,
404 &mut buf[data_len..data_len + context_available],
405 context_start as u64,
406 )?;
407 if context_available < context {
408 buf[data_len + context_available..data_len + context].fill(0);
409 }
410 data_len + context
411 } else {
412 buf[data_len..data_len + context].fill(0);
413 data_len + context
414 };
415
416 let matched_blocks = self
417 .matcher
418 .submit_source_data(&buf[..chunk_context], overlap_start as u64);
419
420 for (block_id, source_offset) in &matched_blocks {
421 let offset = (block_id * blocksize) as u64;
422 let buf_offset = source_offset.saturating_sub(overlap_start);
423 debug_assert!(
424 buf_offset + blocksize <= chunk_context,
425 "buf_offset {} + blocksize {} > chunk_context {} (source_offset={}, overlap_start={})",
426 buf_offset,
427 blocksize,
428 chunk_context,
429 source_offset,
430 overlap_start
431 );
432 let block_data = &buf[buf_offset..buf_offset + blocksize];
433 Self::write_at_offset(file, block_data, offset)?;
434 }
435
436 total_matched += matched_blocks.len();
437 file_offset += bytes_read;
438
439 if bytes_read < read_len {
440 break;
441 }
442 }
443
444 Ok(total_matched)
445 }
446
447 fn read_at_offset(
448 file: &mut File,
449 data: &mut [u8],
450 offset: u64,
451 ) -> Result<usize, AssemblyError> {
452 file.seek(SeekFrom::Start(offset))?;
453 Ok(file.read(data)?)
454 }
455
456 fn write_at_offset(file: &mut File, data: &[u8], offset: u64) -> Result<(), AssemblyError> {
457 file.seek(SeekFrom::Start(offset))?;
458 file.write_all(data)?;
459 Ok(())
460 }
461
462 fn ensure_file(&mut self) -> Result<&mut File, AssemblyError> {
463 if self.file.is_none() {
464 let file = OpenOptions::new()
465 .read(true)
466 .write(true)
467 .create(true)
468 .truncate(false)
469 .open(&self.temp_path)?;
470 self.file = Some(file);
471 }
472 Ok(self.file.as_mut().unwrap())
473 }
474
475 pub fn download_missing_blocks(&mut self) -> Result<usize, AssemblyError> {
495 let relative_url = self
496 .control
497 .urls
498 .first()
499 .ok_or(AssemblyError::NoUrls)?
500 .clone();
501
502 let url = self
503 .base_url
504 .as_ref()
505 .map(|base| resolve_url(base, &relative_url))
506 .unwrap_or(relative_url);
507
508 let block_ranges = self.matcher.needed_block_ranges();
509 if block_ranges.is_empty() {
510 return Ok(0);
511 }
512
513 let byte_ranges = byte_ranges_from_block_ranges(
514 &block_ranges,
515 self.control.blocksize,
516 self.control.length,
517 );
518 let merged_ranges = merge_byte_ranges(&byte_ranges, self.range_gap_threshold);
519 let mut downloaded_blocks = 0;
520 let blocksize = self.control.blocksize;
521 let total_blocks = self.matcher.total_blocks();
522 let mut padded_buf = vec![0u8; blocksize];
523
524 let abort_flag = self.abort_flag.clone();
525
526 for (range_start, range_end) in merged_ranges {
527 if aborted(&abort_flag) {
528 return Err(AssemblyError::Aborted);
529 }
530
531 let mut reader = self.http.fetch_range_reader(&url, range_start, range_end)?;
532 let block_start = (range_start / blocksize as u64) as usize;
533 let initial_offset = (range_start % blocksize as u64) as usize;
534
535 let mut buf = vec![0u8; blocksize + 64 * 1024];
536 buf[..initial_offset].fill(0);
537 let mut buf_len = initial_offset;
538 let mut current_block_id = block_start;
539
540 let mut read_buf = [0u8; 64 * 1024];
541 loop {
542 if aborted(&abort_flag) {
543 return Err(AssemblyError::Aborted);
544 }
545
546 let n = reader.read(&mut read_buf)?;
547 if n == 0 {
548 break;
549 }
550
551 if buf_len + n > buf.len() {
552 buf.resize(buf_len + n, 0);
553 }
554 buf[buf_len..buf_len + n].copy_from_slice(&read_buf[..n]);
555 buf_len += n;
556
557 while buf_len >= blocksize {
558 if current_block_id >= total_blocks {
559 break;
560 }
561
562 if !self.matcher.is_block_known(current_block_id) {
563 let block_data_end = if current_block_id == total_blocks - 1 {
564 let last_block_size = (self.control.length as usize) % blocksize;
565 if last_block_size == 0 {
566 blocksize
567 } else {
568 last_block_size
569 }
570 } else {
571 blocksize
572 };
573
574 let block_data = &buf[..block_data_end];
575 padded_buf[..block_data_end].copy_from_slice(block_data);
576 if block_data_end < blocksize {
577 padded_buf[block_data_end..].fill(0);
578 }
579
580 if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
581 let file = self.ensure_file()?;
582 let file_offset = (current_block_id * blocksize) as u64;
583 Self::write_at_offset(file, block_data, file_offset)?;
584 downloaded_blocks += 1;
585 self.report_progress();
586 }
587 }
588
589 current_block_id += 1;
590 buf.copy_within(blocksize..buf_len, 0);
591 buf_len -= blocksize;
592 }
593 }
594
595 if buf_len > 0
596 && current_block_id < total_blocks
597 && !self.matcher.is_block_known(current_block_id)
598 {
599 let block_data = &buf[..buf_len];
600 padded_buf[..buf_len].copy_from_slice(block_data);
601 padded_buf[buf_len..].fill(0);
602
603 if self.matcher.submit_blocks(&padded_buf, current_block_id)? {
604 let file = self.ensure_file()?;
605 let file_offset = (current_block_id * blocksize) as u64;
606 Self::write_at_offset(file, block_data, file_offset)?;
607 downloaded_blocks += 1;
608 self.report_progress();
609 }
610 }
611 }
612
613 Ok(downloaded_blocks)
614 }
615
616 pub fn complete(mut self) -> Result<(), AssemblyError> {
629 if !self.matcher.is_complete() {
630 return Err(AssemblyError::Control(
631 "Not all blocks downloaded".to_string(),
632 ));
633 }
634
635 let file_length = self.control.length;
636 let expected_sha1 = self.control.sha1.clone();
637
638 let file = self.ensure_file()?;
639 file.set_len(file_length)?;
640
641 if let Some(ref expected) = expected_sha1 {
642 file.seek(SeekFrom::Start(0))?;
643 let actual_checksum = calc_sha1_stream(file)?;
644 let actual_hex = hex_encode(&actual_checksum);
645
646 if !actual_hex.eq_ignore_ascii_case(expected) {
647 return Err(AssemblyError::ChecksumMismatch {
648 expected: expected.clone(),
649 actual: actual_hex,
650 });
651 }
652 }
653
654 self.file.take();
655 std::fs::rename(&self.temp_path, &self.output_path)?;
656
657 Ok(())
658 }
659
660 pub fn abort(self) {}
664}
665
666impl Drop for ZsyncAssembly {
667 fn drop(&mut self) {
674 let _ = std::fs::remove_file(&self.temp_path);
675 }
676}
677
678fn hex_encode(bytes: &[u8]) -> String {
679 bytes.iter().map(|b| format!("{:02x}", b)).collect()
680}
681
682fn extract_base_url(url: &str) -> String {
683 url.rfind('/')
684 .map(|i| url[..=i].to_string())
685 .unwrap_or_default()
686}
687
688fn resolve_url(base: &str, relative: &str) -> String {
689 if relative.contains("://") {
690 return relative.to_string();
691 }
692 if relative.starts_with('/') {
693 let scheme_end = base.find("://").map(|i| i + 3).unwrap_or(0);
694 let host_end = base[scheme_end..]
695 .find('/')
696 .map(|i| scheme_end + i)
697 .unwrap_or(base.len());
698 format!("{}{}", &base[..host_end], relative)
699 } else {
700 format!("{}{}", base, relative)
701 }
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707
708 #[test]
709 fn test_hex_encode() {
710 assert_eq!(hex_encode(&[0x00, 0xff, 0x10]), "00ff10");
711 }
712
713 #[test]
714 fn test_extract_base_url() {
715 assert_eq!(
716 extract_base_url("https://example.com/path/file.zsync"),
717 "https://example.com/path/"
718 );
719 assert_eq!(
720 extract_base_url("https://example.com/file.zsync"),
721 "https://example.com/"
722 );
723 }
724
725 #[test]
726 fn test_resolve_url() {
727 assert_eq!(
728 resolve_url("https://example.com/path/", "file.bin"),
729 "https://example.com/path/file.bin"
730 );
731 assert_eq!(
732 resolve_url("https://example.com/path/", "/file.bin"),
733 "https://example.com/file.bin"
734 );
735 assert_eq!(
736 resolve_url("https://example.com/path/", "https://other.com/file.bin"),
737 "https://other.com/file.bin"
738 );
739 }
740}