backhand-cli 0.25.5

Binaries for the reading, creating, and modification of SquashFS file systems
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
use std::collections::HashSet;
use std::fs::{self, File, Permissions};
use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::os::unix::fs::lchown;
use std::os::unix::prelude::PermissionsExt;
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
use std::sync::Mutex;

#[cfg(feature = "v3")]
use backhand::V3;
use backhand::kind::Kind;
use backhand::traits::filesystem::{BackhandInnerNode, BackhandNode, BackhandNodeHeader};
use backhand::{
    DEFAULT_BLOCK_SIZE, FilesystemReaderTrait, SquashfsVersion, V4, create_squashfs_from_kind,
};
use backhand_cli::after_help;
use clap::builder::PossibleValuesParser;
use clap::{CommandFactory, Parser};
use clap_complete::{Shell, generate};
use console::Term;
use indicatif::{HumanDuration, ProgressBar, ProgressStyle};
use nix::fcntl::AT_FDCWD;
use nix::libc::geteuid;
use nix::sys::stat::{Mode, SFlag, UtimensatFlags, dev_t, mknod, mode_t, umask, utimensat, utimes};
use nix::sys::time::{TimeSpec, TimeVal};
use nix::unistd::mkfifo;
use rayon::prelude::*;
use std::time::{Duration, Instant};

// -musl malloc is slow, use jemalloc
#[cfg(all(target_env = "musl", target_pointer_width = "64"))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

const AVAILABLE_KINDS: &[&str] = &[
    "le_v4_0",
    "be_v4_0",
    #[cfg(feature = "v3")]
    "le_v3_0",
    #[cfg(feature = "v3")]
    "be_v3_0",
    #[cfg(feature = "v3_lzma")]
    "le_v3_0_lzma",
    #[cfg(feature = "v3_lzma")]
    "be_v3_0_lzma",
    #[cfg(feature = "v3_lzma")]
    "netgear_be_v3_0_lzma_standard",
    #[cfg(feature = "v3_lzma")]
    "netgear_be_v3_0_lzma",
    #[cfg(feature = "v3_lzma")]
    "le_v3_0_lzma_swap_standard",
    #[cfg(feature = "v3_lzma")]
    "be_v3_0_lzma_swap_standard",
    #[cfg(feature = "v3_lzma")]
    "le_v3_1_lzma_swap",
    #[cfg(feature = "v3_lzma")]
    "be_v3_1_lzma_swap",
    #[cfg(feature = "v4_lzma")]
    "le_v4_0_lzma",
    #[cfg(feature = "v4_lzma")]
    "be_v4_0_lzma",
    "avm_be_v4_0",
];

pub fn required_root(a: &str) -> Result<PathBuf, String> {
    let p = PathBuf::from(a);

    if p.has_root() { Ok(p) } else { Err("argument requires root \"/\"".to_string()) }
}

fn find_offset(file: &mut BufReader<File>, kind: &Kind) -> Option<u64> {
    let mut magic = [0_u8; 4];
    while file.read_exact(&mut magic).is_ok() {
        if magic == kind.magic() {
            let found = file.stream_position().ok()? - magic.len() as u64;
            file.rewind().ok()?;
            return Some(found);
        }
    }
    file.rewind().ok()?;
    None
}

pub fn extracted(pb: &ProgressBar, s: &str) {
    let blue_bold: console::Style = console::Style::new().blue().bold();
    let line = format!("{:>16} {}", blue_bold.apply_to("Extracted"), s,);
    pb.println(line);
}

pub fn created(pb: &ProgressBar, s: &str) {
    let blue_bold: console::Style = console::Style::new().blue().bold();
    let line = format!("{:>16} {}", blue_bold.apply_to("Created"), s,);
    pb.println(line);
}

pub fn exists(pb: &ProgressBar, s: &str) {
    let red_bold: console::Style = console::Style::new().red().bold();
    let line = format!("{:>16} {}", red_bold.apply_to("Exists"), s,);
    pb.println(line);
}

pub fn failed(pb: &ProgressBar, s: &str) {
    let red_bold: console::Style = console::Style::new().red().bold();
    let line = format!("{:>16} {}", red_bold.apply_to("Failed"), s,);
    pb.println(line);
}

