zarlib 0.18.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
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
use crate::{
    ArchivePath, CommitHeader, CommitValidationLimits, ContainerHeader, ContentAead, DEK_SIZE,
    EncryptionDescriptor, EntryMetadata, HEADER_OFFSET_SIZE, HeaderFrame, MetadataType,
    ValidatedCommit, ValidatedHeader, unwrap_dek_with_password_zeroizing,
};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use sysinfo::System;
use zeroize::Zeroizing;

/// Default extensions whose new data blocks are stored without compression.
pub const SKIP_COMPRESS_EXTENSIONS: [&str; 21] = [
    "gz", "tgz", "bz2", "tbz2", "lzo", "lz4", "lzma", "z", "snappy", "zip", "7z", "rar", "jpg",
    "jpeg", "png", "gif", "mpg", "mpeg", "avi", "mp3", "zar",
];

pub(crate) const COMMIT_CREATED_KEY: &str = "zar.created_unix_millis";
pub(crate) const COMMIT_USER_KEY: &str = "zar.user";

pub(crate) fn commit_metadata(
    username: Option<&str>,
) -> Result<HashMap<String, MetadataType>, Box<dyn std::error::Error>> {
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|error| format!("system clock is before Unix epoch: {error}"))?
        .as_millis();
    let millis = i64::try_from(millis).map_err(|_| "commit timestamp is out of range")?;
    let mut metadata = HashMap::from([(COMMIT_CREATED_KEY.to_owned(), MetadataType::I64(millis))]);
    if let Some(username) = username {
        metadata.insert(
            COMMIT_USER_KEY.to_owned(),
            MetadataType::String(username.to_owned()),
        );
    }
    Ok(metadata)
}

pub(crate) fn current_username() -> Result<String, Box<dyn std::error::Error>> {
    let username = std::env::var("USER").or_else(|_| std::env::var("USERNAME"))?;
    if username.is_empty() {
        return Err("current OS username is empty".into());
    }
    Ok(username)
}

pub fn format_unix_millis(millis: i64) -> String {
    let seconds = millis.div_euclid(1_000);
    let days = seconds.div_euclid(86_400);
    let day_seconds = seconds.rem_euclid(86_400);
    let shifted_days = days + 719_468;
    let era = if shifted_days >= 0 {
        shifted_days
    } else {
        shifted_days - 146_096
    } / 146_097;
    let day_of_era = shifted_days - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let mut year = year_of_era + era * 400;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_prime = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
    year += i64::from(month <= 2);
    let hour = day_seconds / 3_600;
    let minute = day_seconds % 3_600 / 60;
    format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02} UTC")
}

/// Checks the extension against `ZARLIB_SKIP_COMPRESS_EXTENSIONS`, if set, or
/// against [`SKIP_COMPRESS_EXTENSIONS`] otherwise.
///
/// The override is a comma-separated list with optional leading dots and ASCII
/// whitespace. Matching is ASCII case-insensitive; an empty override matches
/// no extensions.
pub fn should_skip_compression(path: &Path) -> bool {
    path.extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| {
            if let Some(extensions) = std::env::var_os("ZARLIB_SKIP_COMPRESS_EXTENSIONS") {
                extensions
                    .as_encoded_bytes()
                    .split(|byte| *byte == b',')
                    .map(|entry| entry.trim_ascii())
                    .map(|entry| entry.strip_prefix(b".").unwrap_or(entry))
                    .any(|entry| {
                        !entry.is_empty() && extension.as_bytes().eq_ignore_ascii_case(entry)
                    })
            } else {
                SKIP_COMPRESS_EXTENSIONS
                    .iter()
                    .any(|known| extension.eq_ignore_ascii_case(known))
            }
        })
}

/// Error raised when strict input scanning rejects unsupported file types.
#[derive(Debug)]
pub struct StrictModeWarning;

impl std::fmt::Display for StrictModeWarning {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("strict mode rejected an unsupported input type")
    }
}

impl std::error::Error for StrictModeWarning {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreateReport {
    pub warnings: Vec<String>,
    pub block_size: usize,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct InputSummary {
    pub files: u64,
    pub empty_files: u64,
    pub tiny_files: u64,
    pub small_files: u64,
    pub big_files: u64,
    pub directories: u64,
    pub symlinks: u64,
    pub named_pipes: u64,
    pub devices: u64,
    pub other_special: u64,
    pub total_bytes: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OverwriteDecision {
    Yes,
    No,
    Always,
    Never,
}

/// Callback receiving progress events while an archive operation runs.
pub trait Progress: Send + Sync {
    fn message(&self, message: &str);
    fn advance(&self, amount: u64);
    fn is_cancelled(&self) -> bool {
        false
    }
    /// Set the operation's estimated total work in bytes.
    fn set_total(&self, _total: u64) {}
    fn start_phase(&self, message: &str, total: u64) {
        self.message(message);
        self.set_total(total);
    }
    fn reset_phase(&self, message: &str, total: u64) {
        self.message(message);
        self.set_total(total);
    }
    fn add_summary(&self, _summary: &InputSummary) {}
    fn extract_summary(&self, summary: &InputSummary) {
        self.add_summary(summary);
    }
    fn is_interactive(&self) -> bool {
        false
    }
    fn warning(&self, _message: &str) {}
    fn confirm_overwrite(
        &self,
        prompt: &str,
    ) -> Result<OverwriteDecision, Box<dyn std::error::Error>> {
        self.confirm(prompt).map(|overwrite| {
            if overwrite {
                OverwriteDecision::Yes
            } else {
                OverwriteDecision::No
            }
        })
    }
    fn confirm(&self, _prompt: &str) -> Result<bool, Box<dyn std::error::Error>> {
        Err("interactive confirmation is unavailable".into())
    }
}

#[derive(Clone, Copy)]
pub struct ProgressReporter<'a>(pub Option<&'a dyn Progress>);

impl<'a> ProgressReporter<'a> {
    pub fn new(callback: Option<&'a dyn Progress>) -> Self {
        Self(callback)
    }

