uucore 0.4.0

uutils ~ 'core' uutils code library (cross-platform)
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
// This file is part of the uutils coreutils package.
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

//! Common functions to manage permissions

// spell-checker:ignore (jargon) TOCTOU fchownat fchown

use crate::display::Quotable;
use crate::error::{UResult, USimpleError, strip_errno};
pub use crate::features::entries;
use crate::show_error;

use clap::{Arg, ArgMatches, Command};

use libc::{gid_t, uid_t};
use options::traverse;
use std::ffi::OsString;

#[cfg(not(target_os = "linux"))]
use walkdir::WalkDir;

#[cfg(target_os = "linux")]
use crate::features::safe_traversal::DirFd;

use std::ffi::CString;
use std::fs::Metadata;
use std::io::Error as IOError;
use std::io::Result as IOResult;
use std::os::unix::fs::MetadataExt;

use std::os::unix::ffi::OsStrExt;
use std::path::{MAIN_SEPARATOR, Path};

/// The various level of verbosity
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum VerbosityLevel {
    Silent,
    Changes,
    Verbose,
    Normal,
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Verbosity {
    pub groups_only: bool,
    pub level: VerbosityLevel,
}

impl Default for Verbosity {
    fn default() -> Self {
        Self {
            groups_only: false,
            level: VerbosityLevel::Normal,
        }
    }
}

/// Actually perform the change of owner on a path
fn chown<P: AsRef<Path>>(path: P, uid: uid_t, gid: gid_t, follow: bool) -> IOResult<()> {
    let path = path.as_ref();
    let s = CString::new(path.as_os_str().as_bytes()).unwrap();
    let ret = unsafe {
        if follow {
            libc::chown(s.as_ptr(), uid, gid)
        } else {
            libc::lchown(s.as_ptr(), uid, gid)
        }
    };
    if ret == 0 {
        Ok(())
    } else {
        Err(IOError::last_os_error())
    }
}

/// Perform the change of owner on a path
/// with the various options
/// and error messages management
pub fn wrap_chown<P: AsRef<Path>>(
    path: P,
    meta: &Metadata,
    dest_uid: Option<u32>,
    dest_gid: Option<u32>,
    follow: bool,
    verbosity: Verbosity,
) -> Result<String, String> {
    let dest_uid = dest_uid.unwrap_or_else(|| meta.uid());
    let dest_gid = dest_gid.unwrap_or_else(|| meta.gid());
    let path = path.as_ref();
    let mut out: String = String::new();

    if let Err(e) = chown(path, dest_uid, dest_gid, follow) {
        match verbosity.level {
            VerbosityLevel::Silent => (),
            level => {
                out = format!(
                    "changing {} of {}: {e}",
                    if verbosity.groups_only {
                        "group"
                    } else {
                        "ownership"
                    },
                    path.quote(),
                );
                if level == VerbosityLevel::Verbose {
                    out = if verbosity.groups_only {
                        let gid = meta.gid();
                        format!(
                            "{out}\nfailed to change group of {} from {} to {}",
                            path.quote(),
                            entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                            entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                        )
                    } else {
                        let uid = meta.uid();
                        let gid = meta.gid();
                        format!(
                            "{out}\nfailed to change ownership of {} from {}:{} to {}:{}",
                            path.quote(),
                            entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
                            entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                            entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                            entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                        )
                    };
                }
            }
        }
        return Err(out);
    }

    let changed = dest_uid != meta.uid() || dest_gid != meta.gid();
    if changed {
        match verbosity.level {
            VerbosityLevel::Changes | VerbosityLevel::Verbose => {
                let gid = meta.gid();
                out = if verbosity.groups_only {
                    format!(
                        "changed group of {} from {} to {}",
                        path.quote(),
                        entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                        entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                    )
                } else {
                    let gid = meta.gid();
                    let uid = meta.uid();
                    format!(
                        "changed ownership of {} from {}:{} to {}:{}",
                        path.quote(),
                        entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
                        entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                        entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                        entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                    )
                };
            }
            _ => (),
        }
    } else if verbosity.level == VerbosityLevel::Verbose {
        out = if verbosity.groups_only {
            format!(
                "group of {} retained as {}",
                path.quote(),
                entries::gid2grp(dest_gid).unwrap_or_default()
            )
        } else {
            format!(
                "ownership of {} retained as {}:{}",
                path.quote(),
                entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
            )
        };
    }

    Ok(out)
}

pub enum IfFrom {
    All,
    User(u32),
    Group(u32),
    UserGroup(u32, u32),
}

#[derive(PartialEq, Eq)]
pub enum TraverseSymlinks {
    None,
    First,
    All,
}

pub struct ChownExecutor {
    pub dest_uid: Option<u32>,
    pub dest_gid: Option<u32>,
    pub raw_owner: String, // The owner of the file as input by the user in the command line.
    pub traverse_symlinks: TraverseSymlinks,
    pub verbosity: Verbosity,
    pub filter: IfFrom,
    pub files: Vec<OsString>,
    pub recursive: bool,
    pub preserve_root: bool,
    pub dereference: bool,
}

#[cfg(test)]
pub fn check_root(path: &Path, would_recurse_symlink: bool) -> bool {
    is_root(path, would_recurse_symlink)
}

/// In the context of chown and chgrp, check whether we are in a "preserve-root" scenario.
///
/// In particular, we want to prohibit further traversal only if:
///     (--preserve-root and -R present) &&
///     (path canonicalizes to "/") &&
///     (
///         (path is a symlink && would traverse/recurse this symlink) ||
///         (path is not a symlink)
///     )
/// The first clause is checked by the caller, the second and third clause is checked here.
/// The caller has to evaluate -P/-H/-L into 'would_recurse_symlink'.
/// Recall that canonicalization resolves both relative paths (e.g. "..") and symlinks.
fn is_root(path: &Path, would_traverse_symlink: bool) -> bool {
    // The third clause can be evaluated without any syscalls, so we do that first.
    // If we would_recurse_symlink, then the clause is true no matter whether the path is a symlink
    // or not. Otherwise, we only need to check here if the path can syntactically be a symlink:
    if !would_traverse_symlink {
        // We cannot check path.is_dir() here, as this would resolve symlinks,
        // which we need to avoid here.
        // All directory-ish paths match "*/", except ".", "..", "*/.", and "*/..".
        let path_bytes = path.as_os_str().as_encoded_bytes();
        let looks_like_dir = path_bytes == [b'.']
            || path_bytes == [b'.', b'.']
            || path_bytes.ends_with(&[MAIN_SEPARATOR as u8])
            || path_bytes.ends_with(&[MAIN_SEPARATOR as u8, b'.'])
            || path_bytes.ends_with(&[MAIN_SEPARATOR as u8, b'.', b'.']);

        if !looks_like_dir {
            return false;
        }
    }

    // FIXME: TOCTOU bug! canonicalize() runs at a different time than WalkDir's recursion decision.
    // However, we're forced to make the decision whether to warn about --preserve-root
    // *before* even attempting to chown the path, let alone doing the stat inside WalkDir.
    if let Ok(p) = path.canonicalize() {
        let path_buf = path.to_path_buf();
        if p.parent().is_none() {
            if path_buf.as_os_str() == "/" {
                show_error!("it is dangerous to operate recursively on '/'");
            } else {
                show_error!(
                    "it is dangerous to operate recursively on {} (same as '/')",
                    path_buf.quote()
                );
            }
            show_error!("use --no-preserve-root to override this failsafe");
            return true;
        }
    }

    false
}

pub fn get_metadata(file: &Path, follow: bool) -> Result<Metadata, std::io::Error> {
    if follow {
        file.metadata()
    } else {
        file.symlink_metadata()
    }
}

impl ChownExecutor {
    pub fn exec(&self) -> UResult<()> {
        let mut ret = 0;
        for f in &self.files {
            ret |= self.traverse(f);
        }
        if ret != 0 {
            return Err(ret.into());
        }
        Ok(())
    }

    #[allow(clippy::cognitive_complexity)]
    fn traverse<P: AsRef<Path>>(&self, root: P) -> i32 {
        let path = root.as_ref();
        let Some(meta) = self.obtain_meta(path, self.dereference) else {
            if self.verbosity.level == VerbosityLevel::Verbose {
                println!(
                    "failed to change ownership of {} to {}",
                    path.quote(),
                    self.raw_owner
                );
            }
            return 1;
        };

        if self.recursive
            && self.preserve_root
            && is_root(path, self.traverse_symlinks != TraverseSymlinks::None)
        {
            // Fail-fast, do not attempt to recurse.
            return 1;
        }

        let ret = if self.matched(meta.uid(), meta.gid()) {
            // Use safe syscalls for root directory to prevent TOCTOU attacks on Linux
            #[cfg(target_os = "linux")]
            let chown_result = if path.is_dir() {
                // For directories on Linux, use safe traversal from the start
                match DirFd::open(path) {
                    Ok(dir_fd) => self
                        .safe_chown_dir(&dir_fd, path, &meta)
                        .map(|_| String::new()),
                    Err(_e) => {
                        // Don't show error here - let safe_dive_into handle directory traversal errors
                        // This prevents duplicate error messages
                        Ok(String::new())
                    }
                }
            } else {
                // For non-directories (files, symlinks), use the regular wrap_chown method
                wrap_chown(
                    path,
                    &meta,
                    self.dest_uid,
                    self.dest_gid,
                    self.dereference,
                    self.verbosity.clone(),
                )
            };

            #[cfg(not(target_os = "linux"))]
            let chown_result = wrap_chown(
                path,
                &meta,
                self.dest_uid,
                self.dest_gid,
                self.dereference,
                self.verbosity.clone(),
            );

            match chown_result {
                Ok(n) => {
                    if !n.is_empty() {
                        show_error!("{n}");
                    }
                    0
                }
                Err(e) => {
                    if self.verbosity.level != VerbosityLevel::Silent {
                        show_error!("{e}");
                    }
                    1
                }
            }
        } else {
            self.print_verbose_ownership_retained_as(
                path,
                meta.uid(),
                self.dest_gid.map(|_| meta.gid()),
            );
            0
        };

        if self.recursive {
            #[cfg(target_os = "linux")]
            {
                ret | self.safe_dive_into(&root)
            }
            #[cfg(not(target_os = "linux"))]
            {
                ret | self.dive_into(&root)
            }
        } else {
            ret
        }
    }

    #[cfg(target_os = "linux")]
    fn safe_chown_dir(&self, dir_fd: &DirFd, path: &Path, meta: &Metadata) -> Result<(), String> {
        let dest_uid = self.dest_uid.unwrap_or_else(|| meta.uid());
        let dest_gid = self.dest_gid.unwrap_or_else(|| meta.gid());

        // Use fchown (safe) to change the directory's ownership
        if let Err(e) = dir_fd.fchown(self.dest_uid, self.dest_gid) {
            let mut error_msg = format!(
                "changing {} of {}: {}",
                if self.verbosity.groups_only {
                    "group"
                } else {
                    "ownership"
                },
                path.quote(),
                e
            );

            if self.verbosity.level == VerbosityLevel::Verbose {
                error_msg = if self.verbosity.groups_only {
                    let gid = meta.gid();
                    format!(
                        "{error_msg}\nfailed to change group of {} from {} to {}",
                        path.quote(),
                        entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                        entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                    )
                } else {
                    let uid = meta.uid();
                    let gid = meta.gid();
                    format!(
                        "{error_msg}\nfailed to change ownership of {} from {}:{} to {}:{}",
                        path.quote(),
                        entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
                        entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string()),
                        entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                        entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                    )
                };
            }

            return Err(error_msg);
        }

        // Report the change if verbose (similar to wrap_chown)
        self.report_ownership_change_success(path, meta.uid(), meta.gid());
        Ok(())
    }

    #[cfg(target_os = "linux")]
    fn safe_dive_into<P: AsRef<Path>>(&self, root: P) -> i32 {
        let root = root.as_ref();

        // Don't traverse into symlinks if configured not to
        if self.traverse_symlinks == TraverseSymlinks::None && root.is_symlink() {
            return 0;
        }

        // Only try to traverse if the root is actually a directory
        // This matches WalkDir's behavior with min_depth(1) - if root is not a directory,
        // there are no children to traverse, so we return early with success
        if !root.is_dir() {
            return 0;
        }

        // Open directory with safe traversal
        let Some(dir_fd) = self.try_open_dir(root) else {
            return 1;
        };

        let mut ret = 0;
        self.safe_traverse_dir(&dir_fd, root, &mut ret);
        ret
    }

    #[cfg(target_os = "linux")]
    fn safe_traverse_dir(&self, dir_fd: &DirFd, dir_path: &Path, ret: &mut i32) {
        // Read directory entries
        let entries = match dir_fd.read_dir() {
            Ok(entries) => entries,
            Err(e) => {
                *ret = 1;
                if self.verbosity.level != VerbosityLevel::Silent {
                    show_error!(
                        "cannot read directory '{}': {}",
                        dir_path.display(),
                        strip_errno(&e)
                    );
                }
                return;
            }
        };

        for entry_name in entries {
            let entry_path = dir_path.join(&entry_name);

            // Get metadata for the entry
            let follow = self.traverse_symlinks == TraverseSymlinks::All;

            let meta = match dir_fd.metadata_at(&entry_name, follow) {
                Ok(m) => m,
                Err(e) => {
                    *ret = 1;
                    if self.verbosity.level != VerbosityLevel::Silent {
                        show_error!(
                            "cannot access '{}': {}",
                            entry_path.display(),
                            strip_errno(&e)
                        );
                    }
                    continue;
                }
            };

            if self.preserve_root
                && is_root(&entry_path, self.traverse_symlinks == TraverseSymlinks::All)
            {
                *ret = 1;
                return;
            }

            // Check if we should chown this entry
            if self.matched(meta.uid(), meta.gid()) {
                // Use fchownat for the actual ownership change
                let follow_symlinks =
                    self.dereference || self.traverse_symlinks == TraverseSymlinks::All;

                // Only pass the IDs that should actually be changed
                let chown_uid = self.dest_uid;
                let chown_gid = self.dest_gid;

                if let Err(e) = dir_fd.chown_at(&entry_name, chown_uid, chown_gid, follow_symlinks)
                {
                    *ret = 1;
                    if self.verbosity.level != VerbosityLevel::Silent {
                        let msg = format!(
                            "changing {} of {}: {}",
                            if self.verbosity.groups_only {
                                "group"
                            } else {
                                "ownership"
                            },
                            entry_path.quote(),
                            strip_errno(&e)
                        );
                        show_error!("{}", msg);
                    }
                } else {
                    // Report the successful ownership change using the shared helper
                    self.report_ownership_change_success(&entry_path, meta.uid(), meta.gid());
                }
            } else {
                self.print_verbose_ownership_retained_as(
                    &entry_path,
                    meta.uid(),
                    self.dest_gid.map(|_| meta.gid()),
                );
            }

            // Recurse into subdirectories
            if meta.is_dir() && (follow || !meta.file_type().is_symlink()) {
                match dir_fd.open_subdir(&entry_name) {
                    Ok(subdir_fd) => {
                        self.safe_traverse_dir(&subdir_fd, &entry_path, ret);
                    }
                    Err(e) => {
                        *ret = 1;
                        if self.verbosity.level != VerbosityLevel::Silent {
                            show_error!(
                                "cannot access '{}': {}",
                                entry_path.display(),
                                strip_errno(&e)
                            );
                        }
                    }
                }
            }
        }
    }

    #[cfg(not(target_os = "linux"))]
    #[allow(clippy::cognitive_complexity)]
    fn dive_into<P: AsRef<Path>>(&self, root: P) -> i32 {
        let root = root.as_ref();

        // walkdir always dereferences the root directory, so we have to check it ourselves
        if self.traverse_symlinks == TraverseSymlinks::None && root.is_symlink() {
            return 0;
        }

        let mut ret = 0;
        let mut iterator = WalkDir::new(root)
            .follow_links(self.traverse_symlinks == TraverseSymlinks::All)
            .min_depth(1)
            .into_iter();
        // We can't use a for loop because we need to manipulate the iterator inside the loop.
        while let Some(entry) = iterator.next() {
            let entry = match entry {
                Err(e) => {
                    ret = 1;
                    if let Some(path) = e.path() {
                        show_error!(
                            "cannot access '{}': {}",
                            path.display(),
                            if let Some(error) = e.io_error() {
                                strip_errno(error)
                            } else {
                                "Too many levels of symbolic links".into()
                            }
                        );
                    } else {
                        show_error!("{e}");
                    }
                    continue;
                }
                Ok(entry) => entry,
            };
            let path = entry.path();

            let Some(meta) = self.obtain_meta(path, self.dereference) else {
                ret = 1;
                if entry.file_type().is_dir() {
                    // Instruct walkdir to skip this directory to avoid getting another error
                    // when walkdir tries to query the children of this directory.
                    iterator.skip_current_dir();
                }
                continue;
            };

            if self.preserve_root && is_root(path, self.traverse_symlinks == TraverseSymlinks::All)
            {
                // Fail-fast, do not recurse further.
                return 1;
            }

            if !self.matched(meta.uid(), meta.gid()) {
                self.print_verbose_ownership_retained_as(
                    path,
                    meta.uid(),
                    self.dest_gid.map(|_| meta.gid()),
                );
                continue;
            }

            ret = match wrap_chown(
                path,
                &meta,
                self.dest_uid,
                self.dest_gid,
                self.dereference,
                self.verbosity.clone(),
            ) {
                Ok(n) => {
                    if !n.is_empty() {
                        show_error!("{n}");
                    }
                    0
                }
                Err(e) => {
                    if self.verbosity.level != VerbosityLevel::Silent {
                        show_error!("{e}");
                    }
                    1
                }
            }
        }
        ret
    }

    fn obtain_meta<P: AsRef<Path>>(&self, path: P, follow: bool) -> Option<Metadata> {
        let path = path.as_ref();
        get_metadata(path, follow)
            .inspect_err(|e| {
                if self.verbosity.level != VerbosityLevel::Silent {
                    show_error!(
                        "cannot {} {}: {}",
                        if follow { "dereference" } else { "access" },
                        path.quote(),
                        strip_errno(e)
                    );
                }
            })
            .ok()
    }

    #[inline]
    fn matched(&self, uid: uid_t, gid: gid_t) -> bool {
        match self.filter {
            IfFrom::All => true,
            IfFrom::User(u) => u == uid,
            IfFrom::Group(g) => g == gid,
            IfFrom::UserGroup(u, g) => u == uid && g == gid,
        }
    }

    fn print_verbose_ownership_retained_as(&self, path: &Path, uid: u32, gid: Option<u32>) {
        if self.verbosity.level == VerbosityLevel::Verbose {
            let ownership = match (self.dest_uid, self.dest_gid, gid) {
                (Some(_), Some(_), Some(gid)) => format!(
                    "{}:{}",
                    entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
                    entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string())
                ),
                (None, Some(_), Some(gid)) => {
                    entries::gid2grp(gid).unwrap_or_else(|_| gid.to_string())
                }
                _ => entries::uid2usr(uid).unwrap_or_else(|_| uid.to_string()),
            };
            if self.verbosity.groups_only {
                println!("group of {} retained as {ownership}", path.quote());
            } else {
                println!("ownership of {} retained as {ownership}", path.quote());
            }
        }
    }

    /// Try to open directory with error reporting
    #[cfg(target_os = "linux")]
    fn try_open_dir(&self, path: &Path) -> Option<DirFd> {
        DirFd::open(path)
            .map_err(|e| {
                if self.verbosity.level != VerbosityLevel::Silent {
                    show_error!("cannot access '{}': {}", path.display(), strip_errno(&e));
                }
            })
            .ok()
    }

    /// Report ownership change with proper verbose output
    /// Returns 0 on success
    #[cfg(target_os = "linux")]
    fn report_ownership_change_success(
        &self,
        path: &Path,
        original_uid: u32,
        original_gid: u32,
    ) -> i32 {
        let dest_uid = self.dest_uid.unwrap_or(original_uid);
        let dest_gid = self.dest_gid.unwrap_or(original_gid);
        let changed = dest_uid != original_uid || dest_gid != original_gid;

        if changed {
            match self.verbosity.level {
                VerbosityLevel::Changes | VerbosityLevel::Verbose => {
                    let output = if self.verbosity.groups_only {
                        format!(
                            "changed group of {} from {} to {}",
                            path.quote(),
                            entries::gid2grp(original_gid)
                                .unwrap_or_else(|_| original_gid.to_string()),
                            entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                        )
                    } else {
                        format!(
                            "changed ownership of {} from {}:{} to {}:{}",
                            path.quote(),
                            entries::uid2usr(original_uid)
                                .unwrap_or_else(|_| original_uid.to_string()),
                            entries::gid2grp(original_gid)
                                .unwrap_or_else(|_| original_gid.to_string()),
                            entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                            entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                        )
                    };
                    show_error!("{output}");
                }
                _ => (),
            }
        } else if self.verbosity.level == VerbosityLevel::Verbose {
            let output = if self.verbosity.groups_only {
                format!(
                    "group of {} retained as {}",
                    path.quote(),
                    entries::gid2grp(dest_gid).unwrap_or_default()
                )
            } else {
                format!(
                    "ownership of {} retained as {}:{}",
                    path.quote(),
                    entries::uid2usr(dest_uid).unwrap_or_else(|_| dest_uid.to_string()),
                    entries::gid2grp(dest_gid).unwrap_or_else(|_| dest_gid.to_string())
                )
            };
            show_error!("{output}");
        }
        0
    }
}