pub fn error(pb: &ProgressBar, s: &str) {
    let red_bold: console::Style = console::Style::new().red().bold();
    let line = format!("{:>14} {}", red_bold.apply_to("Error"), s,);
    pb.finish_with_message(line);
}

/// tool to uncompress, extract and list squashfs filesystems
#[derive(Parser)]
#[command(author,
          version,
          name = "unsquashfs-backhand",
          after_help = after_help(true),
          max_term_width = 98,
          styles = clap_cargo::style::CLAP_STYLING,
)]
struct Args {
    /// Squashfs file
    ///
    /// Required for all usage, except --completions
    #[arg(required_unless_present = "completions")]
    filesystem: Option<PathBuf>,

    /// Skip BYTES at the start of FILESYSTEM
    #[arg(short, long, default_value_t = 0, name = "BYTES")]
    offset: u64,

    /// Find first instance of squashfs --kind magic
    ///
    /// Will overwrite given --offset
    #[arg(short, long)]
    auto_offset: bool,

    /// List filesystem, do not write to DEST (ignores --quiet)
    #[arg(short, long)]
    list: bool,

    /// Extract to [PATHNAME]
    #[arg(short, long, default_value = "squashfs-root", name = "PATHNAME")]
    dest: PathBuf,

    /// Print files as they are extracted
    #[arg(short, long)]
    info: bool,

    /// Limit filesystem extraction
    ///
    /// For example, "/www/webpages/data" will return all files under that dir, such as
    /// "/www/webpages/data/region.json" and "/www/webpages/data/timezone.json". When given an
    /// exact file, only that file will be extracted.
    ///
    /// Like normal operation, these will be extracted as {arg.dest}{arg.path_filter}{files} with
    /// correct file permissions.
    #[arg(long, default_value = "/", value_parser = required_root)]
    path_filter: PathBuf,

    /// If file already exists then overwrite
    #[arg(short, long)]
    force: bool,

    /// Display filesystem superblock information (ignores --quiet)
    #[arg(short, long)]
    stat: bool,

    /// Kind(type of image) to parse. If not specified, will auto-detect by trying all kinds.
    #[arg(short, long, value_parser = PossibleValuesParser::new(AVAILABLE_KINDS))]
    kind: Option<String>,

    /// Emit shell completion scripts
    #[arg(long)]
    completions: Option<Shell>,

    /// Silence all progress bar and RUST_LOG output
    #[arg(long)]
    quiet: bool,
}

fn try_all_kinds(
    file: &mut BufReader<File>,
    offset: u64,
    pb: &ProgressBar,
    quiet: bool,
) -> Result<(Kind, &'static str), String> {
    let mut errors = Vec::new();

    for &kind_name in AVAILABLE_KINDS {
        if let Ok(kind) = Kind::from_target(kind_name) {
            file.seek(SeekFrom::Start(0)).map_err(|e| format!("Failed to seek: {}", e))?;

            let success = {
                let result = create_squashfs_from_kind(&mut *file, offset, kind.clone());
                match result {
                    Ok(_) => true,
                    Err(e) => {
                        errors.push((kind_name, e));
                        false
                    }
                }
            };

            if success {
                file.seek(SeekFrom::Start(0)).map_err(|e| format!("Failed to seek back: {}", e))?;
                return Ok((kind, kind_name));
            }
        }
    }

    // Only emit errors if we failed to detect any kind
    if !quiet {
        pb.finish_and_clear();
        let red_bold: console::Style = console::Style::new().red().bold();
        for (kind_name, e) in errors {
            eprintln!("{:>16} {}: {}", red_bold.apply_to("Failed"), kind_name, e);
        }
    }

    Err("Could not detect kind".to_string())
}