    pub fn inc(&self, amount: u64) {
        if let Some(progress) = self.0 {
            progress.advance(amount);
        }
    }

    pub fn set_total(&self, total: u64) {
        if let Some(progress) = self.0 {
            progress.set_total(total);
        }
    }

    pub fn start_phase(&self, message: &str, total: u64) {
        if let Some(progress) = self.0 {
            progress.start_phase(message, total);
        }
    }

    pub fn reset_phase(&self, message: &str, total: u64) {
        if let Some(progress) = self.0 {
            progress.reset_phase(message, total);
        }
    }

    pub fn input_summary(&self, summary: &InputSummary) {
        if let Some(progress) = self.0 {
            progress.add_summary(summary);
        }
    }

    pub fn extraction_summary(&self, summary: &InputSummary) {
        if let Some(progress) = self.0 {
            progress.extract_summary(summary);
        }
    }

    pub fn set_message(&self, message: impl Into<String>) {
        if let Some(progress) = self.0 {
            progress.message(&message.into());
        }
    }

    pub fn is_cancelled(&self) -> bool {
        self.0.is_some_and(|progress| progress.is_cancelled())
    }

    pub fn check_cancelled(&self) -> io::Result<()> {
        if self.is_cancelled() {
            Err(io::Error::new(
                io::ErrorKind::Interrupted,
                "operation cancelled",
            ))
        } else {
            Ok(())
        }
    }
}

pub(crate) fn copy_interruptibly<R: Read + ?Sized, W: Write + ?Sized>(
    reader: &mut R,
    writer: &mut W,
    progress: &ProgressReporter<'_>,
) -> io::Result<u64> {
    let mut buffer = [0; 128 * 1024];
    let mut copied = 0_u64;
    loop {
        progress.check_cancelled()?;
        let count = reader.read(&mut buffer)?;
        if count == 0 {
            return Ok(copied);
        }
        writer.write_all(&buffer[..count])?;
        copied = copied
            .checked_add(count as u64)
            .ok_or_else(|| io::Error::other("copied data size overflow"))?;
    }
}

pub const CREATE_BLOCK_SIZE: usize = 8 * 1024 * 1024;
pub const AUTO_MIN_BLOCK_SIZE: usize = 1024 * 1024;
pub const MIN_CREATE_BLOCK_SIZE: usize = 64 * 1024;
pub const MAX_CREATE_BLOCK_SIZE: usize = 32 * 1024 * 1024;
pub const DEFAULT_MEMORY_BUDGET_PERCENT: usize = 50;
pub const COMPRESSION_WORKSPACE_MULTIPLIER: usize = 2;
pub const QUEUED_OUTPUT_MULTIPLIER: usize = 2;
pub const FIXED_WORKER_OVERHEAD: usize = 1024 * 1024;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EncodingOptions {
    pub block_size: usize,
    pub compression_level: i32,
}

impl Default for EncodingOptions {
    fn default() -> Self {
        Self {
            block_size: CREATE_BLOCK_SIZE,
            compression_level: 3,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EncodingBudget {
    pub block_size: usize,
    pub workers: usize,
    pub budget_bytes: usize,
    pub estimated_bytes: usize,
    pub warning: bool,
}

pub fn estimate_worker_memory(block_size: usize) -> usize {
    block_size
        .saturating_mul(1 + COMPRESSION_WORKSPACE_MULTIPLIER + QUEUED_OUTPUT_MULTIPLIER)
        .saturating_add(FIXED_WORKER_OVERHEAD)
}

pub fn select_compression_workers(
    block_size: usize,
    available_memory: usize,
    requested_workers: usize,
) -> usize {
    let budget_bytes = available_memory.saturating_mul(DEFAULT_MEMORY_BUDGET_PERCENT) / 100;
    let per_worker_bytes = estimate_worker_memory(block_size).max(1);
    let memory_limited_workers = (budget_bytes / per_worker_bytes).max(1);
    requested_workers.max(1).min(memory_limited_workers)
}

pub fn select_automatic_encoding(
    available_memory: usize,
    requested_workers: usize,
) -> EncodingBudget {
    let budget_bytes = available_memory.saturating_mul(DEFAULT_MEMORY_BUDGET_PERCENT) / 100;
    let requested_workers = requested_workers.max(1);
    let mut workers =
        requested_workers.min((budget_bytes / estimate_worker_memory(AUTO_MIN_BLOCK_SIZE)).max(1));

    loop {
        let per_worker_budget = budget_bytes / workers;
        let affordable = per_worker_budget.saturating_sub(FIXED_WORKER_OVERHEAD)
            / (1 + COMPRESSION_WORKSPACE_MULTIPLIER + QUEUED_OUTPUT_MULTIPLIER);
        if affordable >= AUTO_MIN_BLOCK_SIZE {
            let block_size =
                affordable.min(CREATE_BLOCK_SIZE) / AUTO_MIN_BLOCK_SIZE * AUTO_MIN_BLOCK_SIZE;
            let estimated_bytes = estimate_worker_memory(block_size).saturating_mul(workers);
            return EncodingBudget {
                block_size,
                workers,
                budget_bytes,
                estimated_bytes,
                warning: false,
            };
        }
        if workers == 1 {
            let estimated_bytes = estimate_worker_memory(AUTO_MIN_BLOCK_SIZE);
            return EncodingBudget {
                block_size: AUTO_MIN_BLOCK_SIZE,
                workers: 1,
                budget_bytes,
                estimated_bytes,
                warning: estimated_bytes > budget_bytes,
            };
        }
        workers -= 1;
    }
}

pub fn available_memory_bytes() -> usize {
    static CACHED: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *CACHED.get_or_init(|| {
        if let Ok(mut system) = System::new() {
            system.refresh_memory();
            usize::try_from(system.available_memory()).unwrap_or(usize::MAX)
        } else {
            usize::MAX
        }
    })
}

/// Process-wide overrides for archive worker configuration.
///
/// `None` leaves the corresponding environment variable in effect.
/// A priority of zero keeps the inherited worker priority. Positive priority
/// offsets lower it, just as with `ZARLIB_CPU_PRIORITY`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WorkerOverrides {
    pub cpu_priority: Option<u32>,
    pub max_cpu_count: Option<isize>,
}

static WORKER_OVERRIDES: std::sync::RwLock<WorkerOverrides> =
    std::sync::RwLock::new(WorkerOverrides {
        cpu_priority: None,
        max_cpu_count: None,
    });

/// Changes worker overrides for subsequently configured workers.
///
/// Existing worker pools are not resized or reprioritized. This does not
/// modify the process environment.
pub fn set_worker_overrides(overrides: WorkerOverrides) {
    *WORKER_OVERRIDES
        .write()
        .expect("worker overrides lock poisoned") = overrides;
}

pub(super) fn worker_overrides() -> WorkerOverrides {
    *WORKER_OVERRIDES
        .read()
        .expect("worker overrides lock poisoned")
}

fn requested_worker_count(available: usize, count: isize) -> usize {
    match count {
        0 => available,
        count if count > 0 => count as usize,
        count => available.saturating_sub(count.unsigned_abs()).max(1),
    }
}

/// Returns the requested worker count, accounting for `ZARLIB_MAX_CPU_COUNT`
/// and any process-wide override.
///
/// Unset or zero uses the available parallelism, positive values specify the
/// count, and negative values reserve that many available cores (at least one
/// worker is retained). Invalid values produce a warning and use the default.
pub fn available_compression_workers() -> usize {
    let available = std::thread::available_parallelism().map_or(1, usize::from);
    if let Some(count) = worker_overrides().max_cpu_count {
        return requested_worker_count(available, count);
    }
    match std::env::var("ZARLIB_MAX_CPU_COUNT") {
        Err(std::env::VarError::NotPresent) => available,
        Ok(value) => match value.parse::<isize>() {
            Ok(count) => requested_worker_count(available, count),
            Err(_) => {
                eprintln!("warning: invalid ZARLIB_MAX_CPU_COUNT {value:?}; using available cores");
                available
            }
        },
        Err(std::env::VarError::NotUnicode(value)) => {
            eprintln!("warning: invalid ZARLIB_MAX_CPU_COUNT {value:?}; using available cores");
            available
        }
    }
}

pub fn compression_worker_count(block_size: usize) -> usize {
    #[cfg(target_os = "wasi")]
    let _ = super::worker_priority::worker_priority();
    select_compression_workers(
        block_size,
        available_memory_bytes(),
        available_compression_workers(),
    )
}

pub fn resolve_encoding_options(options: &mut EncodingOptions) -> Option<String> {
    if options.block_size != 0 {
        return None;
    }
    let budget =
        select_automatic_encoding(available_memory_bytes(), available_compression_workers());
    options.block_size = budget.block_size;
    budget.warning.then(|| {
        format!(
            "warning: automatic block size requires an estimated {} bytes, exceeding the {}-byte memory budget",
            budget.estimated_bytes, budget.budget_bytes
        )
    })
}

pub fn parse_block_size(value: &str) -> Result<usize, Box<dyn std::error::Error>> {
    if value == "auto" {
        return Ok(0);
    }
    let (digits, multiplier) = match value.as_bytes().last().copied() {
        Some(b'k' | b'K') => (&value[..value.len() - 1], 1024_usize),
        Some(b'm' | b'M') => (&value[..value.len() - 1], 1024 * 1024),
        _ => (value, 1),
    };
    let size = digits
        .parse::<usize>()
        .map_err(|_| format!("invalid block size `{value}`"))?
        .checked_mul(multiplier)
        .ok_or_else(|| format!("invalid block size `{value}`: value is too large"))?;
    if !(MIN_CREATE_BLOCK_SIZE..=MAX_CREATE_BLOCK_SIZE).contains(&size) {
        return Err(format!(
            "invalid block size `{value}`: choose {MIN_CREATE_BLOCK_SIZE} bytes through {MAX_CREATE_BLOCK_SIZE} bytes"
        )
        .into());
    }
    Ok(size)
}

pub fn parse_compression_level(value: &str) -> Result<i32, Box<dyn std::error::Error>> {
    let level = value
        .parse::<i32>()
        .map_err(|_| format!("invalid compression level `{value}`"))?;
    if !(-7..=22).contains(&level) {
        return Err("invalid compression level: choose a value from -7 through 22".into());
    }
    Ok(level)
}

pub static TEMP_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

pub fn unique_temp_file_id() -> Result<u64, getrandom::Error> {
    let mut id = [0; 8];
    getrandom::fill(&mut id)?;
    Ok(u64::from_ne_bytes(id))
}

pub struct TemporaryFiles(pub Vec<PathBuf>);

impl Drop for TemporaryFiles {
    fn drop(&mut self) {
        for path in &self.0 {
            let _ = std::fs::remove_file(path);
        }
    }
}

pub fn scan_input_summary(
    paths: &[PathBuf],
    cwd: &Path,
) -> Result<InputSummary, Box<dyn std::error::Error>> {
    fn walk(path: &Path, summary: &mut InputSummary) -> Result<(), Box<dyn std::error::Error>> {
        let metadata = std::fs::symlink_metadata(path)?;
        let file_type = metadata.file_type();
        if file_type.is_symlink() {
            summary.symlinks += 1;
        } else if metadata.is_dir() {
            if path.parent().is_some() {
                summary.directories += 1;
            }
            for child in std::fs::read_dir(path)? {
                walk(&child?.path(), summary)?;
            }
        } else if metadata.is_file() {
            summary.files += 1;
            summary.total_bytes = summary
                .total_bytes
                .checked_add(metadata.len())
                .ok_or("input size estimate overflow")?;
            if metadata.len() == 0 {
                summary.empty_files += 1;
            } else if metadata.len() <= 8 {
                summary.tiny_files += 1;
            } else if metadata.len() < 8 * 1024 * 1024 {
                summary.small_files += 1;
            } else {
                summary.big_files += 1;
            }
        } else {
            #[cfg(unix)]
            {
                use std::os::unix::fs::FileTypeExt;
                if file_type.is_fifo() {
                    summary.named_pipes += 1;
                } else if file_type.is_char_device() || file_type.is_block_device() {
                    summary.devices += 1;
                } else {
                    summary.other_special += 1;
                }
            }
            #[cfg(not(unix))]
            {
                summary.other_special += 1;
            }
        }
        Ok(())
    }
    let mut summary = InputSummary::default();
    for input in paths {
        let source = if input.is_absolute() {
            input.clone()
        } else {
            cwd.join(input)
        };
        walk(&source, &mut summary)?;
    }
    Ok(summary)
}

#[cfg(unix)]
pub fn platform_identifier() -> &'static str {
    "unix"
}

#[cfg(windows)]
pub fn platform_identifier() -> &'static str {
    "windows"
}

#[cfg(not(any(unix, windows)))]
pub fn platform_identifier() -> &'static str {
    "other"
}

pub fn modified_unix_millis(metadata: &std::fs::Metadata) -> Option<i64> {
    system_time_unix_millis(metadata.modified().ok()?)
}

pub fn created_unix_millis(metadata: &std::fs::Metadata) -> Option<i64> {
    system_time_unix_millis(metadata.created().ok()?)
}

pub fn accessed_unix_millis(metadata: &std::fs::Metadata) -> Option<i64> {
    system_time_unix_millis(metadata.accessed().ok()?)
}

fn system_time_unix_millis(time: std::time::SystemTime) -> Option<i64> {
    let millis = match time.duration_since(std::time::UNIX_EPOCH) {
        Ok(duration) => i128::try_from(duration.as_millis()).ok()?,
        Err(error) => -(error.duration().as_millis() as i128),
    };
    i64::try_from(millis).ok()
}

/// Drops unrequested timestamps and omits records that carry no data.
pub fn finalize_entry_metadata(
    mut entries: Vec<EntryMetadata>,
    save_modification_time: bool,
    save_creation_time: bool,
    save_access_time: bool,
) -> Vec<EntryMetadata> {
    if !save_modification_time {
        for entry in &mut entries {
            entry.modified_unix_millis = None;
        }
    }
    if !save_creation_time {
        for entry in &mut entries {
            entry.created_unix_millis = None;
        }
    }
    if !save_access_time {
        for entry in &mut entries {
            entry.accessed_unix_millis = None;
        }
    }
    entries.retain(|entry| {
        entry.owner.is_some()
            || entry.group.is_some()
            || entry.permissions.is_some()
            || entry.modified_unix_millis.is_some()
            || entry.created_unix_millis.is_some()
            || entry.accessed_unix_millis.is_some()
    });
    entries
}

pub fn require_creation_times(entries: &[EntryMetadata]) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(entry) = entries
        .iter()
        .find(|entry| entry.created_unix_millis.is_none())
    {
        return Err(format!("creation time unavailable for {}", entry.path).into());
    }
    Ok(())
}