pub mod options {
    pub const HELP: &str = "help";
    pub mod verbosity {
        pub const CHANGES: &str = "changes";
        pub const QUIET: &str = "quiet";
        pub const SILENT: &str = "silent";
        pub const VERBOSE: &str = "verbose";
    }
    pub mod preserve_root {
        pub const PRESERVE: &str = "preserve-root";
        pub const NO_PRESERVE: &str = "no-preserve-root";
    }
    pub mod dereference {
        pub const DEREFERENCE: &str = "dereference";
        pub const NO_DEREFERENCE: &str = "no-dereference";
    }
    pub const FROM: &str = "from";
    pub const RECURSIVE: &str = "recursive";
    pub mod traverse {
        pub const TRAVERSE: &str = "H";
        pub const NO_TRAVERSE: &str = "P";
        pub const EVERY: &str = "L";
    }
    pub const REFERENCE: &str = "reference";
    pub const ARG_OWNER: &str = "OWNER";
    pub const ARG_GROUP: &str = "GROUP";
    pub const ARG_FILES: &str = "FILE";
}

pub struct GidUidOwnerFilter {
    pub dest_gid: Option<u32>,
    pub dest_uid: Option<u32>,
    pub raw_owner: String,
    pub filter: IfFrom,
}
type GidUidFilterOwnerParser = fn(&ArgMatches) -> UResult<GidUidOwnerFilter>;

