dayzmake-core 0.3.1

Readers and writers for DayZ file formats: PBO, rapified config, P3D, PAA, BI keys and signatures, and navmesh generation
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
//! Extracts a whole DayZ install, a mod or a single PBO into one tree organised by prefix.
//!
//! The tree is written to a staging folder next to the target and swapped in with a rename when
//! everything succeeded, so a failed or repeated run never leaves a half-written or stale tree. The
//! entry names, prefixes and PBO files are untrusted: names are validated like [`crate::pbo::unpack`]
//! does and the offenders are skipped with a warning.

use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{self, BufReader, Cursor, Error, ErrorKind, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use crate::config::{Config, WriteOptions, is_rapified};
use crate::error::{ErrorExt, printable};
use crate::pbo::{
    EntryFilter, IndexEntry, decompress_entry, prefix_relative, read_index, safe_relative_path,
    unpack_relative, warn_leading_separator,
};
use crate::warning::{Warning, WarningSink};

/// The file in the target that maps every prefix to its PBO.
const MAP_FILE: &str = "pbo-map.tsv";

/// What [`extract`] does.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ExtractOptions {
    /// Replace an existing target folder instead of failing.
    pub force: bool,
    /// Write every rapified `*.bin` as text, with the extension `.cpp`.
    pub derapify: bool,
    /// Glob patterns of entries to leave out; see [`EntryFilter`].
    pub exclude: Vec<String>,
    /// Glob patterns of the entries to write; see [`EntryFilter`]. Empty means every entry.
    pub only: Vec<String>,
}

/// What [`extract`] wrote.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExtractSummary {
    pbos: usize,
    files: usize,
}

impl ExtractSummary {
    /// The number of PBOs that were read.
    #[must_use]
    pub fn pbos(&self) -> usize {
        self.pbos
    }

    /// The number of files in the tree, without the PBO map.
    #[must_use]
    pub fn files(&self) -> usize {
        self.files
    }
}

/// A PBO of the source: its path and its path relative to the source with `/` separators.
struct SourcePbo {
    path: PathBuf,
    relative: String,
}

/// Removes the staging folder unless it was handed over.
struct Staging {
    path: PathBuf,
    armed: bool,
}

impl Drop for Staging {
    fn drop(&mut self) {
        if self.armed {
            // best effort on the way out: the error that got us here matters more
            let _ = fs::remove_dir_all(&self.path);
        }
    }
}

fn is_dir(path: &Path) -> bool {
    fs::metadata(path).is_ok_and(|m| m.is_dir())
}

/// The PBOs of `source`, in sorted path order: the file itself, or the `*.pbo` files directly in the
/// `dta` and `addons` folders of a folder (any case).
fn find_pbos(source: &Path) -> Result<Vec<SourcePbo>, Error> {
    let shown = printable(&source.display().to_string());
    let meta = fs::metadata(source).prepend_error(format!("Failed to read source \"{shown}\":"))?;
    let mut found = Vec::new();
    if meta.is_file() {
        let name = source
            .file_name()
            .map_or_else(String::new, |n| n.to_string_lossy().into_owned());
        found.push(SourcePbo {
            path: source.to_path_buf(),
            relative: name,
        });
        return Ok(found);
    }
    let read = |dir: &Path| {
        fs::read_dir(dir).prepend_error(format!(
            "Failed to read folder \"{}\":",
            printable(&dir.display().to_string())
        ))
    };
    for folder in read(source)? {
        let folder = folder.prepend_error(format!("Failed to read folder \"{shown}\":"))?;
        let folder_name = folder.file_name().to_string_lossy().into_owned();
        let lower = folder_name.to_lowercase();
        if (lower != "dta" && lower != "addons") || !is_dir(&folder.path()) {
            continue;
        }
        for file in read(&folder.path())? {
            let file = file.prepend_error("Failed to read folder entry:")?;
            let path = file.path();
            let is_pbo = path
                .extension()
                .is_some_and(|e| e.eq_ignore_ascii_case("pbo"));
            if is_pbo && fs::metadata(&path).is_ok_and(|m| m.is_file()) {
                found.push(SourcePbo {
                    relative: format!("{folder_name}/{}", file.file_name().to_string_lossy()),
                    path,
                });
            }
        }
    }
    found.sort_by(|a, b| a.relative.cmp(&b.relative));
    if found.is_empty() {
        return Err(error!(
            "Found no PBOs in the dta or addons folder of \"{shown}\"."
        ));
    }
    Ok(found)
}