pub fn require_access_times(entries: &[EntryMetadata]) -> Result<(), Box<dyn std::error::Error>> {
    if let Some(entry) = entries
        .iter()
        .find(|entry| entry.accessed_unix_millis.is_none())
    {
        return Err(format!("access time unavailable for {}", entry.path).into());
    }
    Ok(())
}

pub fn entry_date_metadata(
    path: &ArchivePath,
    modified_unix_millis: Option<i64>,
    created_unix_millis: Option<i64>,
    accessed_unix_millis: Option<i64>,
) -> EntryMetadata {
    EntryMetadata {
        path: path.clone(),
        platform: platform_identifier().to_owned(),
        owner: None,
        group: None,
        permissions: None,
        modified_unix_millis,
        created_unix_millis,
        accessed_unix_millis,
    }
}

#[cfg(unix)]
pub fn capture_entry_metadata(
    path: &ArchivePath,
    metadata: &std::fs::Metadata,
    save_metadata: bool,
) -> Result<EntryMetadata, Box<dyn std::error::Error>> {
    use std::os::unix::fs::MetadataExt;
    Ok(EntryMetadata {
        path: path.clone(),
        platform: platform_identifier().to_owned(),
        owner: save_metadata.then(|| metadata.uid()),
        group: save_metadata.then(|| metadata.gid()),
        permissions: save_metadata.then(|| metadata.mode() & 0o7777),
        modified_unix_millis: modified_unix_millis(metadata),
        created_unix_millis: created_unix_millis(metadata),
        accessed_unix_millis: accessed_unix_millis(metadata),
    })
}