/// Determines symbolic link traversal and recursion settings based on flags.
/// Returns the updated `dereference` and `traverse_symlinks` values.
pub fn configure_symlink_and_recursion(
    matches: &ArgMatches,
    default_traverse_symlinks: TraverseSymlinks,
) -> Result<(bool, bool, TraverseSymlinks), Box<dyn crate::error::UError>> {
    let mut dereference = if matches.get_flag(options::dereference::DEREFERENCE) {
        Some(true) // Follow symlinks
    } else if matches.get_flag(options::dereference::NO_DEREFERENCE) {
        Some(false) // Do not follow symlinks
    } else {
        None // Default behavior
    };

    let mut traverse_symlinks = if matches.get_flag("L") {
        TraverseSymlinks::All
    } else if matches.get_flag("H") {
        TraverseSymlinks::First
    } else if matches.get_flag("P") {
        TraverseSymlinks::None
    } else {
        default_traverse_symlinks
    };

    let recursive = matches.get_flag(options::RECURSIVE);
    if recursive {
        if traverse_symlinks == TraverseSymlinks::None {
            if dereference == Some(true) {
                return Err(USimpleError::new(
                    1,
                    "-R --dereference requires -H or -L".to_string(),
                ));
            }
            dereference = Some(false);
        }
    } else {
        traverse_symlinks = TraverseSymlinks::None;
    }

    Ok((recursive, dereference.unwrap_or(true), traverse_symlinks))
}