/// Whether `folder` is empty or holds the `pbo-map.tsv` of an earlier run, so that replacing it cannot
/// destroy anything but an extract result.
fn looks_like_extract_result(folder: &Path) -> bool {
    let is_empty = fs::read_dir(folder).is_ok_and(|mut entries| entries.next().is_none());
    is_empty || fs::symlink_metadata(folder.join(MAP_FILE)).is_ok_and(|m| m.is_file())
}

/// `path` with symlinks resolved as far as it exists: the nearest existing ancestor is canonicalized and the
/// missing rest appended. `None` if the missing rest has a `..` or a root, which cannot be resolved by name.
fn resolve_for_comparison(path: &Path) -> Option<PathBuf> {
    let mut existing = path.to_path_buf();
    let mut rest = Vec::new();
    let mut resolved = loop {
        if existing.as_os_str().is_empty() {
            existing = PathBuf::from(".");
        }
        if let Ok(done) = existing.canonicalize() {
            break done;
        }
        rest.push(existing.file_name()?.to_os_string());
        if !existing.pop() {
            return None;
        }
    };
    resolved.extend(rest.iter().rev());
    Some(resolved)
}

/// Checks the target before anything is written: an existing one needs `force`, must be a real folder
/// that is empty or an earlier result, and must neither contain nor lie inside the source.
fn check_target(
    sources: &[SourcePbo],
    source: &Path,
    target: &Path,
    force: bool,
) -> Result<(), Error> {
    let shown = printable(&target.display().to_string());
    match fs::symlink_metadata(target) {
        Ok(meta) => {
            if !meta.is_dir() {
                return Err(error!("Target \"{shown}\" exists and is not a folder."));
            }
            if !force {
                return Err(error!(
                    "Target folder \"{shown}\" already exists. Use --force to replace it."
                ));
            }
            // paths that cannot be compared count as overlapping: better refuse than delete the source
            let outer = target.canonicalize();
            let overlaps = |inner: &Path| match (&outer, inner.canonicalize()) {
                (Ok(outer), Ok(inner)) => inner.starts_with(outer),
                _ => true,
            };
            // `find_pbos` has just listed the source, so this fails only if it vanishes in between
            let Ok(resolved_source) = source.canonicalize() else {
                return Err(error!(
                    "Cannot resolve the source folder \"{}\".",
                    printable(&source.display().to_string())
                ));
            };
            let inside = match &outer {
                Ok(outer) => outer.starts_with(resolved_source),
                Err(_) => true,
            };
            if inside {
                return Err(error!(
                    "Target folder \"{shown}\" is inside the source; refusing to replace it."
                ));
            }
            if overlaps(source) || sources.iter().any(|s| overlaps(&s.path)) {
                return Err(error!(
                    "Target folder \"{shown}\" contains the source; refusing to replace it."
                ));
            }
            if !looks_like_extract_result(target) {
                return Err(error!(
                    "Target folder \"{shown}\" is not empty and not the result of an earlier extract (it has no {MAP_FILE}); refusing to replace it."
                ));
            }
            Ok(())
        }
        Err(e) if e.kind() == ErrorKind::NotFound => {
            // a new target inside the source would write into it, and the next run with --force would
            // refuse it: refuse before anything is created
            let Some(resolved) = resolve_for_comparison(target) else {
                return Err(error!(
                    "Invalid target folder \"{shown}\": cannot resolve \"..\" after a folder that does not exist."
                ));
            };
            // `find_pbos` has just listed the source, so this fails only if it vanishes in between
            let Ok(source) = source.canonicalize() else {
                return Err(error!(
                    "Cannot resolve the source folder \"{}\".",
                    printable(&source.display().to_string())
                ));
            };
            if resolved.starts_with(source) {
                return Err(error!(
                    "Target folder \"{shown}\" is inside the source; refusing to replace it."
                ));
            }
            Ok(())
        }
        Err(e) => Err(e).prepend_error(format!("Failed to read target \"{shown}\":")),
    }
}