fn handle_with_kind<'a>(
    args: &mut Args,
    file: &'a mut BufReader<File>,
    kind_str: &str,
    pb: &ProgressBar,
    blue_bold: &console::Style,
) -> Result<(Box<dyn FilesystemReaderTrait + 'a>, Kind), ExitCode> {
    let kind = match Kind::from_target(kind_str) {
        Ok(k) => k,
        Err(e) => {
            error(pb, &format!("Invalid kind: {e}"));
            return Err(ExitCode::FAILURE);
        }
    };

    if args.auto_offset {
        if !args.quiet {
            pb.enable_steady_tick(Duration::from_millis(120));
            let line = format!("{:>14}", blue_bold.apply_to("Searching for magic"));
            pb.set_message(line);
        }
        if let Some(found_offset) = find_offset(file, &kind) {
            if !args.quiet {
                let line =
                    format!("{:>14} 0x{:08x}", blue_bold.apply_to("Found magic"), found_offset,);
                pb.finish_with_message(line);
            }
            args.offset = found_offset;
        } else {
            if !args.quiet {
                error(pb, "Magic not found");
            }
            return Err(ExitCode::FAILURE);
        }
    }

    match create_squashfs_from_kind(file, args.offset, kind.clone()) {
        Ok(filesystem) => Ok((filesystem, kind)),
        Err(e) => {
            error(pb, &format!("Could not read image: {e:?}"));
            Err(ExitCode::FAILURE)
        }
    }
}

fn handle_auto_detect_kind<'a>(
    args: &Args,
    file: &'a mut BufReader<File>,
    pb: &ProgressBar,
    blue_bold: &console::Style,
) -> Result<(Box<dyn FilesystemReaderTrait + 'a>, Kind), ExitCode> {
    if !args.quiet {
        pb.enable_steady_tick(Duration::from_millis(120));
        let line = format!("{:>14}", blue_bold.apply_to("Auto-detecting kind"));
        pb.set_message(line);
    }

    if args.auto_offset {
        if !args.quiet {
            error(pb, "--auto-offset requires --kind to be specified");
        }
        return Err(ExitCode::FAILURE);
    }

    match try_all_kinds(file, args.offset, pb, args.quiet) {
        Ok((detected_kind, kind_name)) => {
            if !args.quiet {
                let line = format!("{:>16} {}", blue_bold.apply_to("Detected kind"), kind_name);
                pb.finish_and_clear();
                pb.println(line);
            }

            match create_squashfs_from_kind(file, args.offset, detected_kind.clone()) {
                Ok(filesystem) => Ok((filesystem, detected_kind)),
                Err(e) => {
                    error(pb, &format!("Could not read image: {e:?}"));
                    Err(ExitCode::FAILURE)
                }
            }
        }
        Err(e) => {
            if !args.quiet {
                error(pb, &e);
            }
            Err(ExitCode::FAILURE)
        }
    }
}

fn main() -> ExitCode {
    let mut args = Args::parse();
    if !args.quiet {
        tracing_subscriber::fmt::init();
    }

    if let Some(completions) = args.completions {
        let mut cmd = Args::command();
        let name = cmd.get_name().to_string();
        generate(completions, &mut cmd, name, &mut io::stdout());
        return ExitCode::SUCCESS;
    }

    let blue_bold: console::Style = console::Style::new().blue().bold();
    let pb = ProgressBar::new_spinner();

    let filesystem_path = args.filesystem.as_ref().unwrap();

    // Check if path is a regular file
    match fs::metadata(filesystem_path) {
        Ok(metadata) if !metadata.is_file() => {
            error(&pb, &format!("{} is not a regular file", filesystem_path.display()));
            return ExitCode::FAILURE;
        }
        Err(e) => {
            error(&pb, &format!("Failed to access {}: {}", filesystem_path.display(), e));
            return ExitCode::FAILURE;
        }
        _ => {}
    }

    let mut file = match File::open(filesystem_path) {
        Ok(f) => BufReader::with_capacity(DEFAULT_BLOCK_SIZE as usize, f),
        Err(e) => {
            error(&pb, &format!("Failed to open file: {}", e));
            return ExitCode::FAILURE;
        }
    };

    if args.stat {
        if let Some(kind_str) = &args.kind {
            let kind = match Kind::from_target(kind_str) {
                Ok(k) => k,
                Err(e) => {
                    error(&pb, &format!("Invalid kind: {e}"));
                    return ExitCode::FAILURE;
                }
            };
            stat(args, file, kind, &pb);
            return ExitCode::SUCCESS;
        } else {
            if !args.quiet {
                error(&pb, "--stat requires --kind to be specified");
            }
            return ExitCode::FAILURE;
        }
    }

    let (filesystem, _) = if let Some(kind_str) = args.kind.clone() {
        match handle_with_kind(&mut args, &mut file, &kind_str, &pb, &blue_bold) {
            Ok(result) => result,
            Err(exit_code) => return exit_code,
        }
    } else {
        match handle_auto_detect_kind(&args, &mut file, &pb, &blue_bold) {
            Ok(result) => result,
            Err(exit_code) => return exit_code,
        }
    };

    process_filesystem(filesystem.as_ref(), args, pb, blue_bold)
}