/// Base implementation for `chgrp` and `chown`.
///
/// An argument called `add_arg_if_not_reference` will be added to `command` if
/// `args` does not contain the `--reference` option.
/// `parse_gid_uid_and_filter` will be called to obtain the target gid and uid, and the filter,
/// from `ArgMatches`.
/// `groups_only` determines whether verbose output will only mention the group.
#[allow(clippy::cognitive_complexity)]
pub fn chown_base(
    mut command: Command,
    args: impl crate::Args,
    add_arg_if_not_reference: &'static str,
    parse_gid_uid_and_filter: GidUidFilterOwnerParser,
    groups_only: bool,
) -> UResult<()> {
    let args: Vec<_> = args.collect();
    let mut reference = false;
    let mut help = false;
    // stop processing options on --
    for arg in args.iter().take_while(|s| *s != "--") {
        if arg.to_string_lossy().starts_with("--reference=") || arg == "--reference" {
            reference = true;
        } else if arg == "--help" {
            // we stop processing once we see --help,
            // as it doesn't matter if we've seen reference or not
            help = true;
            break;
        }
    }

    if help || !reference {
        // add both positional arguments
        // arg_group is only required if
        command = command.arg(
            Arg::new(add_arg_if_not_reference)
                .value_name(add_arg_if_not_reference)
                .required(true),
        );
    }
    command = command.arg(
        Arg::new(options::ARG_FILES)
            .value_name(options::ARG_FILES)
            .value_hint(clap::ValueHint::FilePath)
            .action(clap::ArgAction::Append)
            .required(true)
            .num_args(1..)
            .value_parser(clap::value_parser!(std::ffi::OsString)),
    );
    let matches = crate::clap_localization::handle_clap_result(command, args)?;

    let files: Vec<OsString> = matches
        .get_many::<OsString>(options::ARG_FILES)
        .map(|v| v.cloned().collect())
        .unwrap_or_default();

    let preserve_root = matches.get_flag(options::preserve_root::PRESERVE);
    let (recursive, dereference, traverse_symlinks) =
        configure_symlink_and_recursion(&matches, TraverseSymlinks::None)?;

    let verbosity_level = if matches.get_flag(options::verbosity::CHANGES) {
        VerbosityLevel::Changes
    } else if matches.get_flag(options::verbosity::SILENT)
        || matches.get_flag(options::verbosity::QUIET)
    {
        VerbosityLevel::Silent
    } else if matches.get_flag(options::verbosity::VERBOSE) {
        VerbosityLevel::Verbose
    } else {
        VerbosityLevel::Normal
    };
    let GidUidOwnerFilter {
        dest_gid,
        dest_uid,
        raw_owner,
        filter,
    } = parse_gid_uid_and_filter(&matches)?;

    let executor = ChownExecutor {
        traverse_symlinks,
        dest_gid,
        dest_uid,
        raw_owner,
        verbosity: Verbosity {
            groups_only,
            level: verbosity_level,
        },
        recursive,
        dereference,
        preserve_root,
        files,
        filter,
    };
    executor.exec()
}