#[cfg(windows)]
pub fn capture_entry_metadata(
    path: &ArchivePath,
    metadata: &std::fs::Metadata,
    save_metadata: bool,
) -> Result<EntryMetadata, Box<dyn std::error::Error>> {
    Ok(EntryMetadata {
        path: path.clone(),
        platform: platform_identifier().to_owned(),
        owner: None,
        group: None,
        permissions: save_metadata.then(|| u32::from(metadata.permissions().readonly())),
        modified_unix_millis: modified_unix_millis(metadata),
        created_unix_millis: created_unix_millis(metadata),
        accessed_unix_millis: accessed_unix_millis(metadata),
    })
}

#[cfg(not(any(unix, windows)))]
pub fn capture_entry_metadata(
    path: &ArchivePath,
    metadata: &std::fs::Metadata,
    save_metadata: bool,
) -> Result<EntryMetadata, Box<dyn std::error::Error>> {
    if save_metadata {
        return Err("metadata preservation is unsupported on this platform".into());
    }
    Ok(entry_date_metadata(
        path,
        modified_unix_millis(metadata),
        created_unix_millis(metadata),
        accessed_unix_millis(metadata),
    ))
}

pub fn push_unique_path(
    path: ArchivePath,
    seen_paths: &mut std::collections::BTreeSet<ArchivePath>,
) -> Result<(), Box<dyn std::error::Error>> {
    if !seen_paths.insert(path.clone()) {
        return Err(format!("duplicate archive path: {path}").into());
    }
    Ok(())
}