/// The final folder name of `target`; a target that ends in `..` or is a root has none and is refused.
fn target_name(target: &Path) -> Result<String, Error> {
    target
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .ok_or_else(|| {
            error!(
                "Invalid target folder \"{}\".",
                printable(&target.display().to_string())
            )
        })
}

/// Creates an empty staging folder next to `target` (same parent, so the final rename stays on one
/// file system).
fn create_staging(target: &Path) -> Result<Staging, Error> {
    let name = target_name(target)?;
    let parent = parent_of(target);
    fs::create_dir_all(&parent).prepend_error("Failed to create the folder of the target:")?;
    for attempt in 0..1000_u32 {
        let path = parent.join(format!(".{name}.extract-{}-{attempt}", std::process::id()));
        match fs::create_dir(&path) {
            Ok(()) => return Ok(Staging { path, armed: true }),
            Err(e) if e.kind() == ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e).prepend_error("Failed to create the staging folder:"),
        }
    }
    Err(error!("Failed to find a free name for the staging folder."))
}

fn parent_of(path: &Path) -> PathBuf {
    match path.parent() {
        Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
        _ => PathBuf::from("."),
    }
}

/// `data` as text if it is a rapified config.
fn derapify(data: &[u8]) -> Result<Vec<u8>, Error> {
    let config = Config::read_rapified(&mut Cursor::new(data))?;
    let mut text = Vec::new();
    config.write_with(&mut text, &WriteOptions::new())?;
    Ok(text)
}

/// `bytes` with `\`, TAB, CR and LF escaped as `\\`, `\t`, `\r` and `\n`, so that every `\` of the output starts an
/// escape.
fn escape(bytes: &[u8], out: &mut Vec<u8>) {
    for &b in bytes {
        match b {
            b'\\' => out.extend_from_slice(b"\\\\"),
            b'\t' => out.extend_from_slice(b"\\t"),
            b'\r' => out.extend_from_slice(b"\\r"),
            b'\n' => out.extend_from_slice(b"\\n"),
            _ => out.push(b),
        }
    }
}

/// The largest entry that is read into memory (compressed ones and derapify candidates); everything
/// else is copied from the PBO to the file in pieces.
const MAX_IN_MEMORY: u64 = 1 << 29;

/// What an entry's file will hold.
enum Content {
    /// Copy this many bytes from the PBO, starting at the offset.
    Stream {
        offset: u64,
        size: u64,
    },
    Bytes(Vec<u8>),
}

/// The state that spans all PBOs of one run.
struct Run<'a> {
    staging: &'a Path,
    options: &'a ExtractOptions,
    filter: EntryFilter,
    /// The PBO paths, by index.
    names: Vec<String>,
    /// Lowercase relative path of every file written -> (path as written, index of its PBO).
    owners: BTreeMap<String, (PathBuf, usize)>,
    /// Prefix bytes and PBO path of every PBO.
    map: Vec<(Vec<u8>, String)>,
    files: usize,
}