pub fn common_args() -> Vec<Arg> {
    vec![
        Arg::new(traverse::TRAVERSE)
            .short(traverse::TRAVERSE.chars().next().unwrap())
            .help("if a command line argument is a symbolic link to a directory, traverse it")
            .overrides_with_all([traverse::EVERY, traverse::NO_TRAVERSE])
            .action(clap::ArgAction::SetTrue),
        Arg::new(traverse::EVERY)
            .short(traverse::EVERY.chars().next().unwrap())
            .help("traverse every symbolic link to a directory encountered")
            .overrides_with_all([traverse::TRAVERSE, traverse::NO_TRAVERSE])
            .action(clap::ArgAction::SetTrue),
        Arg::new(traverse::NO_TRAVERSE)
            .short(traverse::NO_TRAVERSE.chars().next().unwrap())
            .help("do not traverse any symbolic links (default)")
            .overrides_with_all([traverse::TRAVERSE, traverse::EVERY])
            .action(clap::ArgAction::SetTrue),
        Arg::new(options::dereference::DEREFERENCE)
            .long(options::dereference::DEREFERENCE)
            .help(
                "affect the referent of each symbolic link (this is the default), \
    rather than the symbolic link itself",
            )
            .action(clap::ArgAction::SetTrue),
        Arg::new(options::dereference::NO_DEREFERENCE)
            .short('h')
            .long(options::dereference::NO_DEREFERENCE)
            .help(
                "affect symbolic links instead of any referenced file \
        (useful only on systems that can change the ownership of a symlink)",
            )
            .action(clap::ArgAction::SetTrue),
    ]
}