pub fn commit_id(value: u32) -> [u8; 4] {
    value.to_le_bytes()
}

pub fn parse_commit_id(value: &str) -> Result<[u8; 4], Box<dyn std::error::Error>> {
    if value.len() != 8 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err("commit ID must contain exactly 8 hexadecimal digits".into());
    }
    Ok(u32::from_str_radix(value, 16)?.to_le_bytes())
}

pub fn next_commit_id(archive: &Path) -> Result<[u8; 4], Box<dyn std::error::Error>> {
    let mut file = File::open(archive)?;
    let limits = CommitValidationLimits::default();
    let first_header_offset = read_first_header_offset(&mut file)?;
    let mut highest_id = 0_u32;
    let mut header_offset = first_header_offset;
    while header_offset != 0 {
        let (commit_header, _, next_header_offset) =
            read_commit_at_offset(&mut file, header_offset, limits)?;
        highest_id = highest_id.max(u32::from_le_bytes(commit_header.commit_id));
        header_offset = next_header_offset;
    }
    Ok(highest_id
        .checked_add(1)
        .ok_or("commit ID counter exhausted")?
        .to_le_bytes())
}

pub fn encode_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut output = String::with_capacity(bytes.len() * 2);
    for &byte in bytes {
        output.push(HEX[(byte >> 4) as usize] as char);
        output.push(HEX[(byte & 0x0f) as usize] as char);
    }
    output
}

pub fn skip_exact(file: &mut File, mut remaining: u64) -> io::Result<()> {
    let mut buffer = [0_u8; 8192];
    while remaining > 0 {
        let chunk = remaining.min(buffer.len() as u64) as usize;
        file.read_exact(&mut buffer[..chunk])?;
        remaining -= chunk as u64;
    }
    Ok(())
}

pub fn read_first_header_offset(file: &mut File) -> Result<u64, Box<dyn std::error::Error>> {
    read_first_header_offset_from_reader(file)
}