impl Run<'_> {
    /// The file already written that a new file at `relative` (lowercase `key`) cannot coexist with: one at
    /// a parent folder's path, or one below `relative` as a folder. Its path, the index of its PBO and
    /// whether it is the file at a parent folder (the new entry needs a folder there).
    fn clash(&self, relative: &Path, key: &str) -> Option<(PathBuf, usize, bool)> {
        for parent in relative.ancestors().skip(1) {
            let parent = parent.to_string_lossy().to_lowercase();
            if let Some((path, owner)) = self.owners.get(&parent) {
                return Some((path.clone(), *owner, true));
            }
        }
        let below = format!("{key}{}", std::path::MAIN_SEPARATOR);
        let (found, (path, owner)) = self.owners.range(below.clone()..).next()?;
        found
            .starts_with(&below)
            .then(|| (path.clone(), *owner, false))
    }

    /// Warns and returns `true` if the file at `relative` clashes with one written earlier, see [`Run::clash`].
    fn skip_clash(
        &self,
        index: usize,
        relative: &Path,
        key: &str,
        warnings: &mut dyn WarningSink,
    ) -> bool {
        let Some((other, owner, other_is_file)) = self.clash(relative, key) else {
            return false;
        };
        let pbo_name = |i: usize| self.names.get(i).map_or("?", String::as_str);
        // shown with `/` on every platform; the keys stay native paths
        let shown = |p: &Path| {
            let parts: Vec<_> = p
                .components()
                .map(|c| c.as_os_str().to_string_lossy())
                .collect();
            printable(&parts.join("/"))
        };
        let (pbo, other_pbo) = (printable(pbo_name(index)), printable(pbo_name(owner)));
        // the existing file is at a parent folder of the new entry, or the new entry is a file where it has a folder
        let message = if other_is_file {
            format!(
                "Skipping \"{}\" from {pbo}: it needs \"{}\" as a folder, but {other_pbo} has a file there.",
                shown(relative),
                shown(&other),
            )
        } else {
            format!(
                "Skipping \"{}\" from {pbo}: it is a file, but {other_pbo} has a folder there.",
                shown(relative),
            )
        };
        warnings.warn(Warning::new(Some("extract-path-clash"), message));
        true
    }

    /// Extracts one PBO. A PBO that cannot be read or an entry that cannot be decompressed or written is
    /// an error; unsafe names are skipped.
    fn pbo(
        &mut self,
        index: usize,
        source: &SourcePbo,
        warnings: &mut dyn WarningSink,
    ) -> Result<(), Error> {
        let shown = printable(&source.relative);
        let mut file = BufReader::new(
            File::open(&source.path).prepend_error(format!("Failed to open PBO \"{shown}\":"))?,
        );
        let pbo_index =
            read_index(&mut file).prepend_error(format!("Failed to read PBO \"{shown}\":"))?;

        let stem = source
            .path
            .file_stem()
            .map_or_else(String::new, |s| s.to_string_lossy().into_owned());
        let prefix = pbo_index.prefix.as_deref();
        let folder = match prefix_relative(prefix) {
            Ok(Some(relative)) => Some(relative),
            Ok(None) => safe_relative_path(&stem),
            Err(_) => None,
        };
        let map_prefix = match (prefix_relative(prefix), pbo_index.prefix_bytes) {
            (Ok(None), _) => stem.as_bytes().to_vec(),
            (_, Some(raw)) => raw,
            (_, None) => prefix.unwrap_or_default().as_bytes().to_vec(),
        };
        // `/` separators like the tree, so that the file needs no `\` of its own
        let map_prefix: Vec<u8> = map_prefix
            .iter()
            .map(|&b| if b == b'\\' { b'/' } else { b })
            .collect();
        self.map.push((map_prefix, source.relative.clone()));
        let folder = folder.filter(|f| {
            !f.components().next().is_some_and(|c| {
                c.as_os_str()
                    .to_string_lossy()
                    .eq_ignore_ascii_case(MAP_FILE)
            })
        });
        let Some(folder) = folder else {
            warnings.warn(Warning::new(
                Some("unsafe-path"),
                format!("Skipping PBO \"{shown}\": its prefix is not a safe folder name."),
            ));
            return Ok(());
        };

        for entry in &pbo_index.entries {
            if !self.filter.matches(&entry.name) {
                continue;
            }
            let end = entry.offset.checked_add(entry.size);
            if end.is_none_or(|end| end > pbo_index.len) {
                return Err(error!(
                    "PBO \"{shown}\": entry \"{}\" is truncated (its data ends past the end of the file).",
                    printable(&entry.name)
                ));
            }
            self.entry(index, &folder, entry, &mut file, warnings)
                .prepend_error(format!("PBO \"{shown}\":"))?;
        }
        Ok(())
    }

    /// Writes one entry below `folder`, or warns why it is skipped.
    fn entry<F: Read + Seek>(
        &mut self,
        index: usize,
        folder: &Path,
        entry: &IndexEntry,
        file: &mut F,
        warnings: &mut dyn WarningSink,
    ) -> Result<(), Error> {
        let name = entry.name.as_str();
        if entry.non_utf8 {
            warnings.warn(Warning::new(
                Some("non-utf8-filename"),
                format!("Entry name {name:?} is not valid UTF-8; extracting it as windows-1252."),
            ));
        }
        let Some((mut relative, stripped)) = unpack_relative(name) else {
            warnings.warn(Warning::new(
                Some("unsafe-path"),
                format!("Skipping \"{}\": unsafe path.", printable(name)),
            ));
            return Ok(());
        };
        if stripped {
            warn_leading_separator(name, &relative, warnings);
        }
        let is_bin = relative
            .extension()
            .is_some_and(|e| e.eq_ignore_ascii_case("bin"));
        let fail = |what: &str| format!("{what} \"{}\":", printable(name));
        let mut content = Content::Stream {
            offset: entry.offset,
            size: entry.size,
        };
        if entry.compressed {
            if entry.size > MAX_IN_MEMORY || u64::from(entry.original_size) > MAX_IN_MEMORY {
                return Err(error!(
                    "Compressed entry \"{}\" is too large.",
                    printable(name)
                ));
            }
            let stored =
                read_at(file, entry.offset, entry.size).prepend_error(fail("Failed to read"))?;
            let data = decompress_entry(&stored, entry.original_size)
                .prepend_error(fail("Failed to decompress"))?;
            content = Content::Bytes(data);
        }
        if self.options.derapify && is_bin {
            let (derapified, kept) = derapify_entry(entry, content, file, warnings)?;
            if derapified {
                relative = relative.with_extension("cpp");
            }
            content = kept;
        }
        let relative = folder.join(relative);
        let key = relative.to_string_lossy().to_lowercase();
        if self.skip_clash(index, &relative, &key, warnings) {
            return Ok(()); // the clash is a warning, not an error
        }
        if let Some((old, owner)) = self.owners.get(&key).cloned() {
            if owner == index {
                warnings.warn(Warning::new(
                    Some("duplicate-entry"),
                    format!(
                        "Skipping \"{}\": an entry with the same path was already extracted.",
                        printable(name)
                    ),
                ));
                return Ok(());
            }
            let pbo_name = |i: usize| self.names.get(i).map_or("?", String::as_str);
            warnings.warn(Warning::new(
                Some("duplicate-path"),
                format!(
                    "\"{}\" is in {} and in {}; keeping the one of {}.",
                    printable(&relative.to_string_lossy()),
                    printable(pbo_name(owner)),
                    printable(pbo_name(index)),
                    printable(pbo_name(index)),
                ),
            ));
            // the file is replaced below; one that is already gone does not matter
            let _ = fs::remove_file(self.staging.join(old));
        }
        let path = self.staging.join(&relative);
        // the staging folder is new and holds nothing but what this run wrote, so no path in it is a symlink
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).prepend_error(fail("Failed to create the folder of"))?;
        }
        match content {
            Content::Bytes(data) => fs::write(&path, data),
            Content::Stream { offset, size } => file
                .seek(SeekFrom::Start(offset))
                .and_then(|_| File::create(&path))
                .and_then(|mut out| {
                    let copied = io::copy(&mut file.by_ref().take(size), &mut out)?;
                    if copied == size {
                        Ok(())
                    } else {
                        Err(Error::new(
                            ErrorKind::UnexpectedEof,
                            "the entry is truncated",
                        ))
                    }
                }),
        }
        .prepend_error(fail("Failed to write"))?;
        if self.owners.insert(key, (relative, index)).is_none() {
            self.files += 1;
        }
        Ok(())
    }
}