#[cfg(test)]
mod tests {
    // Note this useful idiom: importing names from outer (for mod tests) scope.
    use super::*;
    #[cfg(unix)]
    use std::os::unix;
    use std::path::{Component, PathBuf};
    #[cfg(unix)]
    use tempfile::tempdir;

    #[test]
    fn test_empty_string() {
        let path = PathBuf::new();
        assert_eq!(path.to_str(), Some(""));
        // The main point to test here is that we don't crash.
        // The result should be 'false', to avoid unnecessary and confusing warnings.
        assert!(!is_root(&path, false));
        assert!(!is_root(&path, true));
    }

    #[allow(clippy::needless_borrow)]
    #[cfg(unix)]
    #[test]
    fn test_literal_root() {
        let component = Component::RootDir;
        let path: &Path = component.as_ref();
        assert_eq!(
            path.to_str(),
            Some("/"),
            "cfg(unix) but using non-unix path delimiters?!"
        );
        // Must return true, this is the main scenario that --preserve-root shall prevent.
        assert!(is_root(&path, false));
        assert!(is_root(&path, true));
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_slash() {
        let temp_dir = tempdir().unwrap();
        let symlink_path = temp_dir.path().join("symlink");
        unix::fs::symlink(PathBuf::from("/"), symlink_path).unwrap();
        let symlink_path_slash = temp_dir.path().join("symlink/");
        // Must return true, we're about to "accidentally" recurse on "/",
        // since "symlink/" always counts as an already-entered directory
        // Output from GNU:
        //   $ chown --preserve-root -RH --dereference $(id -u) slink-to-root/
        //   chown: it is dangerous to operate recursively on 'slink-to-root/' (same as '/')
        //   chown: use --no-preserve-root to override this failsafe
        //   [$? = 1]
        //   $ chown --preserve-root -RH --no-dereference $(id -u) slink-to-root/
        //   chown: it is dangerous to operate recursively on 'slink-to-root/' (same as '/')
        //   chown: use --no-preserve-root to override this failsafe
        //   [$? = 1]
        assert!(is_root(&symlink_path_slash, false));
        assert!(is_root(&symlink_path_slash, true));
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_no_slash() {
        // This covers both the commandline-argument case and the recursion case.
        let temp_dir = tempdir().unwrap();
        let symlink_path = temp_dir.path().join("symlink");
        unix::fs::symlink(PathBuf::from("/"), &symlink_path).unwrap();
        // Only return true  we're about to "accidentally" recurse on "/".
        assert!(!is_root(&symlink_path, false));
        assert!(is_root(&symlink_path, true));
    }
}