pub(crate) fn read_first_header_offset_from_reader(
    file: &mut impl Read,
) -> Result<u64, Box<dyn std::error::Error>> {
    let container = ContainerHeader::read_from(file)?;
    Ok(container.first_header_offset)
}

pub fn read_commit_at_offset(
    file: &mut File,
    header_offset: u64,
    limits: CommitValidationLimits,
) -> Result<(CommitHeader, u64, u64), Box<dyn std::error::Error>> {
    read_commit_at_offset_from_reader(file, header_offset, limits)
}

pub(crate) fn read_commit_at_offset_from_reader(
    file: &mut (impl Read + Seek),
    header_offset: u64,
    limits: CommitValidationLimits,
) -> Result<(CommitHeader, u64, u64), Box<dyn std::error::Error>> {
    if header_offset == 0 {
        return Err("invalid header offset: 0".into());
    }
    file.seek(SeekFrom::Start(header_offset))?;
    let header_frame = HeaderFrame::read_from(file, limits.max_frame_payload_size)?;
    let commit_header = header_frame.commit_header.clone();
    let data_start = header_offset
        .checked_sub(commit_header.data_section_size)
        .ok_or("data section offset underflow")?;
    let next_offset_pos = data_start
        .checked_sub(HEADER_OFFSET_SIZE)
        .ok_or("next_header_offset position underflow")?;
    file.seek(SeekFrom::Start(next_offset_pos))?;
    let mut next_offset_bytes = [0u8; 8];
    file.read_exact(&mut next_offset_bytes)?;
    let next_header_offset = u64::from_le_bytes(next_offset_bytes);
    file.seek(SeekFrom::Start(data_start))?;
    Ok((commit_header, data_start, next_header_offset))
}

pub fn find_last_commit(
    file: &mut File,
    limits: CommitValidationLimits,
) -> Result<(u64, CommitHeader), Box<dyn std::error::Error>> {
    let file_len = file.metadata()?.len();
    if file_len < crate::CONTAINER_HEADER_SIZE + HEADER_OFFSET_SIZE {
        return Err("archive is too small to contain a commit".into());
    }
    let this_offset_pos = file_len - HEADER_OFFSET_SIZE;
    file.seek(SeekFrom::Start(this_offset_pos))?;
    let mut bytes = [0u8; 8];
    file.read_exact(&mut bytes)?;
    let header_offset = u64::from_le_bytes(bytes);
    if header_offset == 0 || header_offset >= file_len {
        return Err("archive has no valid last commit".into());
    }
    file.seek(SeekFrom::Start(header_offset))?;
    let header_frame = HeaderFrame::read_from(file, limits.max_frame_payload_size)?;
    Ok((header_offset, header_frame.commit_header))
}

#[derive(Clone, Copy)]
pub(crate) struct ReusableEmptyTail {
    pub commit_id: [u8; 4],
    pub link_position: u64,
    pub incoming_link_position: u64,
    pub is_root: bool,
}

pub(crate) fn find_reusable_empty_tail(
    archive_path: &Path,
    passwords: &PasswordSet,
) -> Result<Option<ReusableEmptyTail>, Box<dyn std::error::Error>> {
    let mut file = File::open(archive_path)?;
    let limits = CommitValidationLimits::default();
    let first_header_offset = read_first_header_offset(&mut file)?;
    if first_header_offset == 0 {
        return Ok(None);
    }
    let (header_offset, commit_header) = find_last_commit(&mut file, limits)?;
    let mut incoming_link_position = 4;
    let mut current_offset = first_header_offset;
    while current_offset != header_offset {
        let (_, data_start, next_header_offset) =
            read_commit_at_offset(&mut file, current_offset, limits)?;
        if next_header_offset == 0 {
            return Err("last archive commit is not reachable from the container header".into());
        }
        incoming_link_position = data_start
            .checked_sub(HEADER_OFFSET_SIZE)
            .ok_or("previous commit offset underflow")?;
        current_offset = next_header_offset;
    }
    let (validated_header, data_start, next_header_offset) =
        read_commit_at_offset(&mut file, header_offset, limits)?;
    if validated_header.commit_id != commit_header.commit_id || next_header_offset != 0 {
        return Err("last archive commit changed while checking for reuse".into());
    }
    if commit_header.data_section_size != 0 {
        return Ok(None);
    }
    let (validated, _) =
        read_commit_with_passwords(&mut file, commit_header.clone(), limits, passwords)?;
    let Some(header) = validated.logical_header else {
        return Ok(None);
    };
    if !header.changes.is_empty()
        || !header.entry_metadata.is_empty()
        || header
            .metadata
            .keys()
            .any(|key| key != COMMIT_CREATED_KEY && key != COMMIT_USER_KEY)
    {
        return Ok(None);
    }
    let link_position = data_start
        .checked_sub(HEADER_OFFSET_SIZE)
        .ok_or("last commit offset underflow")?;
    Ok(Some(ReusableEmptyTail {
        commit_id: commit_header.commit_id,
        link_position,
        incoming_link_position,
        is_root: first_header_offset == header_offset,
    }))
}