fn process_filesystem(
    filesystem: &dyn FilesystemReaderTrait,
    args: Args,
    _pb: ProgressBar,
    blue_bold: console::Style,
) -> ExitCode {
    let root_process = unsafe { geteuid() == 0 };
    if root_process {
        umask(Mode::from_bits(0).unwrap());
    }

    // Start new spinner as we extract all the inode and other information from the image
    let start = Instant::now();
    let pb = ProgressBar::new_spinner();
    if !args.quiet {
        pb.enable_steady_tick(Duration::from_millis(120));
        let line = format!("{:>14}", blue_bold.apply_to("Reading image"));
        pb.set_message(line);
    }

    if !args.quiet {
        let line = format!("{:>14}", blue_bold.apply_to("Read image"));
        pb.finish_with_message(line);
    }

    // if we can find a parent, then a filter must be applied and the exact parent dirs must be
    // found above it
    let mut files: Vec<BackhandNode> = vec![];
    if args.path_filter.parent().is_some() {
        let mut current = PathBuf::new();
        current.push("/");
        for part in args.path_filter.iter() {
            current.push(part);
            if let Some(exact) = filesystem.files().into_iter().find(|a| a.fullpath == current) {
                files.push(exact);
            } else {
                if !args.quiet {
                    error(&pb, "Invalid --path-filter, path doesn't exist");
                }
                return ExitCode::FAILURE;
            }
        }
        // remove the final node, this is a file and will be caught in the following statement
        files.pop();
    }

    // gather all files and dirs
    let nodes = files
        .into_iter()
        .chain(filesystem.files().filter(|a| a.fullpath.starts_with(&args.path_filter)));

    // extract or list
    if args.list {
        list(nodes);
    } else {
        let all_nodes: Vec<BackhandNode> = nodes.collect();
        // This could be expensive, only pass this in when not quiet
        let n_nodes = if !args.quiet { Some(all_nodes.len()) } else { None };

        extract_all(&args, filesystem, root_process, all_nodes, n_nodes, start);
    }

    ExitCode::SUCCESS
}

fn list(nodes: impl Iterator<Item = BackhandNode>) {
    for node in nodes {
        let path = &node.fullpath;
        println!("{}", path.display());
    }
}

fn stat_v4(args: Args, mut file: BufReader<File>, kind: Kind) {
    if let Err(e) = file.seek(SeekFrom::Start(args.offset)) {
        eprintln!("Failed to seek to offset: {e}");
        return;
    }
    let (superblock, compression_options) =
        match V4::superblock_and_compression_options(&mut file, &kind) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("Failed to read superblock: {e}");
                return;
            }
        };

    // show info about flags
    println!("{superblock:#08x?}");

    // show info about compression options
    println!("Compression Options: {compression_options:#x?}");

    // show info about flags
    if superblock.inodes_uncompressed() {
        println!("flag: inodes uncompressed");
    }

    if superblock.data_block_stored_uncompressed() {
        println!("flag: data blocks stored uncompressed");
    }

    if superblock.fragments_stored_uncompressed() {
        println!("flag: fragments stored uncompressed");
    }

    if superblock.fragments_are_not_used() {
        println!("flag: fragments are not used");
    }

    if superblock.fragments_are_always_generated() {
        println!("flag: fragments are always generated");
    }

    if superblock.data_has_been_deduplicated() {
        println!("flag: data has been deduplicated");
    }

    if superblock.nfs_export_table_exists() {
        println!("flag: nfs export table exists");
    }

    if superblock.xattrs_are_stored_uncompressed() {
        println!("flag: xattrs are stored uncompressed");
    }

    if superblock.compressor_options_are_present() {
        println!("flag: compressor options are present");
    }
}