/// The content of a `.bin` entry as text when it is a rapified config (`true`), else as it was. A config
/// that cannot be derapified is kept with a `derapify-failed` warning.
fn derapify_entry<F: Read + Seek>(
    entry: &IndexEntry,
    content: Content,
    file: &mut F,
    warnings: &mut dyn WarningSink,
) -> Result<(bool, Content), Error> {
    let name = entry.name.as_str();
    let fail = |what: &str| format!("{what} \"{}\":", printable(name));
    let head = match &content {
        Content::Bytes(data) => data.get(..4).map(<[u8]>::to_vec),
        Content::Stream { offset, size } if *size >= 4 => {
            Some(read_at(file, *offset, 4).prepend_error(fail("Failed to read"))?)
        }
        Content::Stream { .. } => None,
    };
    if !head.is_some_and(|h| is_rapified(&h)) {
        return Ok((false, content));
    }
    let data = match content {
        Content::Bytes(data) => data,
        Content::Stream { offset, size } if size <= MAX_IN_MEMORY => {
            read_at(file, offset, size).prepend_error(fail("Failed to read"))?
        }
        Content::Stream { offset, size } => {
            warnings.warn(Warning::new(
                Some("derapify-failed"),
                format!(
                    "Keeping \"{}\" as it is: the entry is too large to derapify.",
                    printable(name)
                ),
            ));
            return Ok((false, Content::Stream { offset, size }));
        }
    };
    match derapify(&data) {
        Ok(text) => Ok((true, Content::Bytes(text))),
        Err(e) => {
            warnings.warn(Warning::new(
                Some("derapify-failed"),
                format!("Keeping \"{}\" as it is: {e}", printable(name)),
            ));
            Ok((false, Content::Bytes(data)))
        }
    }
}

