1use crate::filter::TimeFilter;
6use crate::preserve::Metadata as _;
7use crate::progress::Progress;
8use crate::safedir::{self, Dir, FileMeta, Handle};
9use crate::walk::{AdmittedLeaf, EntryKind, LeafPermit, PermitKind};
10use crate::walk_driver::{
11 DirAction, DirPostInput, DirPreResult, EntryCx, SkippedEntry, WalkVisitor, process_entry,
12};
13use anyhow::{Context, anyhow};
14use std::ffi::OsStr;
15use std::os::unix::fs::PermissionsExt;
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18use tracing::instrument;
19
20const SETID_BITS: u32 = 0o6000;
21
22fn mode_of(meta: &FileMeta) -> u32 {
27 meta.permissions().mode() & 0o7777
28}
29
30pub type Error = crate::error::OperationError<Summary>;
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36pub struct OwnerProgram {
37 pub file: Option<u32>,
38 pub dir: Option<u32>,
39 pub symlink: Option<u32>,
40}
41
42impl OwnerProgram {
43 #[must_use]
44 pub fn for_kind(&self, kind: EntryKind) -> Option<u32> {
45 match kind {
46 EntryKind::Dir => self.dir,
47 EntryKind::Symlink => self.symlink,
48 EntryKind::File | EntryKind::Special => self.file,
49 }
50 }
51 #[must_use]
52 pub fn is_empty(&self) -> bool {
53 self.file.is_none() && self.dir.is_none() && self.symlink.is_none()
54 }
55}
56
57#[derive(Clone, Debug, PartialEq, Eq)]
60pub enum ModeSpec {
61 Symbolic(Vec<SymbolicClause>),
62 Octal(u32),
63}
64
65#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct SymbolicClause {
69 pub who: u8,
70 pub op: ModeOp,
71 pub perms: u8,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum ModeOp {
77 Add,
78 Remove,
79 Set,
80}
81
82pub(crate) const WHO_U: u8 = 0b001;
83pub(crate) const WHO_G: u8 = 0b010;
84pub(crate) const WHO_O: u8 = 0b100;
85pub(crate) const WHO_A: u8 = WHO_U | WHO_G | WHO_O;
86pub(crate) const PERM_R: u8 = 0b00_0001;
87pub(crate) const PERM_W: u8 = 0b00_0010;
88pub(crate) const PERM_X: u8 = 0b00_0100;
89pub(crate) const PERM_BIGX: u8 = 0b00_1000;
90pub(crate) const PERM_S: u8 = 0b01_0000;
91pub(crate) const PERM_T: u8 = 0b10_0000;
92
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
96pub struct ModeProgram {
97 pub file: Option<ModeSpec>,
98 pub dir: Option<ModeSpec>,
99}
100
101impl ModeProgram {
102 #[must_use]
103 pub fn for_kind(&self, kind: EntryKind) -> Option<&ModeSpec> {
104 match kind {
105 EntryKind::Dir => self.dir.as_ref(),
106 EntryKind::Symlink => None,
107 EntryKind::File | EntryKind::Special => self.file.as_ref(),
108 }
109 }
110 #[must_use]
111 pub fn is_empty(&self) -> bool {
112 self.file.is_none() && self.dir.is_none()
113 }
114}
115
116#[derive(Clone, Debug)]
118pub struct Settings {
119 pub mode: ModeProgram,
120 pub owner: OwnerProgram,
121 pub group: OwnerProgram,
122 pub no_setid: bool,
124 pub fail_early: bool,
125 pub defer_dir_changes: bool,
129 pub filter: Option<crate::filter::FilterSettings>,
130 pub time_filter: Option<TimeFilter>,
131 pub dry_run: Option<crate::config::DryRunMode>,
132}
133
134#[derive(Copy, Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
135pub struct Summary {
136 pub files_changed: usize,
137 pub symlinks_changed: usize,
138 pub directories_changed: usize,
139 pub files_unchanged: usize,
140 pub symlinks_unchanged: usize,
141 pub directories_unchanged: usize,
142 pub files_skipped: usize,
143 pub symlinks_skipped: usize,
144 pub directories_skipped: usize,
145}
146
147impl std::ops::Add for Summary {
148 type Output = Self;
149 fn add(self, other: Self) -> Self {
150 Self {
151 files_changed: self.files_changed + other.files_changed,
152 symlinks_changed: self.symlinks_changed + other.symlinks_changed,
153 directories_changed: self.directories_changed + other.directories_changed,
154 files_unchanged: self.files_unchanged + other.files_unchanged,
155 symlinks_unchanged: self.symlinks_unchanged + other.symlinks_unchanged,
156 directories_unchanged: self.directories_unchanged + other.directories_unchanged,
157 files_skipped: self.files_skipped + other.files_skipped,
158 symlinks_skipped: self.symlinks_skipped + other.symlinks_skipped,
159 directories_skipped: self.directories_skipped + other.directories_skipped,
160 }
161 }
162}
163
164impl std::fmt::Display for Summary {
165 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
166 write!(
167 f,
168 "files changed: {}\n\
169 symlinks changed: {}\n\
170 directories changed: {}\n\
171 files unchanged: {}\n\
172 symlinks unchanged: {}\n\
173 directories unchanged: {}\n\
174 files skipped: {}\n\
175 symlinks skipped: {}\n\
176 directories skipped: {}\n",
177 self.files_changed,
178 self.symlinks_changed,
179 self.directories_changed,
180 self.files_unchanged,
181 self.symlinks_unchanged,
182 self.directories_unchanged,
183 self.files_skipped,
184 self.symlinks_skipped,
185 self.directories_skipped
186 )
187 }
188}
189
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum IdKind {
193 User,
194 Group,
195}
196
197impl IdKind {
198 fn getent_database(self) -> &'static str {
200 match self {
201 IdKind::User => "passwd",
202 IdKind::Group => "group",
203 }
204 }
205 fn label(self) -> &'static str {
207 match self {
208 IdKind::User => "user",
209 IdKind::Group => "group",
210 }
211 }
212}
213
214fn resolve_id(token: &str, kind: IdKind, getent: &GetentResolver) -> anyhow::Result<u32> {
220 if let Ok(n) = token.parse::<u32>() {
221 return Ok(n);
222 }
223 let in_process = match kind {
224 IdKind::User => {
225 nix::unistd::User::from_name(token).map(|user| user.map(|u| u.uid.as_raw()))
226 }
227 IdKind::Group => {
228 nix::unistd::Group::from_name(token).map(|group| group.map(|g| g.gid.as_raw()))
229 }
230 };
231 match in_process {
232 Ok(Some(id)) => Ok(id),
233 Ok(None) | Err(_) => resolve_via_getent(token, kind, getent),
237 }
238}
239
240const GETENT_NOT_FOUND: i32 = 2;
244
245fn resolve_via_getent(token: &str, kind: IdKind, getent: &GetentResolver) -> anyhow::Result<u32> {
254 match getent.program()? {
255 Some(path) => resolve_via_getent_cmd(path.as_os_str(), token, kind),
256 None => resolve_via_getent_cmd(OsStr::new("getent"), token, kind),
257 }
258}
259
260fn resolve_via_getent_cmd(
266 getent_program: &OsStr,
267 token: &str,
268 kind: IdKind,
269) -> anyhow::Result<u32> {
270 let database = kind.getent_database();
271 let label = kind.label();
272 let prog = getent_program.to_string_lossy();
274 let output = std::process::Command::new(getent_program)
280 .args(["--", database, token])
281 .output()
282 .with_context(|| {
283 format!(
284 "cannot run `{prog} {database} {token}` to look up the {label} name; \
285 use a numeric id instead"
286 )
287 })?;
288 if output.status.code() == Some(GETENT_NOT_FOUND) {
289 return Err(anyhow!("unknown {label}: {token}"));
290 }
291 if !output.status.success() {
292 let status = output.status;
293 let stderr = String::from_utf8_lossy(&output.stderr);
294 let stderr = stderr.trim();
295 let detail = if stderr.is_empty() {
296 String::new()
297 } else {
298 format!(": {stderr}")
299 };
300 return Err(anyhow!(
301 "`{prog} {database} {token}` failed with {status}{detail}; \
302 use a numeric id instead"
303 ));
304 }
305 let stdout = String::from_utf8_lossy(&output.stdout);
306 let line = stdout
307 .lines()
308 .next()
309 .ok_or_else(|| anyhow!("`{prog} {database} {token}` produced no output"))?;
310 parse_getent_id(line).with_context(|| format!("unexpected getent output {line:?}"))
311}
312
313const TRUSTED_GETENT_DIRS: &[&str] = &["/usr/bin", "/bin", "/run/current-system/sw/bin"];
319
320#[must_use]
326pub fn is_privileged() -> bool {
327 let euid = nix::unistd::geteuid();
328 euid.as_raw() == 0 || nix::unistd::getuid() != euid
329}
330
331#[derive(Clone, Debug)]
339pub struct GetentResolver {
340 explicit: Option<PathBuf>,
342 privileged: bool,
344}
345
346impl Default for GetentResolver {
349 fn default() -> Self {
350 Self {
351 explicit: None,
352 privileged: false,
353 }
354 }
355}
356
357impl GetentResolver {
358 pub fn from_cli(getent_path: Option<PathBuf>, privileged: bool) -> anyhow::Result<Self> {
363 if let Some(path) = &getent_path
364 && !path.is_absolute()
365 {
366 return Err(anyhow!(
367 "--getent-path must be an absolute path, got {path:?}"
368 ));
369 }
370 Ok(Self {
371 explicit: getent_path,
372 privileged,
373 })
374 }
375
376 fn program(&self) -> anyhow::Result<Option<PathBuf>> {
379 self.program_in(TRUSTED_GETENT_DIRS)
380 }
381
382 fn program_in(&self, trusted_dirs: &[&str]) -> anyhow::Result<Option<PathBuf>> {
384 if let Some(path) = &self.explicit {
385 return Ok(Some(path.clone()));
386 }
387 if !self.privileged {
388 return Ok(None);
391 }
392 for dir in trusted_dirs {
394 let candidate = Path::new(dir).join("getent");
395 if candidate.is_file() {
396 return Ok(Some(candidate));
397 }
398 }
399 Err(anyhow!(
400 "running with elevated privilege and could not find `getent` in any trusted \
401 directory ({}); PATH is intentionally ignored when privileged so a name lookup \
402 cannot exec an attacker-controlled binary as root — pass an absolute \
403 --getent-path, or use numeric ids",
404 trusted_dirs.join(", ")
405 ))
406 }
407}
408
409fn parse_getent_id(line: &str) -> anyhow::Result<u32> {
412 let field = line
413 .split(':')
414 .nth(2)
415 .ok_or_else(|| anyhow!("expected at least 3 ':'-separated fields"))?;
416 field
417 .parse::<u32>()
418 .with_context(|| format!("parsing id field {field:?}"))
419}
420
421pub fn parse_owner_dsl(
425 s: &str,
426 kind: IdKind,
427 getent: &GetentResolver,
428) -> anyhow::Result<OwnerProgram> {
429 let mut prog = OwnerProgram::default();
430 let mut bare: Option<u32> = None;
431 for clause in s.split_whitespace() {
432 if let Some((ty, rest)) = clause.split_once(':') {
433 let id = resolve_id(rest, kind, getent)?;
434 match ty {
435 "f" | "file" => prog.file = Some(id),
436 "d" | "dir" | "directory" => prog.dir = Some(id),
437 "l" | "link" | "symlink" => prog.symlink = Some(id),
438 _ => return Err(anyhow!("unknown type prefix {ty:?} (expected f:/d:/l:)")),
439 }
440 } else if bare.is_some() {
441 return Err(anyhow!(
442 "multiple bare values in {s:?}; use f:/d:/l: prefixes to set different types"
443 ));
444 } else {
445 bare = Some(resolve_id(clause, kind, getent)?);
446 }
447 }
448 if let Some(b) = bare {
449 prog.file.get_or_insert(b);
450 prog.dir.get_or_insert(b);
451 prog.symlink.get_or_insert(b);
452 }
453 Ok(prog)
454}
455
456#[must_use]
459pub fn apply_mode(current: u32, spec: &ModeSpec, is_dir: bool) -> u32 {
460 match spec {
461 ModeSpec::Octal(m) => m & 0o7777,
462 ModeSpec::Symbolic(clauses) => {
463 let mut mode = current & 0o7777;
464 for clause in clauses {
465 mode = apply_clause(mode, *clause, is_dir);
466 }
467 mode
468 }
469 }
470}
471
472fn apply_clause(current: u32, clause: SymbolicClause, is_dir: bool) -> u32 {
473 let any_exec = current & 0o111 != 0;
474 let exec =
475 (clause.perms & PERM_X != 0) || (clause.perms & PERM_BIGX != 0 && (is_dir || any_exec));
476 let r = clause.perms & PERM_R != 0;
477 let w = clause.perms & PERM_W != 0;
478 let s = clause.perms & PERM_S != 0;
479 let t = clause.perms & PERM_T != 0;
480 let mut value: u32 = 0;
481 if clause.who & WHO_U != 0 {
482 if r {
483 value |= 0o400;
484 }
485 if w {
486 value |= 0o200;
487 }
488 if exec {
489 value |= 0o100;
490 }
491 if s {
492 value |= 0o4000;
493 }
494 }
495 if clause.who & WHO_G != 0 {
496 if r {
497 value |= 0o040;
498 }
499 if w {
500 value |= 0o020;
501 }
502 if exec {
503 value |= 0o010;
504 }
505 if s {
506 value |= 0o2000;
507 }
508 }
509 if clause.who & WHO_O != 0 {
510 if r {
511 value |= 0o004;
512 }
513 if w {
514 value |= 0o002;
515 }
516 if exec {
517 value |= 0o001;
518 }
519 }
520 if t && clause.who & WHO_O != 0 {
521 value |= 0o1000;
523 }
524 match clause.op {
525 ModeOp::Add => current | value,
526 ModeOp::Remove => current & !value,
527 ModeOp::Set => {
528 let mut clear: u32 = 0;
529 if clause.who & WHO_U != 0 {
530 clear |= 0o4700;
531 }
532 if clause.who & WHO_G != 0 {
533 clear |= 0o2070;
534 }
535 if clause.who & WHO_O != 0 {
536 clear |= 0o1007;
537 }
538 (current & !clear) | value
539 }
540 }
541}
542
543fn parse_mode_token(token: &str) -> anyhow::Result<ModeSpec> {
546 if token.is_empty() {
547 return Err(anyhow!("empty mode"));
548 }
549 if token.bytes().all(|b| b.is_ascii_digit()) {
550 if token.bytes().any(|b| b > b'7') {
551 return Err(anyhow!("invalid octal mode {token:?} (digits must be 0-7)"));
552 }
553 let value = u32::from_str_radix(token, 8)
554 .with_context(|| format!("parsing octal mode {token:?}"))?;
555 if value > 0o7777 {
556 return Err(anyhow!("octal mode {token:?} out of range (max 0o7777)"));
557 }
558 return Ok(ModeSpec::Octal(value));
559 }
560 let clauses = token
561 .split(',')
562 .map(parse_symbolic_clause)
563 .collect::<anyhow::Result<Vec<_>>>()?;
564 Ok(ModeSpec::Symbolic(clauses))
565}
566
567fn parse_symbolic_clause(clause: &str) -> anyhow::Result<SymbolicClause> {
568 let op_pos = clause
569 .find(['+', '-', '='])
570 .ok_or_else(|| anyhow!("mode clause {clause:?} missing +, - or ="))?;
571 let (who_str, rest) = clause.split_at(op_pos);
572 let op = match &rest[..1] {
573 "+" => ModeOp::Add,
574 "-" => ModeOp::Remove,
575 "=" => ModeOp::Set,
576 _ => unreachable!("find guaranteed one of +-="),
577 };
578 let perms_str = &rest[1..];
579 let mut who = 0u8;
580 for ch in who_str.chars() {
581 who |= match ch {
582 'u' => WHO_U,
583 'g' => WHO_G,
584 'o' => WHO_O,
585 'a' => WHO_A,
586 other => {
587 return Err(anyhow!(
588 "invalid 'who' {other:?} in {clause:?} (expected u/g/o/a)"
589 ));
590 }
591 };
592 }
593 if who == 0 {
594 who = WHO_A;
595 }
596 let mut perms = 0u8;
597 for ch in perms_str.chars() {
598 perms |= match ch {
599 'r' => PERM_R,
600 'w' => PERM_W,
601 'x' => PERM_X,
602 'X' => PERM_BIGX,
603 's' => PERM_S,
604 't' => PERM_T,
605 other => return Err(anyhow!("invalid permission {other:?} in {clause:?}")),
606 };
607 }
608 Ok(SymbolicClause { who, op, perms })
609}
610
611pub fn parse_mode_dsl(s: &str) -> anyhow::Result<ModeProgram> {
615 let mut prog = ModeProgram::default();
616 let mut bare: Option<ModeSpec> = None;
617 for clause in s.split_whitespace() {
618 if let Some((ty, rest)) = clause.split_once(':') {
619 let spec = parse_mode_token(rest)?;
620 match ty {
621 "f" | "file" => prog.file = Some(spec),
622 "d" | "dir" | "directory" => prog.dir = Some(spec),
623 "l" | "link" | "symlink" => {
624 return Err(anyhow!(
625 "symlink mode (l:) is not settable on Linux; remove the l: section"
626 ));
627 }
628 _ => return Err(anyhow!("unknown type prefix {ty:?} (expected f:/d:)")),
629 }
630 } else if bare.is_some() {
631 return Err(anyhow!(
632 "multiple bare mode expressions in {s:?}; chain sub-ops with commas (e.g. g+r,o+w)"
633 ));
634 } else {
635 bare = Some(parse_mode_token(clause)?);
636 }
637 }
638 if let Some(b) = bare {
639 prog.file.get_or_insert(b.clone());
640 prog.dir.get_or_insert(b);
641 }
642 Ok(prog)
643}
644
645#[derive(Clone, Copy, Debug, PartialEq, Eq)]
651pub(crate) struct EntryPlan {
652 pub chmod_before_chown: Option<u32>,
653 pub chown: Option<(Option<u32>, Option<u32>)>,
654 pub chmod: Option<u32>,
655}
656
657impl EntryPlan {
658 pub(crate) fn is_noop(&self) -> bool {
659 self.chmod_before_chown.is_none() && self.chown.is_none() && self.chmod.is_none()
660 }
661}
662
663pub(crate) fn compute_plan(
666 cur_mode: u32,
667 cur_uid: u32,
668 cur_gid: u32,
669 kind: EntryKind,
670 settings: &Settings,
671) -> EntryPlan {
672 let cur_mode = cur_mode & 0o7777;
673 let requested_uid = settings.owner.for_kind(kind);
674 let requested_gid = settings.group.for_kind(kind);
675 let mode_spec = settings.mode.for_kind(kind);
676 let selected = mode_spec.is_some() || requested_uid.is_some() || requested_gid.is_some();
677 let uid_change = requested_uid.filter(|&u| u != cur_uid);
678 let gid_change = requested_gid.filter(|&g| g != cur_gid);
679 let need_chown = uid_change.is_some() || gid_change.is_some();
680 let chown = need_chown.then_some((uid_change, gid_change));
681 let chmod_before_chown = (kind != EntryKind::Symlink
682 && settings.no_setid
683 && need_chown
684 && cur_mode & SETID_BITS != 0)
685 .then_some(cur_mode & !SETID_BITS);
686 let chmod = if kind == EntryKind::Symlink {
687 None
689 } else if let Some(spec) = mode_spec {
690 let requested = apply_mode(cur_mode, spec, kind == EntryKind::Dir);
691 let desired = if settings.no_setid {
692 requested & !SETID_BITS
693 } else {
694 requested
695 };
696 if desired != cur_mode || (need_chown && (settings.no_setid || desired & SETID_BITS != 0)) {
699 Some(desired)
700 } else {
701 None
702 }
703 } else if settings.no_setid && selected && (need_chown || cur_mode & SETID_BITS != 0) {
704 Some(cur_mode & !SETID_BITS)
708 } else if need_chown && cur_mode & SETID_BITS != 0 {
709 Some(cur_mode)
711 } else {
712 None
713 };
714 EntryPlan {
715 chmod_before_chown,
716 chown,
717 chmod,
718 }
719}
720
721fn inc_changed(prog: &Progress, kind: EntryKind) -> Summary {
722 match kind {
723 EntryKind::Dir => {
724 prog.directories_changed.inc();
725 Summary {
726 directories_changed: 1,
727 ..Default::default()
728 }
729 }
730 EntryKind::Symlink => {
731 prog.symlinks_changed.inc();
732 Summary {
733 symlinks_changed: 1,
734 ..Default::default()
735 }
736 }
737 EntryKind::File | EntryKind::Special => {
738 prog.files_changed.inc();
739 Summary {
740 files_changed: 1,
741 ..Default::default()
742 }
743 }
744 }
745}
746
747fn inc_unchanged(prog: &Progress, kind: EntryKind) -> Summary {
748 match kind {
749 EntryKind::Dir => {
750 prog.directories_unchanged.inc();
751 Summary {
752 directories_unchanged: 1,
753 ..Default::default()
754 }
755 }
756 EntryKind::Symlink => {
757 prog.symlinks_unchanged.inc();
758 Summary {
759 symlinks_unchanged: 1,
760 ..Default::default()
761 }
762 }
763 EntryKind::File | EntryKind::Special => {
764 prog.files_unchanged.inc();
765 Summary {
766 files_unchanged: 1,
767 ..Default::default()
768 }
769 }
770 }
771}
772
773fn skipped_summary_for(kind: EntryKind) -> Summary {
774 match kind {
775 EntryKind::Dir => Summary {
776 directories_skipped: 1,
777 ..Default::default()
778 },
779 EntryKind::Symlink => Summary {
780 symlinks_skipped: 1,
781 ..Default::default()
782 },
783 EntryKind::File | EntryKind::Special => Summary {
784 files_skipped: 1,
785 ..Default::default()
786 },
787 }
788}
789
790fn describe_change(cur_mode: u32, cur_uid: u32, cur_gid: u32, plan: &EntryPlan) -> String {
792 let mut parts = Vec::new();
793 if let Some(mode) = plan.chmod {
794 if mode == cur_mode & 0o7777 {
795 parts.push(format!("mode {mode:04o} (re-applied after chown)"));
797 } else {
798 parts.push(format!("mode {:04o}->{:04o}", cur_mode & 0o7777, mode));
799 }
800 }
801 if let Some((uid, gid)) = plan.chown {
802 if let Some(uid) = uid {
803 parts.push(format!("owner {cur_uid}->{uid}"));
804 }
805 if let Some(gid) = gid {
806 parts.push(format!("group {cur_gid}->{gid}"));
807 }
808 }
809 parts.join(", ")
810}
811
812async fn apply_plan(handle: &Handle, plan: &EntryPlan) -> anyhow::Result<()> {
835 if let Some(mode) = plan.chmod_before_chown {
836 safedir::chmod_via_proc_fd(handle, congestion::Side::Destination, mode)
837 .await
838 .with_context(|| {
839 format!("failed to clear set-ID bits via fd before chown (mode {mode:04o})")
840 })?;
841 }
842 if let Some((uid, gid)) = plan.chown {
843 safedir::fchown_handle(handle, congestion::Side::Destination, uid, gid)
844 .await
845 .with_context(|| format!("failed to chown via fd (uid={uid:?}, gid={gid:?})"))?;
846 }
847 if let Some(mode) = plan.chmod {
848 safedir::chmod_via_proc_fd(handle, congestion::Side::Destination, mode)
849 .await
850 .with_context(|| format!("failed to chmod via fd to {mode:04o}"))?;
851 }
852 Ok(())
853}
854
855async fn apply_entry_change(
863 prog: &'static Progress,
864 path: &std::path::Path,
865 handle: &Handle,
866 kind: EntryKind,
867 settings: &Settings,
868) -> Result<Summary, Error> {
869 if let Some(ref time_filter) = settings.time_filter {
870 let metadata =
873 match safedir::stat_meta_via_proc_fd(handle, congestion::Side::Destination).await {
874 Ok(md) => md,
875 Err(err) => {
876 let err = anyhow::Error::new(err).context(format!(
877 "failed reading metadata for time filter on {path:?}"
878 ));
879 if settings.fail_early {
880 return Err(Error::new(err, Default::default()));
881 }
882 tracing::warn!("time filter failed for {:?}, skipping: {:#}", path, &err);
883 kind.inc_skipped(prog);
884 return Ok(skipped_summary_for(kind));
885 }
886 };
887 match time_filter.matches(&metadata) {
888 Ok(result) => {
889 if let Some(reason) = result.as_skip_reason() {
890 if let Some(mode) = settings.dry_run {
891 crate::dry_run::report_time_skip(path, reason, mode, kind.label());
892 }
893 kind.inc_skipped(prog);
894 return Ok(skipped_summary_for(kind));
895 }
896 }
897 Err(err) => {
898 let err = err.context(format!("failed evaluating time filter on {path:?}"));
899 if settings.fail_early {
900 return Err(Error::new(err, Default::default()));
901 }
902 tracing::warn!("time filter failed for {:?}, skipping: {:#}", path, &err);
903 kind.inc_skipped(prog);
904 return Ok(skipped_summary_for(kind));
905 }
906 }
907 }
908 let meta = handle.meta();
909 let cur_mode = mode_of(meta);
910 let plan = compute_plan(cur_mode, meta.uid(), meta.gid(), kind, settings);
911 if plan.is_noop() {
912 if let Some(crate::config::DryRunMode::All) = settings.dry_run {
913 println!("unchanged {} {:?}", kind.label(), path);
914 }
915 return Ok(inc_unchanged(prog, kind));
916 }
917 if settings.dry_run.is_some() {
918 let desc = describe_change(cur_mode, meta.uid(), meta.gid(), &plan);
919 println!("would modify {} {:?}: {}", kind.label(), path, desc);
920 return Ok(inc_changed(prog, kind));
921 }
922 apply_plan(handle, &plan)
923 .await
924 .map_err(|err| Error::new(err, Default::default()))?;
925 Ok(inc_changed(prog, kind))
926}
927
928#[instrument(skip(prog_track, settings))]
938pub async fn chmod(
939 prog_track: &'static Progress,
940 path: &std::path::Path,
941 settings: &Settings,
942) -> Result<Summary, Error> {
943 let permit = crate::walk::ensure_leaf_permit(PermitKind::PendingMeta, None).await;
947 enum ChmodRootSetup {
948 Complete(Summary),
949 Ready {
950 operand: crate::walk::RootOperand,
951 parent: Arc<Dir>,
952 },
953 }
954 let setup =
955 safedir::with_optional_fd_admission(permit.as_ref().map(LeafPermit::admission), async {
956 let operand = crate::walk::split_root_operand(path)
962 .await
963 .map_err(|err| Error::new(err, Default::default()))?;
964 let parent_path = operand.parent.as_path();
965 let name = operand.name.as_os_str();
966 let path = operand.display.as_path();
967 let parent = Dir::open_parent_dir(parent_path, congestion::Side::Destination)
973 .await
974 .with_context(|| format!("cannot open parent directory {parent_path:?}"))
975 .map_err(|err| Error::new(err, Default::default()))?;
976 let parent = Arc::new(parent.into_tree());
978 if let Some(ref filter) = settings.filter {
979 let root_handle = parent
982 .child(name)
983 .await
984 .with_context(|| format!("failed reading metadata from {path:?}"))
985 .map_err(|err| Error::new(err, Default::default()))?;
986 let name_path = std::path::Path::new(name);
987 match filter
988 .should_include_root_item(name_path, root_handle.kind() == EntryKind::Dir)
989 {
990 crate::filter::FilterResult::Included => {}
991 result => {
992 let kind = root_handle.kind();
993 if let Some(mode) = settings.dry_run {
994 crate::dry_run::report_skip(path, &result, mode, kind.label_long());
995 }
996 kind.inc_skipped(prog_track);
997 return Ok(ChmodRootSetup::Complete(skipped_summary_for(kind)));
998 }
999 }
1000 }
1001 Ok(ChmodRootSetup::Ready { operand, parent })
1002 })
1003 .await?;
1004 let (operand, parent) = match setup {
1005 ChmodRootSetup::Complete(summary) => return Ok(summary),
1006 ChmodRootSetup::Ready { operand, parent } => (operand, parent),
1007 };
1008 let name = operand.name.as_os_str();
1009 let path = operand.display.as_path();
1010 run_chmod_root(prog_track, &parent, name, path, settings, permit).await
1011}
1012
1013async fn run_chmod_root(
1017 prog_track: &'static Progress,
1018 parent: &Arc<Dir>,
1019 name: &OsStr,
1020 root: &std::path::Path,
1021 settings: &Settings,
1022 permit: Option<LeafPermit>,
1023) -> Result<Summary, Error> {
1024 let visitor = Arc::new(ChmodVisitor {
1025 prog_track,
1026 settings: settings.clone(),
1027 });
1028 let root_cx = EntryCx::root(
1030 Arc::clone(parent),
1031 name.to_owned(),
1032 root.to_path_buf(),
1033 prog_track,
1034 );
1035 process_entry(visitor, root_cx, (), permit).await }
1037
1038struct ChmodVisitor {
1044 prog_track: &'static Progress,
1045 settings: Settings,
1046}
1047
1048struct ChmodDirState {
1051 handle: Handle,
1054 traversed_only: bool,
1057 base: Summary,
1059 pre_order_error: Option<anyhow::Error>,
1063}
1064
1065impl WalkVisitor for ChmodVisitor {
1066 type Summary = Summary;
1067 type DirContext = ();
1068 type DirState = ChmodDirState;
1069
1070 fn root_dir_context(&self) {}
1071
1072 fn permit_kind(&self) -> PermitKind {
1073 PermitKind::PendingMeta
1076 }
1077
1078 fn fail_early(&self) -> bool {
1079 self.settings.fail_early
1080 }
1081
1082 fn filter(&self) -> Option<&crate::filter::FilterSettings> {
1083 self.settings.filter.as_ref()
1084 }
1085
1086 fn on_skip(
1087 &self,
1088 cx: &SkippedEntry<'_>,
1089 kind: EntryKind,
1090 skip_result: &crate::filter::FilterResult,
1091 ) -> Summary {
1092 cx.report_skip(self.settings.dry_run, skip_result, kind);
1095 skipped_summary_for(kind)
1096 }
1097
1098 async fn visit_leaf(
1099 &self,
1100 cx: &EntryCx,
1101 _parent_ctx: &(),
1102 leaf: AdmittedLeaf,
1103 ) -> Result<Summary, Error> {
1104 apply_entry_change(
1106 self.prog_track,
1107 &cx.real_path,
1108 leaf.handle(),
1109 leaf.kind(),
1110 &self.settings,
1111 )
1112 .await
1113 }
1114
1115 async fn dir_pre(&self, cx: &EntryCx, _parent_ctx: &(), handle: &Handle) -> DirPreResult<Self> {
1116 let path = &cx.real_path;
1117 let traversed_only =
1121 self.settings.filter.as_ref().is_some_and(|f| {
1122 f.has_includes() && !f.directly_matches_include(&cx.rel_path, true)
1123 });
1124 let mut base = Summary::default();
1125 let mut pre_order_error: Option<anyhow::Error> = None;
1126 if !self.settings.defer_dir_changes {
1131 match apply_dir_self(
1132 self.prog_track,
1133 path,
1134 handle,
1135 traversed_only,
1136 &self.settings,
1137 )
1138 .await
1139 {
1140 Ok(dir_summary) => base = base + dir_summary,
1141 Err(error) if self.settings.fail_early => {
1144 return Err(Error::new(error.source, base + error.summary));
1145 }
1146 Err(error) => {
1147 tracing::error!("chmod: {:?} failed with: {:#}", path, &error);
1148 base = base + error.summary;
1149 pre_order_error = Some(error.source);
1150 }
1151 }
1152 }
1153 let dir_handle = handle
1157 .try_clone()
1158 .with_context(|| format!("cannot duplicate directory handle for {path:?}"))
1159 .map_err(|err| Error::new(err, base))?;
1160 match cx.parent.open_dir(&cx.name).await {
1164 Ok(dir) => Ok(DirAction::Descend {
1165 dir: Arc::new(dir),
1166 child_ctx: (),
1167 state: ChmodDirState {
1168 handle: dir_handle,
1169 traversed_only,
1170 base,
1171 pre_order_error,
1172 },
1173 }),
1174 Err(error) => {
1175 let error = anyhow::Error::new(error)
1176 .context(format!("cannot open directory {path:?} for reading"));
1177 if self.settings.fail_early {
1178 return Err(Error::new(error, base));
1179 }
1180 let errors = crate::error_collector::ErrorCollector::default();
1184 if let Some(pre_order_error) = pre_order_error {
1185 errors.push(pre_order_error);
1186 }
1187 tracing::error!("chmod: {:#}", &error);
1188 errors.push(error);
1189 if self.settings.defer_dir_changes {
1190 match apply_dir_self(
1191 self.prog_track,
1192 path,
1193 handle,
1194 traversed_only,
1195 &self.settings,
1196 )
1197 .await
1198 {
1199 Ok(dir_summary) => base = base + dir_summary,
1200 Err(error) => {
1201 tracing::error!("chmod: {:?} failed with: {:#}", path, &error);
1202 base = base + error.summary;
1203 errors.push(error.source);
1204 }
1205 }
1206 }
1207 Err(Error::new(errors.into_error().unwrap(), base))
1209 }
1210 }
1211 }
1212
1213 async fn dir_post(
1214 &self,
1215 cx: &EntryCx,
1216 state: ChmodDirState,
1217 child_result: DirPostInput<Self>,
1218 ) -> Result<Summary, Error> {
1219 let ChmodDirState {
1220 handle,
1221 traversed_only,
1222 base,
1223 pre_order_error,
1224 } = state;
1225 let path = &cx.real_path;
1226 let (child_summary, child_error) = match child_result {
1229 Ok((summary, _)) => (summary, None),
1230 Err(err) => (err.summary, Some(err.source)),
1231 };
1232 let mut summary = base + child_summary;
1233 let errors = crate::error_collector::ErrorCollector::default();
1235 if let Some(pre_order_error) = pre_order_error {
1236 errors.push(pre_order_error);
1237 }
1238 if let Some(child_error) = child_error {
1239 errors.push(child_error);
1240 }
1241 if self.settings.defer_dir_changes {
1247 match apply_dir_self(
1248 self.prog_track,
1249 path,
1250 &handle,
1251 traversed_only,
1252 &self.settings,
1253 )
1254 .await
1255 {
1256 Ok(dir_summary) => summary = summary + dir_summary,
1257 Err(error) => {
1258 if self.settings.fail_early {
1259 return Err(Error::new(error.source, summary + error.summary));
1260 }
1261 tracing::error!("chmod: {:?} failed with: {:#}", path, &error);
1262 summary = summary + error.summary;
1263 errors.push(error.source);
1264 }
1265 }
1266 }
1267 if let Some(error) = errors.into_error() {
1268 return Err(Error::new(error, summary));
1269 }
1270 Ok(summary)
1271 }
1272}
1273
1274async fn apply_dir_self(
1282 prog_track: &'static Progress,
1283 path: &std::path::Path,
1284 handle: &Handle,
1285 traversed_only: bool,
1286 settings: &Settings,
1287) -> Result<Summary, Error> {
1288 if traversed_only {
1289 if let Some(crate::config::DryRunMode::All) = settings.dry_run {
1290 println!("skip dir {path:?} (only traversed for include matches)");
1291 }
1292 prog_track.directories_skipped.inc();
1293 return Ok(skipped_summary_for(EntryKind::Dir));
1294 }
1295 apply_entry_change(prog_track, path, handle, EntryKind::Dir, settings).await
1296}
1297
1298#[cfg(test)]
1299mod tests {
1300 use super::*;
1301 #[test]
1302 fn hint_skip_reporting_only_builds_paths_for_visible_modes() {
1303 use crate::config::DryRunMode;
1304 static PROGRESS: std::sync::LazyLock<Progress> = std::sync::LazyLock::new(Progress::new);
1305 tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
1306 for (dry_run, expected_builds) in [
1307 (None, 0),
1308 (Some(DryRunMode::Brief), 0),
1309 (Some(DryRunMode::All), 1),
1310 (Some(DryRunMode::Explain), 1),
1311 ] {
1312 let visitor = ChmodVisitor {
1313 prog_track: &PROGRESS,
1314 settings: Settings {
1315 mode: ModeProgram::default(),
1316 owner: OwnerProgram::default(),
1317 group: OwnerProgram::default(),
1318 no_setid: false,
1319 fail_early: false,
1320 defer_dir_changes: false,
1321 filter: None,
1322 time_filter: None,
1323 dry_run,
1324 },
1325 };
1326 let skipped =
1327 SkippedEntry::child(Path::new("source//./nested"), OsStr::new("skip.log"));
1328 let before = crate::walk_driver::skipped_path_builds();
1329 let summary = visitor.on_skip(
1330 &skipped,
1331 EntryKind::File,
1332 &crate::filter::FilterResult::ExcludedByDefault,
1333 );
1334 assert_eq!(summary.files_skipped, 1);
1335 assert_eq!(
1336 crate::walk_driver::skipped_path_builds() - before,
1337 expected_builds,
1338 "{dry_run:?}"
1339 );
1340 }
1341 });
1342 }
1343 #[test]
1344 fn mode_token_octal() {
1345 assert_eq!(parse_mode_token("2775").unwrap(), ModeSpec::Octal(0o2775));
1346 assert_eq!(parse_mode_token("0644").unwrap(), ModeSpec::Octal(0o644));
1347 }
1348 #[test]
1349 fn mode_token_octal_out_of_range_errors() {
1350 assert!(parse_mode_token("9999").is_err()); assert!(parse_mode_token("77777").is_err()); }
1353 #[test]
1354 fn mode_token_symbolic_simple() {
1355 let spec = parse_mode_token("g+w").unwrap();
1356 assert_eq!(
1357 spec,
1358 ModeSpec::Symbolic(vec![SymbolicClause {
1359 who: WHO_G,
1360 op: ModeOp::Add,
1361 perms: PERM_W
1362 }])
1363 );
1364 }
1365 #[test]
1366 fn mode_token_symbolic_omitted_who_means_all() {
1367 let spec = parse_mode_token("+x").unwrap();
1368 assert_eq!(
1369 spec,
1370 ModeSpec::Symbolic(vec![SymbolicClause {
1371 who: WHO_A,
1372 op: ModeOp::Add,
1373 perms: PERM_X
1374 }])
1375 );
1376 }
1377 #[test]
1378 fn mode_token_symbolic_comma_chained() {
1379 let spec = parse_mode_token("u+rw,g-w").unwrap();
1380 let ModeSpec::Symbolic(clauses) = spec else {
1381 panic!("expected symbolic")
1382 };
1383 assert_eq!(clauses.len(), 2);
1384 assert_eq!(
1385 clauses[0],
1386 SymbolicClause {
1387 who: WHO_U,
1388 op: ModeOp::Add,
1389 perms: PERM_R | PERM_W
1390 }
1391 );
1392 assert_eq!(
1393 clauses[1],
1394 SymbolicClause {
1395 who: WHO_G,
1396 op: ModeOp::Remove,
1397 perms: PERM_W
1398 }
1399 );
1400 }
1401 #[test]
1402 fn mode_token_symbolic_bigx_and_specials() {
1403 let spec = parse_mode_token("g+rwXs").unwrap();
1404 assert_eq!(
1405 spec,
1406 ModeSpec::Symbolic(vec![SymbolicClause {
1407 who: WHO_G,
1408 op: ModeOp::Add,
1409 perms: PERM_R | PERM_W | PERM_BIGX | PERM_S,
1410 }])
1411 );
1412 }
1413 #[test]
1414 fn mode_token_rejects_garbage() {
1415 assert!(parse_mode_token("q+z").is_err());
1416 assert!(parse_mode_token("g!w").is_err());
1417 assert!(parse_mode_token("").is_err());
1418 }
1419 #[test]
1420 fn summary_add_combines_fields() {
1421 let a = Summary {
1422 files_changed: 1,
1423 directories_changed: 2,
1424 files_unchanged: 3,
1425 ..Default::default()
1426 };
1427 let b = Summary {
1428 files_changed: 10,
1429 symlinks_skipped: 4,
1430 ..Default::default()
1431 };
1432 let sum = a + b;
1433 assert_eq!(sum.files_changed, 11);
1434 assert_eq!(sum.directories_changed, 2);
1435 assert_eq!(sum.files_unchanged, 3);
1436 assert_eq!(sum.symlinks_skipped, 4);
1437 }
1438 #[test]
1439 fn owner_dsl_bare_applies_to_all_types() {
1440 let prog = parse_owner_dsl("0", IdKind::User, &GetentResolver::default()).unwrap();
1441 assert_eq!(prog.file, Some(0));
1442 assert_eq!(prog.dir, Some(0));
1443 assert_eq!(prog.symlink, Some(0));
1444 }
1445 #[test]
1446 fn owner_dsl_per_type_overrides() {
1447 let prog = parse_owner_dsl("f:1 d:2", IdKind::User, &GetentResolver::default()).unwrap();
1448 assert_eq!(prog.file, Some(1));
1449 assert_eq!(prog.dir, Some(2));
1450 assert_eq!(prog.symlink, None);
1451 }
1452 #[test]
1453 fn owner_dsl_bare_plus_override() {
1454 let prog = parse_owner_dsl("5 d:2", IdKind::Group, &GetentResolver::default()).unwrap();
1455 assert_eq!(prog.file, Some(5));
1456 assert_eq!(prog.dir, Some(2));
1457 assert_eq!(prog.symlink, Some(5));
1458 }
1459 #[test]
1460 fn owner_dsl_explicit_before_bare_is_order_independent() {
1461 let prog = parse_owner_dsl("f:1 5", IdKind::User, &GetentResolver::default()).unwrap();
1462 assert_eq!(prog.file, Some(1));
1463 assert_eq!(prog.dir, Some(5));
1464 assert_eq!(prog.symlink, Some(5));
1465 }
1466 #[test]
1467 fn owner_dsl_rejects_multiple_bare() {
1468 assert!(parse_owner_dsl("1 2", IdKind::User, &GetentResolver::default()).is_err());
1469 }
1470 #[test]
1471 fn owner_dsl_rejects_unknown_id() {
1472 assert!(
1473 parse_owner_dsl(
1474 "definitely-no-such-group-xyz",
1475 IdKind::Group,
1476 &GetentResolver::default()
1477 )
1478 .is_err()
1479 );
1480 }
1481 #[test]
1482 fn owner_dsl_resolves_root_name() {
1483 let prog = parse_owner_dsl("root", IdKind::User, &GetentResolver::default()).unwrap();
1485 assert_eq!(prog.file, Some(0));
1486 assert_eq!(prog.dir, Some(0));
1487 assert_eq!(prog.symlink, Some(0));
1488 }
1489 #[test]
1490 fn getent_id_parses_passwd_and_group_lines() {
1491 assert_eq!(
1493 parse_getent_id("alice:x:1234:100:Alice:/home/alice:/bin/sh").unwrap(),
1494 1234
1495 );
1496 assert_eq!(parse_getent_id("data:*:5678:alice,bob").unwrap(), 5678);
1498 }
1499 #[test]
1500 fn getent_id_rejects_malformed_lines() {
1501 assert!(parse_getent_id("").is_err());
1502 assert!(parse_getent_id("alice").is_err());
1503 assert!(parse_getent_id("alice:x").is_err());
1504 assert!(parse_getent_id("alice:x:notanumber:100").is_err());
1505 }
1506 fn write_stub_getent(dir: &std::path::Path, name: &str, body: &str) -> std::path::PathBuf {
1508 use std::os::unix::fs::PermissionsExt;
1509 let path = dir.join(name);
1510 std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
1511 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
1512 path
1513 }
1514 #[test]
1515 fn getent_stub_resolves_directory_service_names() {
1516 let tmp = tempfile::tempdir().unwrap();
1517 let user_stub = write_stub_getent(
1521 tmp.path(),
1522 "getent-user",
1523 "[ \"$1\" = -- ] && [ \"$2\" = passwd ] || exit 99\necho 'ldapuser:*:4242:4242:LDAP User:/home/ldapuser:/bin/sh'",
1524 );
1525 let group_stub = write_stub_getent(
1526 tmp.path(),
1527 "getent-group",
1528 "[ \"$1\" = -- ] && [ \"$2\" = group ] || exit 99\necho 'ldapgroup:*:4343:ldapuser'",
1529 );
1530 assert_eq!(
1531 resolve_via_getent_cmd(user_stub.as_os_str(), "ldapuser", IdKind::User).unwrap(),
1532 4242
1533 );
1534 assert_eq!(
1535 resolve_via_getent_cmd(group_stub.as_os_str(), "ldapgroup", IdKind::Group).unwrap(),
1536 4343
1537 );
1538 }
1539 #[test]
1540 fn getent_stub_not_found_is_unknown() {
1541 let tmp = tempfile::tempdir().unwrap();
1542 let stub = write_stub_getent(tmp.path(), "getent-miss", "exit 2");
1543 let err = resolve_via_getent_cmd(stub.as_os_str(), "nosuch", IdKind::Group).unwrap_err();
1544 assert!(
1545 format!("{err:#}").contains("unknown group: nosuch"),
1546 "got: {err:#}"
1547 );
1548 }
1549 #[test]
1550 fn getent_missing_program_suggests_numeric_id() {
1551 let tmp = tempfile::tempdir().unwrap();
1552 let missing = tmp.path().join("no-such-getent");
1553 let err = resolve_via_getent_cmd(missing.as_os_str(), "alice", IdKind::User).unwrap_err();
1554 assert!(
1555 format!("{err:#}").contains("use a numeric id instead"),
1556 "got: {err:#}"
1557 );
1558 }
1559 #[test]
1560 fn getent_stub_garbled_output_errors() {
1561 let tmp = tempfile::tempdir().unwrap();
1562 let stub = write_stub_getent(tmp.path(), "getent-garbled", "echo 'not a passwd line'");
1563 let err = resolve_via_getent_cmd(stub.as_os_str(), "alice", IdKind::User).unwrap_err();
1564 assert!(
1565 format!("{err:#}").contains("unexpected getent output"),
1566 "got: {err:#}"
1567 );
1568 }
1569 #[test]
1570 fn getent_stub_exit0_no_output_errors() {
1571 let tmp = tempfile::tempdir().unwrap();
1572 let stub = write_stub_getent(tmp.path(), "getent-empty", "exit 0");
1573 let err = resolve_via_getent_cmd(stub.as_os_str(), "alice", IdKind::User).unwrap_err();
1574 assert!(
1575 format!("{err:#}").contains("produced no output"),
1576 "got: {err:#}"
1577 );
1578 }
1579 #[cfg_attr(
1580 rcp_nix_sandbox,
1581 ignore = "Nix sandbox has no getent/NSS lookup service"
1582 )]
1583 #[test]
1584 fn getent_real_resolves_root() {
1585 assert_eq!(
1588 resolve_via_getent("root", IdKind::User, &GetentResolver::default()).unwrap(),
1589 0
1590 );
1591 assert_eq!(
1592 resolve_via_getent("root", IdKind::Group, &GetentResolver::default()).unwrap(),
1593 0
1594 );
1595 }
1596 #[cfg_attr(
1597 rcp_nix_sandbox,
1598 ignore = "Nix sandbox has no getent/NSS lookup service"
1599 )]
1600 #[test]
1601 fn getent_real_option_like_name_fails_closed_no_injection() {
1602 let err = resolve_via_getent("--service=files", IdKind::Group, &GetentResolver::default())
1608 .unwrap_err();
1609 let msg = format!("{err:#}");
1610 assert!(
1611 msg.contains("unknown group") || msg.contains("produced no output"),
1612 "option-like name must fail closed (not resolve to an id), got: {msg}"
1613 );
1614 }
1615 #[test]
1616 fn getent_source_rejects_relative_explicit_path() {
1617 let err = GetentResolver::from_cli(Some(PathBuf::from("getent")), false).unwrap_err();
1619 assert!(
1620 format!("{err:#}").contains("must be an absolute path"),
1621 "got: {err:#}"
1622 );
1623 }
1624 #[test]
1625 fn getent_source_explicit_absolute_used_even_when_privileged() {
1626 let resolver =
1628 GetentResolver::from_cli(Some(PathBuf::from("/opt/nss/getent")), true).unwrap();
1629 assert_eq!(
1630 resolver.program_in(&["/usr/bin"]).unwrap(),
1631 Some(PathBuf::from("/opt/nss/getent"))
1632 );
1633 }
1634 #[test]
1635 fn getent_source_unprivileged_searches_path() {
1636 let resolver = GetentResolver::from_cli(None, false).unwrap();
1638 assert_eq!(resolver.program_in(&["/nonexistent"]).unwrap(), None);
1639 }
1640 #[test]
1641 fn getent_source_privileged_probes_trusted_dirs_not_path() {
1642 let tmp = tempfile::tempdir().unwrap();
1644 let bin = tmp.path().join("getent");
1645 std::fs::write(&bin, "#!/bin/sh\n").unwrap();
1646 let resolver = GetentResolver::from_cli(None, true).unwrap();
1647 let dirs = [tmp.path().to_str().unwrap()];
1648 assert_eq!(resolver.program_in(&dirs).unwrap(), Some(bin));
1649 }
1650 #[test]
1651 fn getent_source_privileged_missing_getent_errors_not_path_fallback() {
1652 let tmp = tempfile::tempdir().unwrap(); let resolver = GetentResolver::from_cli(None, true).unwrap();
1656 let dir = tmp.path().to_str().unwrap();
1657 let err = resolver.program_in(&[dir]).unwrap_err();
1658 let msg = format!("{err:#}");
1659 assert!(
1660 msg.contains("PATH is intentionally ignored"),
1661 "should explain PATH is not consulted, got: {msg}"
1662 );
1663 assert!(
1664 msg.contains(dir),
1665 "should name the searched dir, got: {msg}"
1666 );
1667 }
1668 fn sym(s: &str) -> ModeSpec {
1669 parse_mode_token(s).unwrap()
1670 }
1671 #[test]
1672 fn apply_mode_group_add_remove() {
1673 assert_eq!(apply_mode(0o644, &sym("g+w"), false), 0o664);
1674 assert_eq!(apply_mode(0o664, &sym("g-w"), false), 0o644);
1675 }
1676 #[test]
1677 fn apply_mode_set_clears_other_bits() {
1678 assert_eq!(apply_mode(0o755, &sym("o="), false), 0o750);
1680 assert_eq!(apply_mode(0o000, &sym("u=rwx,go=rx"), false), 0o755);
1682 assert_eq!(apply_mode(0o1755, &sym("o="), false), 0o0750);
1684 }
1685 #[test]
1686 fn apply_mode_conditional_bigx() {
1687 assert_eq!(apply_mode(0o644, &sym("a+X"), false), 0o644);
1689 assert_eq!(apply_mode(0o744, &sym("a+X"), false), 0o755);
1691 assert_eq!(apply_mode(0o644, &sym("a+X"), true), 0o755);
1693 }
1694 #[test]
1695 fn apply_mode_setgid_and_sticky() {
1696 assert_eq!(apply_mode(0o750, &sym("g+rwxs"), true), 0o2770);
1697 assert_eq!(apply_mode(0o755, &sym("+t"), true), 0o1755);
1698 assert_eq!(apply_mode(0o755, &sym("u+s"), false), 0o4755);
1699 }
1700 #[test]
1701 fn apply_mode_sticky_only_responds_to_other() {
1702 assert_eq!(apply_mode(0o755, &sym("u+t"), false), 0o755);
1704 assert_eq!(apply_mode(0o755, &sym("g+t"), false), 0o755);
1705 assert_eq!(apply_mode(0o755, &sym("ug+t"), false), 0o755);
1706 assert_eq!(apply_mode(0o755, &sym("o+t"), false), 0o1755);
1707 assert_eq!(apply_mode(0o755, &sym("+t"), false), 0o1755);
1708 assert_eq!(apply_mode(0o1755, &sym("u-t"), false), 0o1755);
1709 assert_eq!(apply_mode(0o1755, &sym("o-t"), false), 0o755);
1710 }
1711 #[test]
1712 fn apply_mode_octal_is_absolute() {
1713 assert_eq!(apply_mode(0o4755, &sym("644"), false), 0o644);
1714 assert_eq!(apply_mode(0o000, &sym("2775"), true), 0o2775);
1715 }
1716 #[test]
1717 fn mode_dsl_bare_applies_to_file_and_dir_not_symlink() {
1718 let prog = parse_mode_dsl("g+rwX").unwrap();
1719 assert!(prog.file.is_some());
1720 assert!(prog.dir.is_some());
1721 assert!(prog.for_kind(EntryKind::Symlink).is_none());
1723 }
1724 #[test]
1725 fn mode_dsl_per_type() {
1726 let prog = parse_mode_dsl("f:g+rw d:g+rwxs").unwrap();
1727 assert_eq!(prog.file, Some(sym("g+rw")));
1728 assert_eq!(prog.dir, Some(sym("g+rwxs")));
1729 }
1730 #[test]
1731 fn mode_dsl_bare_plus_override() {
1732 let prog = parse_mode_dsl("g+r d:g+rwx").unwrap();
1733 assert_eq!(prog.file, Some(sym("g+r")));
1734 assert_eq!(prog.dir, Some(sym("g+rwx")));
1735 }
1736 #[test]
1737 fn mode_dsl_rejects_symlink_section() {
1738 assert!(parse_mode_dsl("l:g+w").is_err());
1739 }
1740 #[test]
1741 fn mode_dsl_rejects_multiple_bare() {
1742 assert!(parse_mode_dsl("g+r o+w").is_err());
1743 }
1744 #[test]
1745 fn mode_dsl_rejects_unknown_prefix() {
1746 assert!(parse_mode_dsl("z:644").is_err());
1747 }
1748 #[test]
1749 fn mode_dsl_single_type_leaves_other_none() {
1750 let prog_f = parse_mode_dsl("f:644").unwrap();
1751 assert!(prog_f.file.is_some());
1752 assert!(prog_f.dir.is_none());
1753 let prog_d = parse_mode_dsl("d:755").unwrap();
1754 assert!(prog_d.dir.is_some());
1755 assert!(prog_d.file.is_none());
1756 }
1757 fn settings_with(mode: &str, owner: Option<&str>, group: Option<&str>) -> Settings {
1758 Settings {
1759 mode: if mode.is_empty() {
1760 ModeProgram::default()
1761 } else {
1762 parse_mode_dsl(mode).unwrap()
1763 },
1764 owner: owner
1765 .map(|s| parse_owner_dsl(s, IdKind::User, &GetentResolver::default()).unwrap())
1766 .unwrap_or_default(),
1767 group: group
1768 .map(|s| parse_owner_dsl(s, IdKind::Group, &GetentResolver::default()).unwrap())
1769 .unwrap_or_default(),
1770 no_setid: false,
1771 fail_early: false,
1772 defer_dir_changes: false,
1773 filter: None,
1774 time_filter: None,
1775 dry_run: None,
1776 }
1777 }
1778 fn settings_with_no_setid(mode: &str, owner: Option<&str>, group: Option<&str>) -> Settings {
1779 let mut settings = settings_with(mode, owner, group);
1780 settings.no_setid = true;
1781 settings
1782 }
1783 #[test]
1784 fn plan_noop_when_already_correct() {
1785 let s = settings_with("g+r", None, None);
1786 let plan = compute_plan(0o644, 1000, 1000, EntryKind::File, &s);
1788 assert!(plan.is_noop());
1789 }
1790 #[test]
1791 fn plan_chmod_when_mode_differs() {
1792 let s = settings_with("g+w", None, None);
1793 let plan = compute_plan(0o644, 1000, 1000, EntryKind::File, &s);
1794 assert_eq!(plan.chmod, Some(0o664));
1795 assert!(plan.chown.is_none());
1796 }
1797 #[test]
1798 fn plan_chown_only_changed_ids() {
1799 let s = settings_with("", None, Some("2000"));
1800 let plan = compute_plan(0o644, 1000, 1000, EntryKind::File, &s);
1801 assert_eq!(plan.chown, Some((None, Some(2000))));
1803 assert!(plan.chmod.is_none());
1804 }
1805 #[test]
1806 fn plan_preserves_setgid_across_chgrp() {
1807 let s = settings_with("", None, Some("2000"));
1810 let plan = compute_plan(0o2755, 1000, 1000, EntryKind::File, &s);
1811 assert_eq!(plan.chown, Some((None, Some(2000))));
1812 assert_eq!(plan.chmod, Some(0o2755));
1813 }
1814 #[test]
1815 fn plan_symlink_never_chmods_but_chowns() {
1816 let s = settings_with("g+w", None, Some("2000"));
1817 let plan = compute_plan(0o777, 1000, 1000, EntryKind::Symlink, &s);
1818 assert!(plan.chmod.is_none());
1819 assert_eq!(plan.chown, Some((None, Some(2000))));
1820 }
1821 #[test]
1822 fn plan_preserves_setuid_when_mode_rule_noop_but_chown_runs() {
1823 let s = settings_with("g+r", Some("2000"), None);
1826 let plan = compute_plan(0o4755, 1000, 1000, EntryKind::File, &s);
1827 assert_eq!(plan.chown, Some((Some(2000), None)));
1828 assert_eq!(plan.chmod, Some(0o4755));
1829 }
1830 #[test]
1831 fn plan_preserves_setgid_dir_across_chgrp() {
1832 let s = settings_with("", None, Some("2000"));
1834 let plan = compute_plan(0o2770, 1000, 1000, EntryKind::Dir, &s);
1835 assert_eq!(plan.chown, Some((None, Some(2000))));
1836 assert_eq!(plan.chmod, Some(0o2770));
1837 }
1838 #[test]
1839 fn no_setid_drops_symbolic_setuid_request() {
1840 let s = settings_with_no_setid("u+s", None, None);
1841 let plan = compute_plan(0o755, 1000, 1000, EntryKind::File, &s);
1842 assert!(plan.is_noop());
1843 }
1844 #[test]
1845 fn no_setid_masks_octal_setid_bits() {
1846 let s = settings_with_no_setid("6755", None, None);
1847 let plan = compute_plan(0o644, 1000, 1000, EntryKind::File, &s);
1848 assert_eq!(plan.chmod, Some(0o755));
1849 }
1850 #[test]
1851 fn no_setid_clears_inherited_bits_on_unrelated_mode_change() {
1852 let s = settings_with_no_setid("g+w", None, None);
1853 let plan = compute_plan(0o6755, 1000, 1000, EntryKind::File, &s);
1854 assert_eq!(plan.chmod, Some(0o775));
1855 }
1856 #[test]
1857 fn no_setid_clears_bits_before_and_after_ownership_change() {
1858 let s = settings_with_no_setid("", Some("2000"), None);
1859 let plan = compute_plan(0o4755, 1000, 1000, EntryKind::File, &s);
1860 assert_eq!(plan.chmod_before_chown, Some(0o755));
1861 assert_eq!(plan.chown, Some((Some(2000), None)));
1862 assert_eq!(plan.chmod, Some(0o755));
1863 }
1864 #[test]
1865 fn no_setid_reapplies_mask_after_chown_without_snapshot_bits() {
1866 let s = settings_with_no_setid("", Some("2000"), None);
1867 let plan = compute_plan(0o755, 1000, 1000, EntryKind::File, &s);
1868 assert!(plan.chmod_before_chown.is_none());
1869 assert_eq!(plan.chown, Some((Some(2000), None)));
1870 assert_eq!(plan.chmod, Some(0o755));
1871 }
1872 #[test]
1873 fn no_setid_clears_bits_when_selected_owner_is_unchanged() {
1874 let s = settings_with_no_setid("", Some("1000"), None);
1875 let plan = compute_plan(0o4755, 1000, 1000, EntryKind::File, &s);
1876 assert!(plan.chmod_before_chown.is_none());
1877 assert!(plan.chown.is_none());
1878 assert_eq!(plan.chmod, Some(0o755));
1879 }
1880 #[test]
1881 fn no_setid_retains_sticky_bit_on_setgid_directory() {
1882 let s = settings_with_no_setid("", None, Some("2000"));
1883 let plan = compute_plan(0o3775, 1000, 1000, EntryKind::Dir, &s);
1884 assert_eq!(plan.chmod_before_chown, Some(0o1775));
1885 assert_eq!(plan.chown, Some((None, Some(2000))));
1886 assert_eq!(plan.chmod, Some(0o1775));
1887 }
1888 #[test]
1889 fn no_setid_never_chmods_symlink() {
1890 let s = settings_with_no_setid("", None, Some("2000"));
1891 let plan = compute_plan(0o6777, 1000, 1000, EntryKind::Symlink, &s);
1892 assert!(plan.chmod_before_chown.is_none());
1893 assert_eq!(plan.chown, Some((None, Some(2000))));
1894 assert!(plan.chmod.is_none());
1895 }
1896
1897 static RACE_PROGRESS: std::sync::LazyLock<Progress> = std::sync::LazyLock::new(Progress::new);
1898
1899 fn spawn_file_symlink_swapper(
1905 dir: std::path::PathBuf,
1906 entry_name: &'static str,
1907 sentinel: std::path::PathBuf,
1908 stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
1909 ) -> std::thread::JoinHandle<()> {
1910 use std::os::unix::fs::PermissionsExt;
1911 std::thread::spawn(move || {
1912 let entry = dir.join(entry_name);
1913 let staged_real = dir.join("__staged_real");
1914 let staged_link = dir.join("__staged_link");
1915 while !stop.load(std::sync::atomic::Ordering::Relaxed) {
1916 let _ = std::fs::remove_file(&staged_real);
1918 if std::fs::write(&staged_real, b"REAL").is_err() {
1919 continue;
1920 }
1921 let _ =
1922 std::fs::set_permissions(&staged_real, std::fs::Permissions::from_mode(0o644));
1923 let _ = std::fs::rename(&staged_real, &entry);
1924 let _ = std::fs::remove_file(&staged_link);
1926 let _ = std::os::unix::fs::symlink(&sentinel, &staged_link);
1927 let _ = std::fs::rename(&staged_link, &entry);
1928 }
1929 })
1930 }
1931
1932 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1940 async fn entry_symlink_swap_never_changes_sentinel_mode() -> anyhow::Result<()> {
1941 use std::os::unix::fs::PermissionsExt;
1942 let tmp = crate::testutils::create_temp_dir().await?;
1943 let root = tmp.as_path();
1944 let sentinel = root.join("sentinel_secret");
1946 tokio::fs::write(&sentinel, b"SENTINEL").await?;
1947 std::fs::set_permissions(&sentinel, std::fs::Permissions::from_mode(0o600))?;
1948 let sentinel_uid_before =
1949 std::os::unix::fs::MetadataExt::uid(&std::fs::symlink_metadata(&sentinel)?);
1950 let target_dir = root.join("tree");
1952 tokio::fs::create_dir(&target_dir).await?;
1953 let entry_path = target_dir.join("entry");
1954 tokio::fs::write(&entry_path, b"REAL").await?;
1955 std::fs::set_permissions(&entry_path, std::fs::Permissions::from_mode(0o644))?;
1956
1957 let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1958 let swapper =
1959 spawn_file_symlink_swapper(target_dir.clone(), "entry", sentinel.clone(), stop.clone());
1960
1961 let settings = settings_with("g+w", None, None);
1963 let mut caught = 0usize;
1964 let mut changed_real = 0usize;
1965 for i in 0..300 {
1966 let result = tokio::time::timeout(
1967 std::time::Duration::from_secs(30),
1968 chmod(&RACE_PROGRESS, &target_dir, &settings),
1969 )
1970 .await
1971 .expect("rchm must not hang under concurrent swapping");
1972 match result {
1973 Ok(summary) => changed_real += summary.files_changed,
1974 Err(_) => caught += 1, }
1976 let sentinel_md = std::fs::symlink_metadata(&sentinel)?;
1979 assert_eq!(
1980 sentinel_md.permissions().mode() & 0o7777,
1981 0o600,
1982 "iteration {i}: sentinel mode changed — rchm followed the symlink to chmod it"
1983 );
1984 assert_eq!(
1985 std::os::unix::fs::MetadataExt::uid(&sentinel_md),
1986 sentinel_uid_before,
1987 "iteration {i}: sentinel owner changed — rchm followed the symlink to chown it"
1988 );
1989 }
1990
1991 stop.store(true, std::sync::atomic::Ordering::Relaxed);
1992 swapper.join().expect("swapper thread panicked");
1993 tracing::info!("entry swap: caught={caught}, changed_real={changed_real}");
1995 assert!(
1996 caught + changed_real > 0,
1997 "expected at least one observable outcome across the iterations"
1998 );
1999 Ok(())
2000 }
2001
2002 mod max_files_in_flight_tests {
2005 use super::*;
2006 use crate::walk_driver::process_entry;
2007
2008 static PROGRESS: std::sync::LazyLock<Progress> = std::sync::LazyLock::new(Progress::new);
2009
2010 #[tokio::test]
2014 async fn filtered_root_waits_for_admission_before_setup() -> anyhow::Result<()> {
2015 let root = crate::testutils::create_temp_dir().await?;
2016 let path = root.join("victim");
2017 tokio::fs::write(&path, b"x").await?;
2018 let mut settings = settings_with("f:600", None, None);
2019 let mut filter = crate::filter::FilterSettings::new();
2020 filter.add_exclude("victim")?;
2021 settings.filter = Some(filter);
2022 let admission = crate::testutils::AdmissionLimit::new().await;
2023 admission.set_files_in_flight(1);
2024 let stat_resource =
2025 throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Stat);
2026 admission.set_max_ops_in_flight(stat_resource, 1);
2027 let held_stat = throttle::ops_in_flight_permit(stat_resource).await;
2028 let operation = chmod(&PROGRESS, &path, &settings);
2029 tokio::pin!(operation);
2030 let stopped_at_stat_gate = futures::poll!(operation.as_mut()).is_pending();
2031 let mut second_permit = Box::pin(throttle::pending_meta_permit());
2032 let setup_bypassed_admission = futures::poll!(second_permit.as_mut()).is_ready();
2033 drop(second_permit);
2034 drop(held_stat);
2035 let result = admission
2036 .run_with_timeout(std::time::Duration::from_secs(20), operation.as_mut())
2037 .await;
2038 assert!(
2039 stopped_at_stat_gate,
2040 "chmod root did not reach the held stat gate"
2041 );
2042 let summary =
2043 result.context("chmod root did not resume after stat capacity was released")??;
2044 assert!(
2045 !setup_bypassed_admission,
2046 "chmod performed root setup before pending-metadata admission"
2047 );
2048 assert_eq!(summary.files_skipped, 1);
2049 Ok(())
2050 }
2051
2052 #[tokio::test]
2066 async fn hinted_leaf_that_is_dir_drops_permit_before_recursion() -> anyhow::Result<()> {
2067 let root = crate::testutils::create_temp_dir().await?;
2068 let dir_path = root.join("d");
2070 tokio::fs::create_dir(&dir_path).await?;
2071 let child_path = dir_path.join("c");
2072 tokio::fs::write(&child_path, b"x").await?;
2073 std::fs::set_permissions(&child_path, std::fs::Permissions::from_mode(0o644))?;
2074 let admission = crate::testutils::AdmissionLimit::new().await;
2077 admission.set_files_in_flight(1);
2078 let parent = Dir::open_parent_dir(&root, congestion::Side::Destination)
2080 .await
2081 .context("open parent dir")?;
2082 let parent = Arc::new(parent.into_tree());
2083 let name = std::ffi::OsStr::new("d");
2084 let handle = parent.child(name).await.context("classify d")?;
2085 assert_eq!(
2086 handle.kind(),
2087 EntryKind::Dir,
2088 "fixture `d` must be a directory"
2089 );
2090 drop(handle);
2091 let visitor = Arc::new(ChmodVisitor {
2095 prog_track: &PROGRESS,
2096 settings: settings_with("g+w", None, None),
2097 });
2098 let cx = EntryCx::root(
2099 Arc::clone(&parent),
2100 name.to_owned(),
2101 dir_path.clone(),
2102 &PROGRESS,
2103 );
2104 let permit =
2105 crate::walk::preacquire_leaf_permit(PermitKind::PendingMeta, Some(EntryKind::File))
2106 .await;
2107 assert!(permit.is_some(), "the pre-acquire must take the one permit");
2108 let result = admission
2109 .run_with_timeout(
2110 std::time::Duration::from_secs(20),
2111 process_entry(visitor, cx, (), permit),
2112 )
2113 .await;
2114 let summary = result
2115 .context(
2116 "process_entry hung — leaf permit held across directory recursion (deadlock)",
2117 )?
2118 .map_err(|e| e.source)
2119 .context("process_entry failed")?;
2120 assert_eq!(
2122 summary.files_changed, 1,
2123 "child file should have its mode changed"
2124 );
2125 assert_eq!(
2126 summary.directories_changed, 1,
2127 "directory should have its mode changed"
2128 );
2129 assert_eq!(
2130 std::fs::symlink_metadata(&child_path)?.permissions().mode() & 0o777,
2131 0o664,
2132 "child file mode should be g+w applied"
2133 );
2134 Ok(())
2135 }
2136 }
2137}