#[cfg(feature = "v3")]
fn stat_v3(args: Args, mut file: BufReader<File>, kind: Kind) {
    if let Err(e) = file.seek(SeekFrom::Start(args.offset)) {
        eprintln!("Failed to seek to offset: {e}");
        return;
    }
    let (superblock, _compression_options) =
        match V3::superblock_and_compression_options(&mut file, &kind) {
            Ok(result) => result,
            Err(e) => {
                eprintln!("Failed to read superblock: {e}");
                return;
            }
        };

    // show info about flags
    println!("{superblock:#08x?}");
}

fn stat(args: Args, file: BufReader<File>, kind: Kind, pb: &ProgressBar) {
    match (kind.version_major(), kind.version_minor()) {
        (4, 0) => stat_v4(args, file, kind),
        #[cfg(feature = "v3")]
        (3, 0) => stat_v3(args, file, kind),
        _ => {
            error(
                pb,
                &format!(
                    "Unsupported SquashFS version: {}.{}",
                    kind.version_major(),
                    kind.version_minor()
                ),
            );
        }
    }
}

fn set_attributes(
    pb: &ProgressBar,
    args: &Args,
    path: &Path,
    header: &BackhandNodeHeader,
    root_process: bool,
    is_file: bool,
) {
    // TODO Use (file_set_times) when not nightly: https://github.com/rust-lang/rust/issues/98245
    let timeval = TimeVal::new(header.mtime as _, 0);
    if let Err(e) = utimes(path, &timeval, &timeval) {
        if !args.quiet {
            let line = format!("{} : could not set times: {e}", path.display());
            failed(pb, &line);
        }
        return;
    }

    let mut mode = u32::from(header.permissions);

    // Only chown when root
    if root_process {
        // TODO: Use (unix_chown) when not nightly: https://github.com/rust-lang/rust/issues/88989
        match lchown(path, Some(header.uid), Some(header.gid)) {
            Ok(_) => (),
            Err(e) => {
                if !args.quiet {
                    let line =
                        format!("lchown {} {} {} : {e}", path.display(), header.uid, header.gid,);
                    failed(pb, &line);
                }
                return;
            }
        }
    } else if is_file {
        // bitwise-not if not rooted (disable write permissions for user/group). Following
        // squashfs-tools/unsquashfs behavior
        mode &= !0o022;
    }

    // set permissions
    //
    // NOTE: In squashfs-tools/unsquashfs they remove the write bits for user and group?
    // I don't know if there is a reason for that but I keep the permissions the same if possible
    if let Err(e) = fs::set_permissions(path, Permissions::from_mode(mode))
        && e.kind() == std::io::ErrorKind::PermissionDenied
    {
        // try without sticky bit
        if fs::set_permissions(path, Permissions::from_mode(mode & !1000)).is_err() && !args.quiet {
            let line = format!("{} : could not set permissions", path.display());
            failed(pb, &line);
        }
    }
}

