zarlib 0.16.0

ZAR archive library with compression, deduplication, and commit-based history
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
use super::common::*;
use super::info::group_size_metadata;
use super::list::load_toc_through_with_passwords;
use super::pipeline::{BlockWorkItem, EncryptionContext, SmallFilePacker, encode_block};
use crate::{
    ArchivePath, BlockFrame, CommitHeader, CommitValidationLimits, ContentAead,
    EncryptionDescriptor, EncryptionScope, FileEntry, HEADER_OFFSET_SIZE, HeaderFrame,
    LogicalHeader, Toc, TocChange, TocEntry, UNENCRYPTED_DESCRIPTOR, ValidatedCommit, generate_dek,
    generate_nonce, wrap_dek_with_password,
};
use std::collections::{BTreeMap, HashMap};
use std::fs::{File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::Path;
use xxhash_rust::xxh64::Xxh64;
use zeroize::Zeroizing;

struct JoinCommit {
    header: CommitHeader,
    data_start: u64,
    commit_end: u64,
    validated: ValidatedCommit,
    key: Option<Zeroizing<[u8; crate::DEK_SIZE]>>,
}

fn write_joined_block(
    data: &mut Vec<u8>,
    block_sizes: &mut HashMap<u32, u64>,
    block_index: &mut Vec<crate::HeaderBlockIndexEntry>,
    block: BlockWorkItem,
    compression_level: i32,
    encryption: Option<&EncryptionContext>,
) -> Result<(), Box<dyn std::error::Error>> {
    let frame = encode_block(
        block.block_index,
        &block.data,
        compression_level,
        block.skip_compression,
        encryption,
    )?;
    block_sizes.insert(
        block.block_index,
        u64::try_from(frame.payload.len()).map_err(|_| "joined block size overflow")?,
    );
    write_joined_frame(data, block_index, &frame)?;
    Ok(())
}

fn write_joined_frame(
    data: &mut Vec<u8>,
    block_index: &mut Vec<crate::HeaderBlockIndexEntry>,
    frame: &BlockFrame,
) -> Result<(), Box<dyn std::error::Error>> {
    let offset = u64::try_from(data.len())?;
    let encoded_size = u64::try_from(frame.encoded_size()?)?;
    frame.write_to(data)?;
    block_index.push(crate::HeaderBlockIndexEntry {
        index: frame.block_index,
        offset,
        encoded_size,
    });
    Ok(())
}

/// Creates an empty overlay with a root commit ID following the base archive's IDs.
pub fn create_overlay_archive(
    base: &Path,
    destination: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let parent = destination
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut output = tempfile::NamedTempFile::new_in(parent)?;
    let id = next_commit_id(base)?;
    let logical = LogicalHeader::new(Vec::new()).encode()?;
    let provisional = CommitHeader::new(0, id, 0, 0)?;
    let frame =
        HeaderFrame::from_uncompressed(provisional, &logical, UNENCRYPTED_DESCRIPTOR.to_vec(), 3)?;
    let header = CommitHeader::new(0, id, 0, u32::try_from(frame.encoded_size()?)?)?;
    let frame =
        HeaderFrame::from_uncompressed(header, &logical, UNENCRYPTED_DESCRIPTOR.to_vec(), 3)?;
    let header_offset = crate::CONTAINER_HEADER_SIZE + HEADER_OFFSET_SIZE;
    crate::ContainerHeader::new(header_offset).write_to(&mut output)?;
    output.write_all(&0u64.to_le_bytes())?;
    frame.write_to(&mut output)?;
    output.write_all(&header_offset.to_le_bytes())?;
    output.as_file_mut().sync_all()?;
    output
        .persist_noclobber(destination)
        .map_err(|error| error.error)?;
    Ok(())
}

/// Writes a new archive containing the commits of `base` followed by `overlay`.
///
/// The destination must not exist. Commit IDs must be unique across both inputs.
pub fn combine_archives(
    base: &Path,
    overlay: &Path,
    destination: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    combine_archives_with_progress(base, overlay, destination, None)
}

/// Writes a combined archive, checking for cancellation while copying its data.
pub fn combine_archives_with_progress(
    base: &Path,
    overlay: &Path,
    destination: &Path,
    progress: Option<&dyn Progress>,
) -> Result<(), Box<dyn std::error::Error>> {
    let parent = destination
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut output = tempfile::NamedTempFile::new_in(parent)?;
    let mut base_file = File::open(base)?;
    let mut overlay_file = File::open(overlay)?;
    let limits = CommitValidationLimits::default();
    let mut ids = std::collections::HashSet::new();
    let mut offsets = std::collections::HashSet::new();
    let mut offset = read_first_header_offset(&mut base_file)?;
    let mut link_position = 4;
    while offset != 0 {
        if !offsets.insert(offset) {
            return Err("base archive commit chain contains a cycle".into());
        }
        let (header, data_start, next) = read_commit_at_offset(&mut base_file, offset, limits)?;
        if !ids.insert(header.commit_id) {
            return Err("base archive contains duplicate commit IDs".into());
        }
        link_position = data_start
            .checked_sub(HEADER_OFFSET_SIZE)
            .ok_or("invalid commit link")?;
        offset = next;
    }
    base_file.seek(SeekFrom::Start(0))?;
    copy_archive_data(&mut base_file, &mut output, progress)?;

    offsets.clear();
    offset = read_first_header_offset(&mut overlay_file)?;
    while offset != 0 {
        if !offsets.insert(offset) {
            return Err("overlay archive commit chain contains a cycle".into());
        }
        let (header, data_start, next) = read_commit_at_offset(&mut overlay_file, offset, limits)?;
        if !ids.insert(header.commit_id) {
            return Err("archive commit IDs collide".into());
        }
        let body_size = header
            .data_section_size
            .checked_add(u64::from(header.header_frame_size))
            .ok_or("commit size overflow")?;
        output.seek(SeekFrom::End(0))?;
        let new_link_position = output.stream_position()?;
        output.write_all(&0u64.to_le_bytes())?;
        let new_header_offset = output
            .stream_position()?
            .checked_add(header.data_section_size)
            .ok_or("header offset overflow")?;
        overlay_file.seek(SeekFrom::Start(data_start))?;
        if copy_archive_data(
            &mut (&mut overlay_file).take(body_size),
            &mut output,
            progress,
        )? != body_size
        {
            return Err("overlay commit is truncated".into());
        }
        output.write_all(&new_header_offset.to_le_bytes())?;
        output.seek(SeekFrom::Start(link_position))?;
        output.write_all(&new_header_offset.to_le_bytes())?;
        link_position = new_link_position;
        offset = next;
    }
    ProgressReporter::new(progress).check_cancelled()?;
    output.as_file_mut().sync_all()?;
    output
        .persist_noclobber(destination)
        .map_err(|error| error.error)?;
    Ok(())
}

fn copy_archive_data(
    reader: &mut dyn Read,
    writer: &mut dyn Write,
    progress: Option<&dyn Progress>,
) -> Result<u64, Box<dyn std::error::Error>> {
    if progress.is_none() {
        return Ok(io::copy(reader, writer)?);
    }
    let mut buffer = [0; 64 * 1024];
    let mut total = 0_u64;
    loop {
        ProgressReporter::new(progress).check_cancelled()?;
        let count = reader.read(&mut buffer)?;
        if count == 0 {
            return Ok(total);
        }
        writer.write_all(&buffer[..count])?;
        total = total
            .checked_add(count as u64)
            .ok_or("archive size overflow")?;
    }
}

/// Compacts an overlay into one commit and atomically writes the resulting archive.
/// Encrypted overlay commits require an explicitly encrypted output.
pub fn save_overlay_archive(
    base: &Path,
    overlay: &Path,
    destination: &Path,
    options: EncodingOptions,
    passwords: &PasswordSet,
    encryption: Option<(&[u8], ContentAead, EncryptionScope)>,
) -> Result<[u8; 4], Box<dyn std::error::Error>> {
    let base_metadata = std::fs::metadata(base)?;
    let overlay_path = overlay.to_str().ok_or("overlay path is not valid UTF-8")?;
    let commits = super::info::info_archive(overlay_path, false)?;
    let first = commits.first().ok_or("overlay contains no commits")?;
    let last = commits.last().ok_or("overlay contains no commits")?;
    if encryption.is_none()
        && commits
            .iter()
            .any(|commit| commit.header_encrypted || commit.data_encrypted)
    {
        return Err("encrypted overlay commits require encrypted output".into());
    }
    if let Some((_, _, scope)) = encryption {
        let protects_header = matches!(
            scope,
            EncryptionScope::Header | EncryptionScope::HeaderAndData
        );
        let protects_data = matches!(
            scope,
            EncryptionScope::Data | EncryptionScope::HeaderAndData
        );
        if commits.iter().any(|commit| {
            (commit.header_encrypted && !protects_header)
                || (commit.data_encrypted && !protects_data)
        }) {
            return Err("output encryption must protect all encrypted overlay content".into());
        }
    }
    let first_id = format!("{:08x}", u32::from_le_bytes(first.id));
    let last_id = format!("{:08x}", u32::from_le_bytes(last.id));
    let parent = destination
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let directory = tempfile::tempdir_in(parent)?;
    let assembled = directory.path().join("assembled.zar");
    combine_archives(base, overlay, &assembled)?;
    let assembled_path = assembled
        .to_str()
        .ok_or("temporary archive path is not valid UTF-8")?;
    join_archive_with_encryption(
        assembled_path,
        &first_id,
        &last_id,
        options,
        None,
        passwords,
        encryption,
    )?;
    let saved_commits = super::info::info_archive(assembled_path, false)?;
    let saved_id = saved_commits
        .last()
        .ok_or("saved archive contains no commits")?
        .id;
    let mut source = File::open(&assembled)?;
    let mut output = tempfile::NamedTempFile::new_in(parent)?;
    io::copy(&mut source, &mut output)?;
    output
        .as_file()
        .set_permissions(File::open(base)?.metadata()?.permissions())?;
    output.as_file_mut().sync_all()?;
    let current_metadata = std::fs::metadata(base)?;
    if current_metadata.len() != base_metadata.len()
        || current_metadata.modified()? != base_metadata.modified()?
    {
        return Err("base archive changed while saving".into());
    }
    output.persist(destination).map_err(|error| error.error)?;
    Ok(saved_id)
}

pub fn join_archive_with_encoding(
    archive: &str,
    from_id: &str,
    to_id: &str,
    options: EncodingOptions,
) -> Result<(), Box<dyn std::error::Error>> {
    join_archive_with_encoding_progress(archive, from_id, to_id, options, None)
}

pub fn join_archive_with_encoding_progress(
    archive: &str,
    from_id: &str,
    to_id: &str,
    options: EncodingOptions,
    progress: Option<&dyn Progress>,
) -> Result<(), Box<dyn std::error::Error>> {
    join_archive_with_encoding_progress_and_passwords(
        archive,
        from_id,
        to_id,
        options,
        progress,
        &PasswordSet::default(),
    )
}

/// Joins the readable commits in the selected range. Encrypted commits whose
/// password is unavailable are retained unchanged; the joined commit is placed
/// at the first readable commit's position.
pub fn join_archive_with_encoding_progress_and_passwords(
    archive: &str,
    from_id: &str,
    to_id: &str,
    options: EncodingOptions,
    progress: Option<&dyn Progress>,
    passwords: &PasswordSet,
) -> Result<(), Box<dyn std::error::Error>> {
    join_archive_with_encryption(archive, from_id, to_id, options, progress, passwords, None)
}

/// Joins commits and optionally encrypts the resulting commit with a new password.
pub fn join_archive_with_encryption(
    archive: &str,
    from_id: &str,
    to_id: &str,
    mut options: EncodingOptions,
    progress: Option<&dyn Progress>,
    passwords: &PasswordSet,
    encryption: Option<(&[u8], ContentAead, EncryptionScope)>,
) -> Result<(), Box<dyn std::error::Error>> {
    let encoding_warning = resolve_encoding_options(&mut options);
    if let (Some(progress), Some(warning)) = (progress, encoding_warning.as_deref()) {
        progress.warning(warning);
    }
    let progress = ProgressReporter::new(progress);
    let from_id = parse_commit_id(from_id)?;
    let to_id = parse_commit_id(to_id)?;
    let archive_path = Path::new(archive);
    let parent = archive_path
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    if !parent.is_dir() {
        return Err(format!("archive parent is not a directory: {}", parent.display()).into());
    }
    let mut input = File::open(archive_path)?;
    let limits = CommitValidationLimits::default();
    let archive_bytes = input.metadata()?.len();
    if let Some(callback) = progress.0 {
        callback.set_total(archive_bytes);
    }
    let mut commits = Vec::new();
    let first_header_offset = read_first_header_offset(&mut input)?;
    let mut header_offset = first_header_offset;
    while header_offset != 0 {
        let (commit_header, data_start, next_header_offset) =
            read_commit_at_offset(&mut input, header_offset, limits)?;
        let (validated, key) =
            read_commit_with_passwords(&mut input, commit_header.clone(), limits, passwords)?;
        let commit_end = header_offset
            .checked_add(u64::from(commit_header.header_frame_size))
            .and_then(|size| size.checked_add(HEADER_OFFSET_SIZE))
            .ok_or("commit end overflow")?;
        progress.inc(commit_end.saturating_sub(data_start));
        progress.set_message(format!(
            "Joining commit {:08x}",
            u32::from_le_bytes(commit_header.commit_id)
        ));
        commits.push(JoinCommit {
            header: commit_header,
            data_start,
            commit_end,
            validated,
            key,
        });
        header_offset = next_header_offset;
    }
    let matching_indices = |id: &[u8; 4]| {
        commits
            .iter()
            .enumerate()
            .filter_map(|(index, commit)| (commit.header.commit_id == *id).then_some(index))
            .collect::<Vec<_>>()
    };
    let from_matches = matching_indices(&from_id);
    let to_matches = matching_indices(&to_id);
    if from_matches.len() != 1 || to_matches.len() != 1 {
        return Err("commit IDs must each identify exactly one archive commit".into());
    }
    let first = from_matches[0];
    let last = to_matches[0];
    if first > last {
        return Err("start commit ID must not appear after end commit ID".into());
    }

    let selected: Vec<usize> = (first..=last)
        .filter(|&index| {
            let commit = &commits[index];
            commit.validated.logical_header.is_some()
                && (!commit.validated.encryption.is_data_encrypted() || commit.key.is_some())
        })
        .collect();
    if selected.is_empty() {
        return Err(
            "the selected range contains no commits readable with the supplied passwords".into(),
        );
    }
    if encryption.is_some() && selected.len() != last - first + 1 {
        return Err(
            "all selected commits must be readable to create an encrypted joined commit".into(),
        );
    }

    let selected_ids: std::collections::HashSet<_> = selected
        .iter()
        .map(|&index| commits[index].header.commit_id)
        .collect();
    for (index, commit) in commits.iter().enumerate() {
        if selected.contains(&index) || index < selected[0] {
            continue;
        }
        let header =
            commit.validated.logical_header.as_ref().ok_or(
                "cannot check references in an encrypted commit following the joined range",
            )?;
        for change in &header.changes {
            if let TocChange::PutFile { path, entry } = change
                && let Some(source) = entry.source_commit
                && selected_ids.contains(&source)
            {
                return Err(format!("cannot join referenced commit {:08x}: commit {:08x}, path {path} references it", u32::from_le_bytes(source), u32::from_le_bytes(commit.header.commit_id)).into());
            }
        }
    }
    let referenced_selected_ids: std::collections::HashSet<_> = selected
        .iter()
        .flat_map(|&index| {
            commits[index]
                .validated
                .logical_header
                .as_ref()
                .unwrap()
                .changes
                .iter()
                .filter_map(|change| match change {
                    TocChange::PutFile { entry, .. } => entry
                        .source_commit
                        .filter(|source| selected_ids.contains(source)),
                    _ => None,
                })
        })
        .collect();

    let first_selected = selected[0];
    let mut prefix_toc = Toc::default();
    for commit in &commits[..first_selected] {
        let header = commit
            .validated
            .logical_header
            .as_ref()
            .ok_or("cannot build join prefix while a preceding commit header is encrypted")?;
        Toc::check_available_blocks(&header.changes, &commit.validated.block_indices)?;
        prefix_toc.apply_archive_commit(commit.header.commit_id, &header.changes)?;
    }
    let mut joined_toc = prefix_toc.clone();
    let mut written_files = BTreeMap::<ArchivePath, Vec<u8>>::new();
    let mut written_references = BTreeMap::<ArchivePath, FileEntry>::new();
    let mut historical_blocks = HashMap::<[u8; 4], HashMap<u32, Vec<u8>>>::new();
    let mut custom_metadata = HashMap::new();
    let mut joined_special = BTreeMap::<ArchivePath, TocEntry>::new();
    let mut joined_metadata = BTreeMap::<ArchivePath, crate::EntryMetadata>::new();
    let limits = CommitValidationLimits::default();
    for &index in &selected {
        let commit = &commits[index];
        let commit_header = &commit.header;
        let header = commit.validated.logical_header.as_ref().unwrap();
        let algorithm = match &commit.validated.encryption {
            crate::EncryptionDescriptor::Unencrypted => None,
            crate::EncryptionDescriptor::Symmetric { algorithm, .. }
            | crate::EncryptionDescriptor::Password { algorithm, .. }
            | crate::EncryptionDescriptor::Recipients { algorithm, .. }
            | crate::EncryptionDescriptor::PasswordAndRecipients { algorithm, .. } => {
                Some(*algorithm)
            }
        };
        input.seek(io::SeekFrom::Start(commit.data_start))?;
        let mut data_reader = (&mut input).take(commit_header.data_section_size);
        let mut blocks = HashMap::with_capacity(commit.validated.block_count as usize);
        while data_reader.limit() != 0 {
            let block = BlockFrame::read_from(&mut data_reader, limits.max_frame_payload_size)?;
            let contents = if block.flags & crate::BLOCK_FLAG_ENCRYPTED != 0 {
                block.uncompressed_encrypted(
                    commit_header,
                    commit
                        .key
                        .as_deref()
                        .ok_or("join password is unavailable")?,
                    algorithm.ok_or("encrypted commit is missing its algorithm")?,
                    limits.max_uncompressed_block_size,
                )?
            } else {
                block.uncompressed_at_most(limits.max_uncompressed_block_size)?
            };
            progress.inc(contents.len() as u64);
            blocks.insert(block.block_index, contents);
        }
        super::meta::merge_custom_metadata(&mut custom_metadata, &header.metadata);
        Toc::check_available_blocks(&header.changes, &commit.validated.block_indices)?;
        joined_toc.apply_archive_commit(commit.header.commit_id, &header.changes)?;
        let metadata: HashMap<_, _> = header
            .entry_metadata
            .iter()
            .map(|entry| (&entry.path, entry))
            .collect();
        for change in &header.changes {
            match change {
                TocChange::PutFile { path, .. }
                | TocChange::PutDirectory { path }
                | TocChange::PutSymlink { path, .. }
                | TocChange::PutNamedPipe { path }
                | TocChange::PutDevice { path, .. } => {
                    if let Some(entry) = metadata.get(path) {
                        joined_metadata.insert(path.clone(), (*entry).clone());
                    } else {
                        joined_metadata.remove(path);
                    }
                }
                TocChange::RemoveFile { path } => {
                    joined_metadata.remove(path);
                }
                TocChange::RemoveDirectory { path } => {
                    let prefix = format!("{}/", path.as_str());
                    joined_metadata.retain(|existing, _| {
                        existing != path && !existing.as_str().starts_with(&prefix)
                    });
                }
            }
            match change {
                TocChange::PutFile { path, entry } => {
                    if let Some(source) = entry.source_commit
                        && !selected_ids.contains(&source)
                    {
                        let source_commit = commits
                            .iter()
                            .find(|candidate| candidate.header.commit_id == source)
                            .ok_or("missing reference source commit")?;
                        let output_data_encrypted = encryption.is_some_and(|(_, _, scope)| {
                            matches!(
                                scope,
                                EncryptionScope::Data | EncryptionScope::HeaderAndData
                            )
                        });
                        if source_commit.validated.encryption.is_data_encrypted()
                            != output_data_encrypted
                        {
                            return Err(format!("cannot preserve reference for {path}: source and joined commit have different data encryption").into());
                        }
                        if source_commit.validated.encryption.is_header_encrypted()
                            || source_commit.validated.encryption.is_data_encrypted()
                        {
                            let password = encryption.map(|(password, _, _)| password).ok_or("cannot preserve an encrypted source reference in an unencrypted joined commit")?;
                            let offset = source_commit
                                .data_start
                                .checked_add(source_commit.header.data_section_size)
                                .ok_or("source header offset overflow")?;
                            input.seek(io::SeekFrom::Start(offset))?;
                            if read_header_with_password(&mut input, limits, Some(password))
                                .is_err()
                            {
                                return Err(format!("cannot preserve reference for {path}: source uses a different password").into());
                            }
                        }
                        written_files.remove(path);
                        written_references.insert(path.clone(), entry.clone());
                        continue;
                    }
                    written_references.remove(path);
                    let source_blocks = match entry.source_commit {
                        Some(source) => historical_blocks
                            .get(&source)
                            .ok_or("missing joined source commit")?,
                        None => &blocks,
                    };
                    let mut contents = Vec::new();
                    for index in &entry.block_indices {
                        let block = source_blocks
                            .get(index)
                            .ok_or_else(|| format!("TOC references unavailable block {index}"))?;
                        if let Some(offset) = entry.offset_in_block {
                            if entry.block_indices.len() != 1 {
                                return Err(format!(
                                    "packed file {path} must reference exactly one block"
                                )
                                .into());
                            }
                            let start = usize::try_from(offset)
                                .map_err(|_| format!("packed file offset overflow for {path}"))?;
                            let end = start
                                .checked_add(
                                    usize::try_from(entry.size)
                                        .map_err(|_| format!("file size overflow for {path}"))?,
                                )
                                .filter(|&end| end <= block.len())
                                .ok_or_else(|| {
                                    format!("packed file range exceeds block for {path}")
                                })?;
                            contents.extend_from_slice(&block[start..end]);
                        } else {
                            contents.extend_from_slice(block);
                        }
                    }
                    if contents.len() as u64 != entry.size {
                        return Err(format!("decoded size mismatch for {path}").into());
                    }
                    written_files.insert(path.clone(), contents);
                }
                TocChange::RemoveFile { path } => {
                    written_files.remove(path);
                    written_references.remove(path);
                    joined_special.remove(path);
                }
                TocChange::RemoveDirectory { path } => {
                    let prefix = format!("{}/", path.as_str());
                    written_files.retain(|existing, _| {
                        existing != path && !existing.as_str().starts_with(&prefix)
                    });
                    written_references.retain(|existing, _| {
                        existing != path && !existing.as_str().starts_with(&prefix)
                    });
                    joined_special.retain(|existing, _| {
                        existing != path && !existing.as_str().starts_with(&prefix)
                    });
                }
                TocChange::PutDirectory { .. } => {}
                TocChange::PutSymlink { path, target } => {
                    joined_special.insert(
                        path.clone(),
                        TocEntry::Symlink {
                            target: target.clone(),
                        },
                    );
                }
                TocChange::PutNamedPipe { path } => {
                    joined_special.insert(path.clone(), TocEntry::NamedPipe);
                }
                TocChange::PutDevice {
                    path,
                    kind,
                    major,
                    minor,
                } => {
                    joined_special.insert(
                        path.clone(),
                        TocEntry::Device {
                            kind: *kind,
                            major: *major,
                            minor: *minor,
                        },
                    );
                }
            }
        }
        if referenced_selected_ids.contains(&commit_header.commit_id) {
            historical_blocks.insert(commit_header.commit_id, blocks);
        }
    }
    let mut changes = Vec::new();
    let mut rewritten_paths = std::collections::HashSet::new();
    for (path, entry) in prefix_toc.iter() {
        match (entry, joined_toc.get(path)) {
            (TocEntry::Directory, Some(TocEntry::Directory))
            | (TocEntry::File(_), Some(TocEntry::File(_)))
            | (TocEntry::Symlink { .. }, Some(TocEntry::Symlink { .. }))
            | (TocEntry::NamedPipe, Some(TocEntry::NamedPipe))
            | (TocEntry::Device { .. }, Some(TocEntry::Device { .. })) => {}
            (TocEntry::Directory, _) => {
                changes.push(TocChange::RemoveDirectory { path: path.clone() })
            }
            (
                TocEntry::File(_)
                | TocEntry::Symlink { .. }
                | TocEntry::NamedPipe
                | TocEntry::Device { .. },
                _,
            ) => {
                changes.push(TocChange::RemoveFile { path: path.clone() });
                rewritten_paths.insert(path.clone());
            }
        }
    }
    for (path, entry) in joined_toc.iter() {
        if !matches!(entry, TocEntry::File(_) | TocEntry::Directory) {
            let unchanged = prefix_toc.get(path) == Some(entry) && !rewritten_paths.contains(path);
            if !unchanged {
                match entry {
                    TocEntry::Symlink { target } => changes.push(TocChange::PutSymlink {
                        path: path.clone(),
                        target: target.clone(),
                    }),
                    TocEntry::NamedPipe => {
                        changes.push(TocChange::PutNamedPipe { path: path.clone() })
                    }
                    TocEntry::Device { kind, major, minor } => changes.push(TocChange::PutDevice {
                        path: path.clone(),
                        kind: *kind,
                        major: *major,
                        minor: *minor,
                    }),
                    TocEntry::File(_) | TocEntry::Directory => unreachable!(),
                }
            }
            continue;
        }
        match entry {
            TocEntry::Directory if !matches!(prefix_toc.get(path), Some(TocEntry::Directory)) => {
                changes.push(TocChange::PutDirectory { path: path.clone() });
            }
            TocEntry::File(file_entry)
                if !matches!(prefix_toc.get(path), Some(TocEntry::File(_)))
                    || written_files.contains_key(path)
                    || written_references.contains_key(path) =>
            {
                changes.push(TocChange::PutFile {
                    path: path.clone(),
                    entry: file_entry.clone(),
                });
            }
            _ => {}
        }
    }

    let id = TEMP_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let unique_id = unique_temp_file_id()?;
    let stem = archive_path
        .file_name()
        .ok_or("archive path has no filename")?
        .to_string_lossy();
    let _staged_commit = parent.join(format!(".{stem}.zarc-join-{unique_id}-{id}.tmp"));
    let staged_archive = parent.join(format!(".{stem}.zarc-join-full-{unique_id}-{id}.tmp"));
    let mut cleanup = TemporaryFiles(Vec::new());
    let mut data = Vec::new();
    let mut next_block_index = 0_u32;
    let mut block_sizes = std::collections::HashMap::<u32, u64>::new();
    let mut block_locations = Vec::new();
    let mut small_packer = SmallFilePacker::new(options.block_size);
    let mut joined_dedup = HashMap::<(u64, u64), Vec<(ArchivePath, FileEntry)>>::new();
    let new_commit_id = next_commit_id(archive_path)?;
    let (dek, descriptor, scope, data_encryption) = match encryption {
        Some((password, algorithm, scope)) => {
            if password.is_empty() {
                return Err("the encryption password must not be empty".into());
            }
            let dek = Zeroizing::new(generate_dek()?);
            let descriptor = EncryptionDescriptor::Password {
                scope,
                algorithm,
                nonce: generate_nonce()?,
                key_wrap: wrap_dek_with_password(password, &dek, algorithm, 65_536, 3, 1)?,
            }
            .encode()?;
            let provisional = CommitHeader::new(0, new_commit_id, 0, 0)?;
            let data_encryption = matches!(
                scope,
                EncryptionScope::Data | EncryptionScope::HeaderAndData
            )
            .then(|| EncryptionContext::new(Zeroizing::new(*dek), provisional, algorithm));
            (Some(dek), descriptor, Some(scope), data_encryption)
        }
        None => (None, UNENCRYPTED_DESCRIPTOR.to_vec(), None, None),
    };
    for change in &mut changes {
        if let TocChange::PutFile { path, entry } = change {
            if let Some(reference) = written_references.get(path) {
                *entry = reference.clone();
                continue;
            }
            let contents = written_files
                .get(path)
                .ok_or_else(|| format!("missing data for joined file {path}"))?;
            let mut hasher = Xxh64::new(0);
            hasher.update(contents);
            let checksum = hasher.digest();
            if let Some(existing) =
                joined_dedup
                    .get(&(entry.size, checksum))
                    .and_then(|candidates| {
                        candidates
                            .iter()
                            .find(|(candidate, _)| written_files.get(candidate) == Some(contents))
                    })
            {
                *entry = existing.1.clone();
                continue;
            }
            if entry.size > 8 && entry.size < options.block_size as u64 {
                let (block_index, offset_in_block, completed) = small_packer
                    .add(contents.clone(), checksum, false, || {
                        let index = next_block_index;
                        next_block_index = next_block_index
                            .checked_add(1)
                            .ok_or_else(|| "too many joined blocks".to_owned())?;
                        Ok(index)
                    })
                    .map_err(io::Error::other)?;
                if let Some(block) = completed {
                    write_joined_block(
                        &mut data,
                        &mut block_sizes,
                        &mut block_locations,
                        block,
                        options.compression_level,
                        data_encryption.as_ref(),
                    )?;
                }
                *entry = FileEntry::new(entry.size, vec![block_index])?
                    .with_block_offset(offset_in_block)
                    .with_checksum(checksum);
                joined_dedup
                    .entry((entry.size, checksum))
                    .or_default()
                    .push((path.clone(), entry.clone()));
                continue;
            }
            let mut indices = Vec::new();
            for chunk in contents.chunks(options.block_size) {
                let index = next_block_index;
                next_block_index = next_block_index
                    .checked_add(1)
                    .ok_or("too many joined blocks")?;
                let block = encode_block(
                    index,
                    chunk,
                    options.compression_level,
                    false,
                    data_encryption.as_ref(),
                )?;
                block_sizes.insert(index, block.payload.len() as u64);
                write_joined_frame(&mut data, &mut block_locations, &block)?;
                indices.push(index);
            }
            *entry = FileEntry::new(entry.size, indices)?;
            if entry.size != 0 {
                entry.checksum = Some(checksum);
            }
            joined_dedup
                .entry((entry.size, checksum))
                .or_default()
                .push((path.clone(), entry.clone()));
        }
    }
    if let Some(block) = small_packer.take_block().map_err(io::Error::other)? {
        write_joined_block(
            &mut data,
            &mut block_sizes,
            &mut block_locations,
            block,
            options.compression_level,
            data_encryption.as_ref(),
        )?;
    }
    let entry_metadata = changes
        .iter()
        .filter_map(|change| match change {
            TocChange::PutFile { path, .. }
            | TocChange::PutDirectory { path }
            | TocChange::PutSymlink { path, .. }
            | TocChange::PutNamedPipe { path }
            | TocChange::PutDevice { path, .. } => joined_metadata.remove(path),
            TocChange::RemoveFile { .. } | TocChange::RemoveDirectory { .. } => None,
        })
        .collect();
    let logical_header = LogicalHeader::with_block_size(changes.clone(), options.block_size as u32)
        .with_block_index(block_locations)
        .with_entry_metadata(entry_metadata);
    let mut group_sizes = group_size_metadata(&logical_header, &block_sizes)?;
    group_sizes.extend(custom_metadata);
    group_sizes.extend(commit_metadata(None)?);
    let header_bytes = logical_header.with_metadata(group_sizes).encode()?;
    let data_section_size = data.len() as u64;
    let temp_ch = CommitHeader::new(0, new_commit_id, data_section_size, 0)?;
    let encrypted_header = matches!(
        scope,
        Some(EncryptionScope::Header | EncryptionScope::HeaderAndData)
    );
    let make_header = |commit_header| -> Result<HeaderFrame, Box<dyn std::error::Error>> {
        if encrypted_header {
            Ok(HeaderFrame::from_uncompressed_encrypted(
                commit_header,
                &header_bytes,
                descriptor.clone(),
                options.compression_level,
                dek.as_deref()
                    .ok_or("encrypted output is missing its key")?,
            )?)
        } else {
            Ok(HeaderFrame::from_uncompressed(
                commit_header,
                &header_bytes,
                descriptor.clone(),
                options.compression_level,
            )?)
        }
    };
    let staged_header = make_header(temp_ch)?;
    let header_size = u32::try_from(staged_header.encoded_size()?)?;
    let commit_header = CommitHeader::new(0, new_commit_id, data_section_size, header_size)?;
    let header = make_header(commit_header.clone())?;

    let selected_set = selected
        .into_iter()
        .collect::<std::collections::HashSet<_>>();
    let merged_body_start = data.len() as u64;
    let mut merged_body = data;
    header.write_to(&mut merged_body)?;
    let merged_body = merged_body;

    let mut output = OpenOptions::new()
        .write(true)
        .read(true)
        .create_new(true)
        .open(&staged_archive)?;
    cleanup.0.push(staged_archive.clone());
    crate::ContainerHeader::new(0).write_to(&mut output)?;
    let mut previous_link_position = None;
    let mut output_commits = 0usize;

    for (index, commit) in commits.iter().enumerate() {
        if index == first_selected {
            let link_position = output.stream_position()?;
            output.write_all(&0u64.to_le_bytes())?;
            let data_start = output.stream_position()?;
            output.write_all(&merged_body)?;
            let merged_header_offset = data_start
                .checked_add(merged_body_start)
                .ok_or("joined header offset overflow")?;
            output.write_all(&merged_header_offset.to_le_bytes())?;
            if let Some(position) = previous_link_position {
                let end = output.stream_position()?;
                output.seek(SeekFrom::Start(position))?;
                output.write_all(&merged_header_offset.to_le_bytes())?;
                output.seek(SeekFrom::Start(end))?;
            } else {
                output.seek(SeekFrom::Start(4))?;
                output.write_all(&merged_header_offset.to_le_bytes())?;
                output.seek(SeekFrom::End(0))?;
            }
            previous_link_position = Some(link_position);
            output_commits += 1;
        }
        if selected_set.contains(&index) {
            continue;
        }

        let link_position = output.stream_position()?;
        output.write_all(&0u64.to_le_bytes())?;
        let data_start = output.stream_position()?;
        let body_size = commit
            .commit_end
            .checked_sub(commit.data_start)
            .and_then(|size| size.checked_sub(HEADER_OFFSET_SIZE))
            .ok_or("source commit body size underflow")?;
        input.seek(SeekFrom::Start(commit.data_start))?;
        io::copy(&mut (&mut input).take(body_size), &mut output)?;
        let output_header_offset = data_start
            .checked_add(commit.header.data_section_size)
            .ok_or("copied header offset overflow")?;
        output.write_all(&output_header_offset.to_le_bytes())?;
        if let Some(position) = previous_link_position {
            let end = output.stream_position()?;
            output.seek(SeekFrom::Start(position))?;
            output.write_all(&output_header_offset.to_le_bytes())?;
            output.seek(SeekFrom::Start(end))?;
        } else {
            output.seek(SeekFrom::Start(4))?;
            output.write_all(&output_header_offset.to_le_bytes())?;
            output.seek(SeekFrom::End(0))?;
        }
        previous_link_position = Some(link_position);
        output_commits += 1;
    }

    if output_commits == 0 {
        return Err("joining would leave an archive with no commits".into());
    }
    output.flush()?;
    drop(output);

    let mut validation = File::open(&staged_archive)?;
    let mut validation_passwords = PasswordSet::default();
    for commit in &commits {
        if let Some(password) = passwords.password_for(&commit.header.commit_id) {
            validation_passwords.insert_for_commit(commit.header.commit_id, password.to_vec());
        }
    }
    if let Some((password, _, _)) = encryption {
        validation_passwords.insert_for_commit(new_commit_id, password.to_vec());
    }
    let mut output_offset = read_first_header_offset(&mut validation)?;
    let mut validation_count = 0usize;
    while output_offset != 0 {
        let (ch, _, next_offset) = read_commit_at_offset(&mut validation, output_offset, limits)?;
        let (validated, _) =
            read_commit_with_passwords(&mut validation, ch.clone(), limits, &validation_passwords)?;
        if ch.commit_id == new_commit_id && validated.logical_header.is_none() {
            return Err("joined commit failed logical-header validation".into());
        }
        validation_count += 1;
        output_offset = next_offset;
    }
    if validation_count != output_commits {
        return Err("staged archive has an unexpected number of commits".into());
    }
    let _ = load_toc_through_with_passwords(
        staged_archive
            .to_str()
            .ok_or("archive path is not valid UTF-8")?,
        None,
        &validation_passwords,
    )?;
    drop(validation);
    drop(input);
    std::fs::rename(&staged_archive, archive_path)?;
    cleanup.0.retain(|path| path != &staged_archive);
    drop(cleanup);
    Ok(())
}