pub fn ensure_archive_unencrypted(archive_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let mut file = File::open(archive_path)?;
    let limits = CommitValidationLimits::default();
    let first_header_offset = read_first_header_offset(&mut file)?;
    let mut header_offset = first_header_offset;
    let mut visited = HashSet::new();
    while header_offset != 0 {
        if !visited.insert(header_offset) {
            return Err("archive commit chain contains a cycle".into());
        }
        file.seek(SeekFrom::Start(header_offset))?;
        let header_frame = HeaderFrame::read_from(&mut file, limits.max_frame_payload_size)?;
        let (descriptor, _) = EncryptionDescriptor::decode(&header_frame.encryption_descriptor)?;
        if descriptor.is_header_encrypted() || descriptor.is_data_encrypted() {
            return Err(
                "mutations on archives containing encrypted commits are unsupported".into(),
            );
        }
        let (_, _, next_header_offset) = read_commit_at_offset(&mut file, header_offset, limits)?;
        header_offset = next_header_offset;
    }
    Ok(())
}

pub type UnlockedCommit = (ValidatedCommit, Option<Zeroizing<[u8; DEK_SIZE]>>);
pub type UnlockedHeader = (ValidatedHeader, Option<Zeroizing<[u8; DEK_SIZE]>>);

#[derive(Clone, Default, PartialEq, Eq)]
pub struct PasswordSet {
    default: Option<Zeroizing<Vec<u8>>>,
    by_commit: BTreeMap<[u8; 4], Zeroizing<Vec<u8>>>,
}

impl PasswordSet {
    pub fn new(default: Option<Vec<u8>>) -> Self {
        Self {
            default: default.map(Zeroizing::new),
            by_commit: BTreeMap::new(),
        }
    }

    pub fn insert_for_commit(&mut self, commit_id: [u8; 4], password: Vec<u8>) {
        self.by_commit.insert(commit_id, Zeroizing::new(password));
    }

    pub fn password_for(&self, commit_id: &[u8; 4]) -> Option<&[u8]> {
        self.by_commit
            .get(commit_id)
            .or(self.default.as_ref())
            .map(|password| password.as_slice())
    }
}

pub fn read_header_with_password(
    file: &mut File,
    limits: CommitValidationLimits,
    password: Option<&[u8]>,
) -> Result<UnlockedHeader, Box<dyn std::error::Error>> {
    let passwords = PasswordSet::new(password.map(<[u8]>::to_vec));
    read_header_with_passwords(file, limits, &passwords)
}

pub fn read_header_with_passwords(
    file: &mut File,
    limits: CommitValidationLimits,
    passwords: &PasswordSet,
) -> Result<UnlockedHeader, Box<dyn std::error::Error>> {
    read_header_with_passwords_from_reader(file, limits, passwords)
}

pub(crate) fn read_header_with_passwords_from_reader(
    file: &mut impl Read,
    limits: CommitValidationLimits,
    passwords: &PasswordSet,
) -> Result<UnlockedHeader, Box<dyn std::error::Error>> {
    let header_frame = HeaderFrame::read_from(file, limits.max_frame_payload_size)?;
    let password = passwords.password_for(&header_frame.commit_header.commit_id);
    let (descriptor, _) = EncryptionDescriptor::decode(&header_frame.encryption_descriptor)?;
    let key = match (password, descriptor) {
        (Some(password), EncryptionDescriptor::Password { key_wrap, .. }) => {
            Some(unwrap_dek_with_password_zeroizing(password, &key_wrap)?)
        }
        (Some(password), EncryptionDescriptor::PasswordAndRecipients { password: wrap, .. }) => {
            Some(unwrap_dek_with_password_zeroizing(password, &wrap)?)
        }
        (Some(_), descriptor)
            if descriptor.is_header_encrypted() || descriptor.is_data_encrypted() =>
        {
            return Err("this encryption descriptor cannot be unlocked with a password".into());
        }
        _ => None,
    };
    let validated = ValidatedHeader::from_header_frame(header_frame, limits, key.as_deref())?;
    Ok((validated, key))
}

pub fn read_commit_with_password(
    file: &mut File,
    commit_header: CommitHeader,
    limits: CommitValidationLimits,
    password: Option<&[u8]>,
) -> Result<UnlockedCommit, Box<dyn std::error::Error>> {
    let passwords = PasswordSet::new(password.map(<[u8]>::to_vec));
    read_commit_with_passwords(file, commit_header, limits, &passwords)
}

pub fn read_commit_with_passwords(
    file: &mut File,
    commit_header: CommitHeader,
    limits: CommitValidationLimits,
    passwords: &PasswordSet,
) -> Result<UnlockedCommit, Box<dyn std::error::Error>> {
    let data_start = file.stream_position()?;
    let header_offset = data_start
        .checked_add(commit_header.data_section_size)
        .ok_or("header offset overflow")?;
    file.seek(SeekFrom::Start(header_offset))?;
    let header = HeaderFrame::read_from(file, limits.max_frame_payload_size)?;
    let password = passwords.password_for(&commit_header.commit_id);
    let (descriptor, _) = EncryptionDescriptor::decode(&header.encryption_descriptor)?;
    let key = match (password, descriptor) {
        (Some(password), EncryptionDescriptor::Password { key_wrap, .. }) => {
            Some(unwrap_dek_with_password_zeroizing(password, &key_wrap)?)
        }
        (Some(password), EncryptionDescriptor::PasswordAndRecipients { password: wrap, .. }) => {
            Some(unwrap_dek_with_password_zeroizing(password, &wrap)?)
        }
        (Some(_), descriptor)
            if descriptor.is_header_encrypted() || descriptor.is_data_encrypted() =>
        {
            return Err("this encryption descriptor cannot be unlocked with a password".into());
        }
        _ => None,
    };
    file.seek(SeekFrom::Start(data_start))?;
    let validated = match key.as_ref() {
        Some(key) => ValidatedCommit::read_body_with_key(file, commit_header, limits, key)?,
        None => ValidatedCommit::read_body(file, commit_header, limits)?,
    };
    Ok((validated, key))
}