fn extract_all(
    args: &Args,
    filesystem: &dyn FilesystemReaderTrait,
    root_process: bool,
    nodes: Vec<BackhandNode>,
    n_nodes: Option<usize>,
    start: Instant,
) {
    let pb = ProgressBar::new(n_nodes.unwrap_or(0) as u64);
    if !args.quiet {
        pb.set_style(ProgressStyle::default_spinner());
        pb.set_style(
            ProgressStyle::with_template(
                // note that bar size is fixed unlike cargo which is dynamic
                // and also the truncation in cargo uses trailers (`...`)
                if Term::stdout().size().1 > 80 {
                    "{prefix:>16.cyan.bold} [{bar:57}] {pos}/{len} {wide_msg}"
                } else {
                    "{prefix:>16.cyan.bold} [{bar:57}] {pos}/{len}"
                },
            )
            .unwrap()
            .progress_chars("=> "),
        );
        pb.set_prefix("Extracting");
        pb.inc(1);
    }

    let processing = Mutex::new(HashSet::new());

    tracing::trace!("{:?}", nodes);
    nodes.into_par_iter().for_each(|node| {
        let path = &node.fullpath;
        let fullpath = path.strip_prefix(Component::RootDir).unwrap_or(path);
        if !args.quiet {
            let mut p = processing.lock().unwrap();
            p.insert(fullpath.to_path_buf());
            pb.set_message(p.iter().map(|a| a.to_string_lossy()).collect::<Vec<_>>().join(", "));
            pb.inc(1);
        }

        let filepath = Path::new(&args.dest).join(fullpath);
        // create required dirs, we will fix permissions later
        let _ = fs::create_dir_all(filepath.parent().unwrap());

        match &node.inner {
            BackhandInnerNode::File(file) => {
                // alloc required space for file data readers
                // check if file exists
                if !args.force && filepath.exists() {
                    if !args.quiet {
                        exists(&pb, &filepath.display().to_string());
                        let mut p = processing.lock().unwrap();
                        p.remove(&fullpath.to_path_buf());
                    }
                    return;
                }

                // write to file
                let file_data = match filesystem.file_data(file) {
                    Ok(file_data) => file_data,
                    Err(e) => {
                        if !args.quiet {
                            let line = format!("{} : {e}", filepath.display());
                            failed(&pb, &line);
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                };
                let fd = match File::create(&filepath) {
                    Ok(f) => f,
                    Err(e) => {
                        if !args.quiet {
                            let line = format!("{} : {e}", filepath.display());
                            failed(&pb, &line);
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                };
                let mut writer = BufWriter::with_capacity(file_data.len(), &fd);

                match writer.write_all(&file_data) {
                    Ok(_) => {
                        if args.info && !args.quiet {
                            extracted(&pb, &filepath.display().to_string());
                        }
                        set_attributes(&pb, args, &filepath, &node.header, root_process, true);
                    }
                    Err(e) => {
                        if !args.quiet {
                            let line = format!("{} : {e}", filepath.display());
                            failed(&pb, &line);
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                }
                if let Err(e) = writer.flush()
                    && !args.quiet
                {
                    let line = format!("{} : flush failed: {e}", filepath.display());
                    failed(&pb, &line);
                }
            }
            BackhandInnerNode::Symlink { link } => {
                // create symlink
                let link_display = link.display();
                // check if file exists
                if !args.force && filepath.exists() {
                    exists(&pb, &filepath.display().to_string());
                    let mut p = processing.lock().unwrap();
                    p.remove(&fullpath.to_path_buf());
                    return;
                }

                match std::os::unix::fs::symlink(link, &filepath) {
                    Ok(_) => {
                        if args.info && !args.quiet {
                            let line = format!("{}->{link_display}", filepath.display());
                            created(&pb, &line);
                        }
                    }
                    Err(e) => {
                        if !args.quiet {
                            let line = format!("{}->{link_display} : {e}", filepath.display());
                            failed(&pb, &line);
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                }

                // set attributes, but special to not follow the symlink

                if root_process {
                    // TODO: Use (unix_chown) when not nightly: https://github.com/rust-lang/rust/issues/88989
                    match lchown(&filepath, Some(node.header.uid), Some(node.header.gid)) {
                        Ok(_) => (),
                        Err(e) => {
                            if !args.quiet {
                                let line = format!(
                                    "lchown {} {} {} : {e}",
                                    filepath.display(),
                                    node.header.uid,
                                    node.header.gid,
                                );
                                failed(&pb, &line);
                            }
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                            return;
                        }
                    }
                }

                // TODO Use (file_set_times) when not nightly: https://github.com/rust-lang/rust/issues/98245
                // Make sure this doesn't follow symlinks when changed to std library!
                let timespec = TimeSpec::new(node.header.mtime as _, 0);
                if let Err(e) = utimensat(
                    AT_FDCWD,
                    &filepath,
                    &timespec,
                    &timespec,
                    UtimensatFlags::NoFollowSymlink,
                ) && !args.quiet
                {
                    let line = format!("{} : could not set times: {e}", filepath.display());
                    failed(&pb, &line);
                }
            }
            BackhandInnerNode::Dir => {
                // These permissions are corrected later (user default permissions for now)
                //
                // don't display error if this was already created, we might have already
                // created it in another thread to put down a file
                if std::fs::create_dir(&filepath).is_ok() && args.info && !args.quiet {
                    created(&pb, &filepath.display().to_string())
                }
            }
            BackhandInnerNode::CharacterDevice { device_number } => {
                if root_process {
                    #[allow(clippy::unnecessary_fallible_conversions)]
                    match mknod(
                        &filepath,
                        SFlag::S_IFCHR,
                        Mode::from_bits(mode_t::from(node.header.permissions)).unwrap(),
                        dev_t::try_from(*device_number).unwrap(),
                    ) {
                        Ok(_) => {
                            if args.info && !args.quiet {
                                created(&pb, &filepath.display().to_string());
                            }

                            set_attributes(&pb, args, &filepath, &node.header, root_process, true);
                        }
                        Err(_) => {
                            if !args.quiet {
                                let line = format!(
                                    "char device {}, are you superuser?",
                                    filepath.display()
                                );
                                failed(&pb, &line);
                                let mut p = processing.lock().unwrap();
                                p.remove(&fullpath.to_path_buf());
                            }
                            return;
                        }
                    }
                } else {
                    if !args.quiet {
                        let line =
                            format!("char device {}, are you superuser?", filepath.display());
                        failed(&pb, &line);
                    }
                    let mut p = processing.lock().unwrap();
                    p.remove(&fullpath.to_path_buf());
                    return;
                }
            }
            BackhandInnerNode::BlockDevice { device_number } => {
                #[allow(clippy::unnecessary_fallible_conversions)]
                match mknod(
                    &filepath,
                    SFlag::S_IFBLK,
                    Mode::from_bits(mode_t::from(node.header.permissions)).unwrap(),
                    dev_t::try_from(*device_number).unwrap(),
                ) {
                    Ok(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                        }

                        set_attributes(&pb, args, &filepath, &node.header, root_process, true);
                    }
                    Err(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                }
            }
            BackhandInnerNode::NamedPipe => {
                match mkfifo(
                    &filepath,
                    Mode::from_bits(mode_t::from(node.header.permissions)).unwrap(),
                ) {
                    Ok(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                        }

                        set_attributes(&pb, args, &filepath, &node.header, root_process, true);
                    }
                    Err(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                        }
                        let mut p = processing.lock().unwrap();
                        p.remove(&fullpath.to_path_buf());
                        return;
                    }
                }
            }
            BackhandInnerNode::Socket => {
                #[allow(clippy::unnecessary_fallible_conversions)]
                match mknod(
                    &filepath,
                    SFlag::S_IFSOCK,
                    Mode::from_bits(mode_t::from(node.header.permissions)).unwrap(),
                    dev_t::try_from(0_u64).unwrap(),
                ) {
                    Ok(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                        }

                        set_attributes(&pb, args, &filepath, &node.header, root_process, true);
                    }
                    Err(_) => {
                        if args.info && !args.quiet {
                            created(&pb, &filepath.display().to_string());
                            let mut p = processing.lock().unwrap();
                            p.remove(&fullpath.to_path_buf());
                        }
                        return;
                    }
                }
            }
        }
        let mut p = processing.lock().unwrap();
        p.remove(&fullpath.to_path_buf());
    });

    // fixup dir permissions
    for node in filesystem.files().filter(|a| a.fullpath.starts_with(&args.path_filter)) {
        if let BackhandInnerNode::Dir = &node.inner {
            let path = &node.fullpath;
            let path = path.strip_prefix(Component::RootDir).unwrap_or(path);
            let path = Path::new(&args.dest).join(path);
            set_attributes(&pb, args, &path, &node.header, root_process, false);
        }
    }

    pb.finish_and_clear();

    // extraction is finished
    let green_bold: console::Style = console::Style::new().green().bold();
    if !args.quiet {
        println!(
            "{:>16} extraction of {} nodes in {}",
            green_bold.apply_to("Finished"),
            n_nodes.unwrap(),
            HumanDuration(start.elapsed())
        );
    }
}