/// `size` bytes of `file` at `offset`; the caller has checked `size` against `MAX_IN_MEMORY`.
fn read_at<F: Read + Seek>(file: &mut F, offset: u64, size: u64) -> Result<Vec<u8>, Error> {
    file.seek(SeekFrom::Start(offset))?;
    let mut data = Vec::new();
    file.by_ref().take(size).read_to_end(&mut data)?;
    if u64::try_from(data.len()).ok() != Some(size) {
        return Err(Error::new(
            ErrorKind::UnexpectedEof,
            "the entry is truncated",
        ));
    }
    Ok(data)
}

/// Replaces `target` with the finished `staging` folder. The old tree is renamed away first, so a failure
/// puts it back.
fn swap(staging: &mut Staging, target: &Path, warnings: &mut dyn WarningSink) -> Result<(), Error> {
    let shown = printable(&target.display().to_string());
    let old = match fs::symlink_metadata(target) {
        Ok(_) => {
            let mut old = staging.path.clone().into_os_string();
            old.push(".old");
            let old = PathBuf::from(old);
            fs::rename(target, &old)
                .prepend_error(format!("Failed to move the old target \"{shown}\" away:"))?;
            Some(old)
        }
        Err(_) => None,
    };
    if let Err(e) = fs::rename(&staging.path, target) {
        if let Some(old) = &old {
            // put the old tree back; if that fails too the error below names where it is
            if let Err(back) = fs::rename(old, target) {
                return Err(error!(
                    "Failed to move the new tree to \"{shown}\": {e}; the old tree is in \"{}\" ({back}).",
                    printable(&old.display().to_string())
                ));
            }
        }
        return Err(e).prepend_error(format!("Failed to move the new tree to \"{shown}\":"));
    }
    staging.armed = false;
    if let Some(old) = old
        && let Err(e) = fs::remove_dir_all(&old)
    {
        warnings.warn(Warning::new(
            Some("old-tree-left"),
            format!(
                "Could not remove the old tree \"{}\": {e}",
                printable(&old.display().to_string())
            ),
        ));
    }
    Ok(())
}