pub fn extraction_content_nonce(descriptor: &EncryptionDescriptor) -> Option<[u8; 12]> {
    match descriptor {
        EncryptionDescriptor::Unencrypted => None,
        EncryptionDescriptor::Symmetric { nonce, .. }
        | EncryptionDescriptor::Password { nonce, .. }
        | EncryptionDescriptor::Recipients { nonce, .. }
        | EncryptionDescriptor::PasswordAndRecipients { nonce, .. } => Some(*nonce),
    }
}

pub fn encryption_algorithm(descriptor: &EncryptionDescriptor) -> Option<ContentAead> {
    match descriptor {
        EncryptionDescriptor::Unencrypted => None,
        EncryptionDescriptor::Symmetric { algorithm, .. }
        | EncryptionDescriptor::Password { algorithm, .. }
        | EncryptionDescriptor::Recipients { algorithm, .. }
        | EncryptionDescriptor::PasswordAndRecipients { algorithm, .. } => Some(*algorithm),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_archives_have_no_reusable_tail_or_last_commit() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("empty.zar");
        let mut file = File::create(&path).unwrap();
        ContainerHeader::new(0).write_to(&mut file).unwrap();
        drop(file);

        assert!(
            find_reusable_empty_tail(&path, &PasswordSet::default())
                .unwrap()
                .is_none()
        );
        assert!(ensure_archive_unencrypted(&path).is_ok());
        let mut file = File::open(path).unwrap();
        assert!(find_last_commit(&mut file, CommitValidationLimits::default()).is_err());
    }

    #[test]
    fn progress_reporter_forwards_callbacks_and_checks_cancellation() {
        struct Callbacks {
            cancelled: bool,
            messages: std::sync::Mutex<Vec<String>>,
            advances: std::sync::Mutex<Vec<u64>>,
            totals: std::sync::Mutex<Vec<u64>>,
            summaries: std::sync::Mutex<Vec<InputSummary>>,
        }

        impl Progress for Callbacks {
            fn message(&self, message: &str) {
                self.messages.lock().unwrap().push(message.to_owned());
            }

            fn advance(&self, amount: u64) {
                self.advances.lock().unwrap().push(amount);
            }

            fn is_cancelled(&self) -> bool {
                self.cancelled
            }

            fn set_total(&self, total: u64) {
                self.totals.lock().unwrap().push(total);
            }

            fn add_summary(&self, summary: &InputSummary) {
                self.summaries.lock().unwrap().push(summary.clone());
            }

            fn confirm(&self, _: &str) -> Result<bool, Box<dyn std::error::Error>> {
                Ok(true)
            }
        }

        let callback = Callbacks {
            cancelled: false,
            messages: std::sync::Mutex::new(Vec::new()),
            advances: std::sync::Mutex::new(Vec::new()),
            totals: std::sync::Mutex::new(Vec::new()),
            summaries: std::sync::Mutex::new(Vec::new()),
        };
        let reporter = ProgressReporter::new(Some(&callback));
        reporter.inc(5);
        reporter.set_total(10);
        reporter.start_phase("starting", 20);
        reporter.reset_phase("reset", 30);
        reporter.input_summary(&InputSummary {
            files: 1,
            ..InputSummary::default()
        });
        reporter.extraction_summary(&InputSummary {
            directories: 1,
            ..InputSummary::default()
        });
        reporter.set_message("message");
        assert!(!reporter.is_cancelled());
        reporter.check_cancelled().unwrap();
        assert_eq!(
            *callback.messages.lock().unwrap(),
            ["starting", "reset", "message"]
        );
        assert_eq!(*callback.advances.lock().unwrap(), [5]);
        assert_eq!(*callback.totals.lock().unwrap(), [10, 20, 30]);
        assert_eq!(callback.summaries.lock().unwrap().len(), 2);
        assert_eq!(
            callback.confirm_overwrite("overwrite").unwrap(),
            OverwriteDecision::Yes
        );

        let cancelled_callback = Callbacks {
            cancelled: true,
            messages: std::sync::Mutex::new(Vec::new()),
            advances: std::sync::Mutex::new(Vec::new()),
            totals: std::sync::Mutex::new(Vec::new()),
            summaries: std::sync::Mutex::new(Vec::new()),
        };
        let cancelled = ProgressReporter::new(Some(&cancelled_callback));
        assert_eq!(
            cancelled.check_cancelled().unwrap_err().kind(),
            io::ErrorKind::Interrupted
        );
        assert!(ProgressReporter::new(None).check_cancelled().is_ok());
    }
}