/// Extracts `source` into `target`.
///
/// `source` is a DayZ client or server folder, a mod folder or a single PBO. For a folder, every `*.pbo`
/// directly in its `dta` and `addons` subfolders (any case) is read, in sorted path order. The entries of
/// each PBO go to `<target>/<prefix>/<entry>`; an empty prefix means the file stem of the PBO. Names are
/// validated like [`crate::pbo::unpack`] does and unsafe ones are skipped with a warning. When two PBOs
/// write the same path (ignoring case), the later one wins and a `duplicate-path` warning names both. When
/// an entry would be a file where an earlier one has a folder, or the reverse, the first stays and the
/// later one is skipped with an `extract-path-clash` warning.
/// With `options.derapify`, a rapified `*.bin` becomes a `.cpp` of the same name, or stays a `.bin` with a
/// `derapify-failed` warning. `options.only` and `options.exclude` select entries like they do for
/// [`crate::pbo::unpack`].
///
/// The tree is written to a staging folder next to `target` and then replaces it with one rename, so a
/// re-run drops files that no longer exist and a failure leaves the old tree alone. The file `pbo-map.tsv`
/// in the target has one line per PBO, `prefix<TAB>path of the PBO relative to source` with `/`
/// separators, sorted by prefix. The prefix is written with `/` instead of `\` (like the tree below the target); then
/// `\`, TAB, CR and LF in either column are written as `\\`, `\t`, `\r` and `\n`, so every `\` in the file starts
/// an escape. The bytes of the prefix as stored are in the `--json` output of `inspect`.
///
/// # Errors
///
/// Returns an error if the source has no PBO or cannot be read, a PBO is malformed or an entry is truncated
/// (its data ends past the end of the file), an entry cannot be read or decompressed, the target exists and
/// `options.force` is not set, the target is not a folder, is inside the source or contains it, the target
/// folder is neither empty nor the result of an earlier extract (no `pbo-map.tsv`), or the tree cannot be
/// written. A failure leaves an existing target alone.
pub fn extract(
    source: &Path,
    target: &Path,
    options: &ExtractOptions,
    warnings: &mut dyn WarningSink,
) -> Result<ExtractSummary, Error> {
    let sources = find_pbos(source)?;
    // before anything looks at the target: `a/missing/..` must fail the same way where it resolves to `a`
    target_name(target)?;
    check_target(&sources, source, target, options.force)?;
    let mut staging = create_staging(target)?;
    let mut run = Run {
        staging: &staging.path.clone(),
        options,
        names: sources.iter().map(|s| s.relative.clone()).collect(),
        filter: EntryFilter::new(options.only.clone(), options.exclude.clone()),
        owners: BTreeMap::new(),
        map: Vec::new(),
        files: 0,
    };
    for (index, source) in sources.iter().enumerate() {
        run.pbo(index, source, warnings)?;
    }
    run.map.sort();
    let mut text = Vec::new();
    for (prefix, path) in &run.map {
        escape(prefix, &mut text);
        text.push(b'\t');
        escape(path.as_bytes(), &mut text);
        text.push(b'\n');
    }
    fs::write(staging.path.join(MAP_FILE), &text).prepend_error("Failed to write the PBO map:")?;
    let summary = ExtractSummary {
        pbos: sources.len(),
        files: run.files,
    };
    swap(&mut staging, target, warnings)?;
    Ok(summary)
}