Debian Codegraph @

tests/by-util/test_chmod.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (words) dirfd subdirs openat FDCWD rwxr
7
8 use std::fs::{OpenOptions, Permissions, metadata, set_permissions};
9 use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
10 use uutests::at_and_ucmd;
11 use uutests::util::{AtPath, TestScenario, UCommand};
12
13 use uutests::new_ucmd;
14 use uutests::util_name;
15
16 static TEST_FILE: &str = "file";
17 static REFERENCE_FILE: &str = "reference";
18 static REFERENCE_PERMS: u32 = 0o247;
19
20 struct TestCase {
21 args: Vec<&'static str>,
22 before: u32,
23 after: u32,
24 umask: Option<libc::mode_t>,
25 }
26
27 fn make_file(file: &str, mode: u32) {
28 OpenOptions::new()
29 .mode(mode)
30 .create(true)
31 .write(true)
32 .open(file)
33 .unwrap();
34 let mut perms = metadata(file).unwrap().permissions();
35 perms.set_mode(mode);
36 set_permissions(file, perms).unwrap();
37 }
38
39 fn run_single_test(test: &TestCase, at: &AtPath, mut ucmd: UCommand) {
40 make_file(&at.plus_as_string(TEST_FILE), test.before);
41 let perms = at.metadata(TEST_FILE).permissions().mode();
42
43 assert_eq!(
44 perms, test.before,
45 "{}: expected: {:o} got: {perms:o}",
46 "setting permissions on test files before actual test run failed", test.after
47 );
48
49 for arg in &test.args {
50 ucmd.arg(arg);
51 if let Some(umask) = test.umask {
52 ucmd.umask(umask);
53 }
54 }
55 let r = ucmd.run();
56 if !r.succeeded() {
57 println!("{}", r.stderr_str());
58 panic!("{ucmd}: failed");
59 }
60
61 let perms = at.metadata(TEST_FILE).permissions().mode();
62 assert_eq!(
63 perms, test.after,
64 "{ucmd}: expected: {:o} got: {perms:o}",
65 test.after
66 );
67 }
68
69 fn run_tests(tests: Vec<TestCase>) {
70 for test in tests {
71 let (at, ucmd) = at_and_ucmd!();
72 run_single_test(&test, &at, ucmd);
73 }
74 }
75
76 #[test]
77 #[allow(clippy::unreadable_literal)]
78 fn test_chmod_octal() {
79 let tests = vec![
80 TestCase {
81 args: vec!["0700", TEST_FILE],
82 before: 0o100000,
83 after: 0o100700,
84 umask: None,
85 },
86 TestCase {
87 args: vec!["0070", TEST_FILE],
88 before: 0o100000,
89 after: 0o100070,
90 umask: None,
91 },
92 TestCase {
93 args: vec!["0007", TEST_FILE],
94 before: 0o100000,
95 after: 0o100007,
96 umask: None,
97 },
98 TestCase {
99 args: vec!["-0700", TEST_FILE],
100 before: 0o100700,
101 after: 0o100000,
102 umask: None,
103 },
104 TestCase {
105 args: vec!["-0070", TEST_FILE],
106 before: 0o100060,
107 after: 0o100000,
108 umask: None,
109 },
110 TestCase {
111 args: vec!["-0007", TEST_FILE],
112 before: 0o100001,
113 after: 0o100000,
114 umask: None,
115 },
116 TestCase {
117 args: vec!["+0100", TEST_FILE],
118 before: 0o100600,
119 after: 0o100700,
120 umask: None,
121 },
122 TestCase {
123 args: vec!["+0020", TEST_FILE],
124 before: 0o100050,
125 after: 0o100070,
126 umask: None,
127 },
128 TestCase {
129 args: vec!["+0004", TEST_FILE],
130 before: 0o100003,
131 after: 0o100007,
132 umask: None,
133 },
134 ];
135 run_tests(tests);
136 }
137
138 #[test]
139 #[allow(clippy::unreadable_literal)]
140 #[allow(clippy::too_many_lines)]
141 // spell-checker:disable-next-line
142 fn test_chmod_ugoa() {
143 let tests = vec![
144 TestCase {
145 args: vec!["u=rwx", TEST_FILE],
146 before: 0o100000,
147 after: 0o100700,
148 umask: Some(0),
149 },
150 TestCase {
151 args: vec!["g=rwx", TEST_FILE],
152 before: 0o100000,
153 after: 0o100070,
154 umask: Some(0),
155 },
156 TestCase {
157 args: vec!["o=rwx", TEST_FILE],
158 before: 0o100000,
159 after: 0o100007,
160 umask: Some(0),
161 },
162 TestCase {
163 args: vec!["a=rwx", TEST_FILE],
164 before: 0o100000,
165 after: 0o100777,
166 umask: Some(0),
167 },
168 TestCase {
169 args: vec!["-r", TEST_FILE],
170 before: 0o100777,
171 after: 0o100333,
172 umask: Some(0),
173 },
174 TestCase {
175 args: vec!["-w", TEST_FILE],
176 before: 0o100777,
177 after: 0o100555,
178 umask: Some(0),
179 },
180 TestCase {
181 args: vec!["-x", TEST_FILE],
182 before: 0o100777,
183 after: 0o100666,
184 umask: Some(0),
185 },
186 ];
187 run_tests(tests);
188
189 let tests = vec![
190 TestCase {
191 args: vec!["u=rwx", TEST_FILE],
192 before: 0o100000,
193 after: 0o100700,
194 umask: Some(0o022),
195 },
196 TestCase {
197 args: vec!["g=rwx", TEST_FILE],
198 before: 0o100000,
199 after: 0o100070,
200 umask: Some(0o022),
201 },
202 TestCase {
203 args: vec!["o=rwx", TEST_FILE],
204 before: 0o100000,
205 after: 0o100007,
206 umask: Some(0o022),
207 },
208 TestCase {
209 args: vec!["a=rwx", TEST_FILE],
210 before: 0o100000,
211 after: 0o100777,
212 umask: Some(0o022),
213 },
214 TestCase {
215 args: vec!["+rw", TEST_FILE],
216 before: 0o100000,
217 after: 0o100644,
218 umask: Some(0o022),
219 },
220 TestCase {
221 args: vec!["=rwx", TEST_FILE],
222 before: 0o100000,
223 after: 0o100755,
224 umask: Some(0o022),
225 },
226 TestCase {
227 args: vec!["-x", TEST_FILE],
228 before: 0o100777,
229 after: 0o100666,
230 umask: Some(0o022),
231 },
232 ];
233 run_tests(tests);
234 }
235
236 #[test]
237 #[cfg(unix)]
238 #[allow(clippy::cast_lossless)]
239 fn test_chmod_umask_expected() {
240 // Get the actual system umask
241 let system_umask = {
242 use rustix::process::umask;
243 let mask = umask(rustix::fs::Mode::empty());
244 umask(mask);
245 mask
246 };
247
248 // Now verify that get_umask() returns the same value
249 let current_umask = uucore::mode::get_umask();
250 assert_eq!(
251 current_umask,
252 system_umask.bits() as u32,
253 "get_umask() returned {current_umask:03o}, but system umask is {system_umask:03o}",
254 );
255 }
256
257 fn get_expected_symlink_permissions() -> u32 {
258 #[cfg(any(target_os = "linux", target_os = "android"))]
259 {
260 0o120_777
261 }
262 #[cfg(not(any(target_os = "linux", target_os = "android")))]
263 {
264 0o120_755
265 }
266 }
267
268 #[test]
269 fn test_chmod_error_permissions() {
270 // check that we print an error if umask prevents us from removing a permission
271 let (at, mut ucmd) = at_and_ucmd!();
272
273 at.touch("file");
274 set_permissions(at.plus("file"), Permissions::from_mode(0o777)).unwrap();
275
276 ucmd.args(&["-w", "file"])
277 .umask(0o022)
278 .fails_with_code(1)
279 .stderr_is(
280 // spell-checker:disable-next-line
281 "chmod: file: new permissions are r-xrwxrwx, not r-xr-xr-x\n",
282 );
283 assert_eq!(
284 metadata(at.plus("file")).unwrap().permissions().mode(),
285 0o100_577
286 );
287 }
288
289 #[test]
290 fn test_chmod_permissions_too_large() {
291 let scenario = TestScenario::new(util_name!());
292 let at = &scenario.fixtures;
293
294 at.touch("file");
295
296 scenario
297 .ucmd()
298 .args(&["10777", "file"])
299 .fails_with_code(1)
300 .stderr_is(
301 // spell-checker:disable-next-line
302 "chmod: mode is too large (10777 > 7777)\n",
303 );
304 // test around the boundary of the acceptable octal mode
305 scenario
306 .ucmd()
307 .args(&["10000", "file"])
308 .fails_with_code(1)
309 .stderr_is(
310 // spell-checker:disable-next-line
311 "chmod: mode is too large (10000 > 7777)\n",
312 );
313 at.mkdir("dir");
314 scenario.ucmd().args(&["7777", "dir"]).succeeds();
315 }
316
317 #[test]
318 #[allow(clippy::unreadable_literal)]
319 fn test_chmod_ugo_copy() {
320 let tests = vec![
321 TestCase {
322 args: vec!["u=g", TEST_FILE],
323 before: 0o100070,
324 after: 0o100770,
325 umask: None,
326 },
327 TestCase {
328 args: vec!["g=o", TEST_FILE],
329 before: 0o100005,
330 after: 0o100055,
331 umask: None,
332 },
333 TestCase {
334 args: vec!["o=u", TEST_FILE],
335 before: 0o100200,
336 after: 0o100202,
337 umask: None,
338 },
339 TestCase {
340 args: vec!["u-g", TEST_FILE],
341 before: 0o100710,
342 after: 0o100610,
343 umask: None,
344 },
345 TestCase {
346 args: vec!["u+g", TEST_FILE],
347 before: 0o100250,
348 after: 0o100750,
349 umask: None,
350 },
351 ];
352 run_tests(tests);
353 }
354
355 #[test]
356 #[allow(clippy::unreadable_literal)]
357 fn test_chmod_many_options() {
358 let tests = vec![TestCase {
359 args: vec!["-r,a+w", TEST_FILE],
360 before: 0o100444,
361 after: 0o100222,
362 umask: Some(0),
363 }];
364 run_tests(tests);
365 }
366
367 #[test]
368 #[allow(clippy::unreadable_literal)]
369 fn test_chmod_reference_file() {
370 let tests = [
371 TestCase {
372 args: vec!["--reference", REFERENCE_FILE, TEST_FILE],
373 before: 0o100070,
374 after: 0o100247,
375 umask: None,
376 },
377 TestCase {
378 args: vec!["a-w", "--reference", REFERENCE_FILE, TEST_FILE],
379 before: 0o100070,
380 after: 0o100247,
381 umask: None,
382 },
383 ];
384 let (at, ucmd) = at_and_ucmd!();
385 make_file(&at.plus_as_string(REFERENCE_FILE), REFERENCE_PERMS);
386 run_single_test(&tests[0], &at, ucmd);
387 }
388
389 #[test]
390 fn test_permission_denied() {
391 let scene = TestScenario::new(util_name!());
392 let at = &scene.fixtures;
393
394 at.mkdir("d/");
395 at.mkdir("d/no-x");
396 at.mkdir("d/no-x/y");
397
398 scene.ucmd().arg("u=rw").arg("d/no-x").succeeds();
399
400 scene
401 .ucmd()
402 .arg("-R")
403 .arg("o=r")
404 .arg("d")
405 .fails()
406 .stderr_is("chmod: cannot access 'd/no-x/y': Permission denied\n");
407 }
408
409 #[test]
410 fn test_chmod_inaccessible_file_reports_permission_denied() {
411 // Non-recursive chmod of a file whose metadata cannot be read because its
412 // parent directory lacks search permission must report "Permission denied",
413 // not "No such file or directory" (issue #9789). `Path::exists()` collapses
414 // the permission error into `false`, so the fix relies on `try_exists()`.
415 let scene = TestScenario::new(util_name!());
416 let at = &scene.fixtures;
417
418 at.mkdir("locked");
419 make_file(&at.plus_as_string("locked/file"), 0o100_644);
420 set_permissions(at.plus_as_string("locked"), Permissions::from_mode(0o000)).unwrap();
421
422 scene
423 .ucmd()
424 .arg("644")
425 .arg("locked/file")
426 .fails()
427 .stderr_is("chmod: cannot access 'locked/file': Permission denied\n");
428
429 // Restore search permission so the fixture directory can be cleaned up.
430 set_permissions(at.plus_as_string("locked"), Permissions::from_mode(0o755)).unwrap();
431 }
432
433 #[test]
434 #[allow(clippy::unreadable_literal)]
435 fn test_chmod_recursive_correct_exit_code() {
436 let (at, mut ucmd) = at_and_ucmd!();
437
438 // create 3 folders to test on
439 at.mkdir("a");
440 at.mkdir("a/b");
441 at.mkdir("z");
442
443 // remove read permissions for folder a so the chmod command for a/b fails
444 let mut perms = at.metadata("a").permissions();
445 perms.set_mode(0o000);
446 set_permissions(at.plus_as_string("a"), perms).unwrap();
447
448 // With safe_traversal enabled on all Unix platforms (except Redox),
449 // we get detailed error messages that include the file path
450 #[cfg(all(unix, not(target_os = "redox")))]
451 let err_msg = "chmod: cannot access 'a': Permission denied\n";
452 #[cfg(not(all(unix, not(target_os = "redox"))))]
453 let err_msg = "chmod: Permission denied\n";
454
455 // order of command is a, a/b then c
456 // command is expected to fail and not just take the last exit code
457 ucmd.arg("-R")
458 .arg("--verbose")
459 .arg("a+w")
460 .arg("a")
461 .arg("z")
462 .umask(0)
463 .fails()
464 .stderr_is(err_msg);
465 }
466
467 #[test]
468 fn test_chmod_hyper_recursive_directory_tree_does_not_fail() {
469 let (at, mut ucmd) = at_and_ucmd!();
470 let mkdir = "a/".repeat(400);
471
472 at.mkdir_all(&mkdir);
473
474 ucmd.arg("-R").arg("777").arg("a").succeeds();
475 }
476
477 #[test]
478 #[allow(clippy::unreadable_literal)]
479 fn test_chmod_recursive() {
480 let (at, mut ucmd) = at_and_ucmd!();
481 at.mkdir("a");
482 at.mkdir("a/b");
483 at.mkdir("a/b/c");
484 at.mkdir("z");
485
486 // create expected permissions by removing read bits and write bits to the current perms
487 let a_perms_expected = (at.metadata("a").permissions().mode() & !0o444) | 0o222;
488 let z_perms_expected = (at.metadata("z").permissions().mode() & !0o444) | 0o222;
489
490 make_file(&at.plus_as_string("a/a"), 0o100444);
491 make_file(&at.plus_as_string("a/b/b"), 0o100444);
492 make_file(&at.plus_as_string("a/b/c/c"), 0o100444);
493 make_file(&at.plus_as_string("z/y"), 0o100444);
494 // With safe_traversal enabled on all Unix platforms, the error message
495 // now includes the file path consistently across platforms
496 let err_msg = "chmod: cannot access 'z': Permission denied\n";
497
498 // only the permissions of folder `a` and `z` are changed
499 // folder can't be read after read permission is removed
500 ucmd.arg("-R")
501 .arg("--verbose")
502 .arg("-r,a+w")
503 .arg("a")
504 .arg("z")
505 .umask(0)
506 .fails()
507 .stderr_is(err_msg);
508
509 assert_eq!(at.metadata("z/y").permissions().mode(), 0o100444);
510 assert_eq!(at.metadata("a/a").permissions().mode(), 0o100444);
511 assert_eq!(at.metadata("a/b/b").permissions().mode(), 0o100444);
512 assert_eq!(at.metadata("a/b/c/c").permissions().mode(), 0o100444);
513 println!("mode {:o}", at.metadata("a").permissions().mode());
514 assert_eq!(at.metadata("a").permissions().mode(), a_perms_expected);
515 assert_eq!(at.metadata("z").permissions().mode(), z_perms_expected);
516 }
517
518 #[test]
519 #[allow(clippy::unreadable_literal)]
520 fn test_chmod_recursive_read_permission() {
521 let (at, mut ucmd) = at_and_ucmd!();
522 at.mkdir("a");
523 at.mkdir("a/b");
524 let mut perms = at.metadata("a/b").permissions();
525 perms.set_mode(0o311);
526 set_permissions(at.plus_as_string("a/b"), perms.clone()).unwrap();
527 set_permissions(at.plus_as_string("a"), perms).unwrap();
528
529 ucmd.arg("-R").arg("u+r").arg("a").succeeds();
530
531 assert_eq!(at.metadata("a").permissions().mode(), 0o40711);
532 assert_eq!(at.metadata("a/b").permissions().mode(), 0o40711);
533 }
534
535 #[test]
536 fn test_chmod_non_existing_file() {
537 new_ucmd!()
538 .arg("-R")
539 .arg("-r,a+w")
540 .arg("does-not-exist")
541 .fails()
542 .stderr_contains("cannot access 'does-not-exist': No such file or directory");
543 }
544
545 #[test]
546 fn test_chmod_non_existing_file_silent() {
547 new_ucmd!()
548 .arg("-R")
549 .arg("--quiet")
550 .arg("-r,a+w")
551 .arg("does-not-exist")
552 .fails_with_code(1)
553 .no_stderr();
554 }
555
556 #[test]
557 fn test_chmod_preserve_root() {
558 new_ucmd!()
559 .arg("-R")
560 .arg("--preserve-root")
561 .arg("755")
562 .arg("/")
563 .fails_with_code(1)
564 .stderr_contains("chmod: it is dangerous to operate recursively on '/'");
565 }
566
567 #[test]
568 fn test_chmod_preserve_root_with_paths_that_resolve_to_root() {
569 // Only a bare "/" is reported as such; any other spelling of the root
570 // directory is named as the user wrote it, followed by "(same as '/')".
571 // "//" also checks we compare the raw operand, since Path("//") == Path("/").
572 new_ucmd!()
573 .arg("-R")
574 .arg("--preserve-root")
575 .arg("755")
576 .arg("//")
577 .fails_with_code(1)
578 .stderr_contains("chmod: it is dangerous to operate recursively on '//' (same as '/')");
579 }
580
581 #[test]
582 fn test_chmod_preserve_root_symlink_during_recursion() {
583 // The failsafe must be re-checked during the descent, not only for the
584 // operands: with -L, a symlink met inside the tree that resolves to '/'
585 // would otherwise be recursed into.
586 let (at, mut ucmd) = at_and_ucmd!();
587 at.mkdir("tree");
588 at.symlink_dir("/", "tree/link");
589
590 ucmd.arg("-R")
591 .arg("-L")
592 .arg("--preserve-root")
593 .arg("755")
594 .arg("tree")
595 .fails_with_code(1)
596 .stderr_contains(
597 "chmod: it is dangerous to operate recursively on 'tree/link' (same as '/')",
598 );
599 }
600
601 #[test]
602 fn test_chmod_recursive_reference_does_not_follow_inner_symlink() {
603 // A symlink met inside the tree during `chmod -R` must not have its referent
604 // touched: chmod(2) follows the link, and the target can live outside the
605 // tree. GNU never follows such a link, and the --reference path has to behave
606 // like the symbolic/numeric path, which already skips it.
607 let (at, mut ucmd) = at_and_ucmd!();
608
609 // A file that lives outside the tree being modified.
610 at.touch("outside_target");
611 at.set_mode("outside_target", 0o600);
612
613 // The reference file carries a distinctive mode.
614 at.touch("ref");
615 at.set_mode("ref", 0o745);
616
617 // The tree holds a symlink pointing at the outside file.
618 at.mkdir("tree");
619 at.symlink_file("outside_target", "tree/link");
620
621 ucmd.arg("-R").arg("--reference=ref").arg("tree").succeeds();
622
623 // The referent outside the tree keeps its mode, while the walked directory
624 // still picks up the reference mode.
625 assert_eq!(
626 at.metadata("outside_target").permissions().mode() & 0o7777,
627 0o600
628 );
629 assert_eq!(at.metadata("tree").permissions().mode() & 0o7777, 0o745);
630 }
631
632 #[test]
633 fn test_chmod_recursive_symlink_option_like_mode() {
634 // A symlink met inside the tree during `chmod -R` must be left alone.
635 // When using an option-like mode (e.g. `-w`), umask sensitivity checks
636 // must not trigger for symlinks inside the tree.
637 let (at, mut ucmd) = at_and_ucmd!();
638
639 at.mkdir_all("d/sub");
640 at.set_mode("d", 0o755);
641 at.set_mode("d/sub", 0o755);
642 at.touch("d/sub/target");
643 at.set_mode("d/sub/target", 0o644);
644 // Verbatim reproducer from Launchpad #2167122: ln -s target d/sub/link
645 at.relative_symlink_file("target", "d/sub/link");
646
647 ucmd.umask(0o022).arg("-R").arg("-w").arg("d").succeeds();
648
649 assert_eq!(at.metadata("d").permissions().mode() & 0o7777, 0o555);
650 assert_eq!(at.metadata("d/sub").permissions().mode() & 0o7777, 0o555);
651 assert_eq!(
652 at.metadata("d/sub/target").permissions().mode() & 0o7777,
653 0o444
654 );
655 }
656
657 #[test]
658 fn test_chmod_symlink_non_existing_file() {
659 let scene = TestScenario::new(util_name!());
660 let at = &scene.fixtures;
661
662 let non_existing = "test_chmod_symlink_non_existing_file";
663 let test_symlink = "test_chmod_symlink_non_existing_file_symlink";
664 let expected_stdout = &format!(
665 "failed to change mode of '{test_symlink}' from 0000 (---------) to 1500 (r-x-----T)"
666 );
667 let expected_stderr = &format!("cannot operate on dangling symlink '{test_symlink}'");
668
669 at.symlink_file(non_existing, test_symlink);
670
671 // this cannot succeed since the symbolic link dangles
672 scene
673 .ucmd()
674 .arg("755")
675 .arg("-v")
676 .arg(test_symlink)
677 .fails_with_code(1)
678 .stdout_contains(expected_stdout)
679 .stderr_contains(expected_stderr);
680
681 // this should be the same than with just '-v' but without stderr
682 scene
683 .ucmd()
684 .arg("755")
685 .arg("-v")
686 .arg("-f")
687 .arg(test_symlink)
688 .fails_with_code(1)
689 .no_stderr()
690 .stdout_contains(expected_stdout);
691
692 // this should only include the dangling symlink message
693 // NOT the failure to change mode
694 scene
695 .ucmd()
696 .arg("755")
697 .arg(test_symlink)
698 .fails_with_code(1)
699 .no_stdout()
700 .stderr_contains(expected_stderr);
701 }
702
703 #[test]
704 fn test_chmod_symlink_non_existing_file_recursive() {
705 let scene = TestScenario::new(util_name!());
706 let at = &scene.fixtures;
707
708 let non_existing = "test_chmod_symlink_non_existing_file_recursive";
709 let test_symlink = "test_chmod_symlink_non_existing_file_recursive_symlink";
710 let test_directory = "test_chmod_symlink_non_existing_file_directory";
711
712 at.mkdir(test_directory);
713 at.symlink_file(non_existing, &format!("{test_directory}/{test_symlink}"));
714
715 // this should succeed
716 scene
717 .ucmd()
718 .arg("-R")
719 .arg("755")
720 .arg(test_directory)
721 .succeeds()
722 .no_output();
723
724 let expected_stdout = &format!(
725 // spell-checker:disable-next-line
726 "mode of '{test_directory}' retained as 0755 (rwxr-xr-x)"
727 );
728
729 // '-v': this should succeed without stderr
730 scene
731 .ucmd()
732 .arg("-R")
733 .arg("-v")
734 .arg("755")
735 .arg(test_directory)
736 .succeeds()
737 .stdout_contains(expected_stdout)
738 .no_stderr();
739
740 // '-vf': this should be the same than with just '-v'
741 scene
742 .ucmd()
743 .arg("-R")
744 .arg("-v")
745 .arg("-f")
746 .arg("755")
747 .arg(test_directory)
748 .succeeds()
749 .stdout_contains(expected_stdout)
750 .no_stderr();
751 }
752
753 #[test]
754 fn test_chmod_keep_setgid() {
755 for (from, arg, to) in [
756 (0o7777, "777", 0o46777),
757 (0o7777, "=777", 0o40777),
758 (0o7777, "0777", 0o46777),
759 (0o7777, "=0777", 0o40777),
760 (0o7777, "00777", 0o40777),
761 (0o2444, "a+wx", 0o42777),
762 (0o2444, "a=wx", 0o42333),
763 (0o1444, "g+s", 0o43444),
764 (0o4444, "u-s", 0o40444),
765 (0o7444, "a-s", 0o41444),
766 ] {
767 let (at, mut ucmd) = at_and_ucmd!();
768 at.mkdir("dir");
769 set_permissions(at.plus("dir"), Permissions::from_mode(from)).unwrap();
770 let r = ucmd.arg(arg).arg("dir").succeeds();
771 println!("{}", r.stderr_str());
772 assert_eq!(at.metadata("dir").permissions().mode(), to);
773 }
774 }
775
776 #[test]
777 fn test_no_operands() {
778 new_ucmd!()
779 .arg("777")
780 .fails_with_code(1)
781 .usage_error("missing operand");
782 }
783
784 #[test]
785 fn test_invalid_arg() {
786 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
787 }
788
789 #[test]
790 #[cfg(not(target_os = "android"))]
791 fn test_mode_after_dash_dash() {
792 let (at, ucmd) = at_and_ucmd!();
793 run_single_test(
794 &TestCase {
795 args: vec!["--", "-r", TEST_FILE],
796 before: 0o100_777,
797 after: 0o100_333,
798 umask: None,
799 },
800 &at,
801 ucmd,
802 );
803 }
804
805 #[test]
806 fn test_chmod_file_after_non_existing_file() {
807 let scene = TestScenario::new(util_name!());
808 let at = &scene.fixtures;
809 at.touch(TEST_FILE);
810 at.touch("file2");
811 set_permissions(at.plus(TEST_FILE), Permissions::from_mode(0o664)).unwrap();
812 set_permissions(at.plus("file2"), Permissions::from_mode(0o664)).unwrap();
813 scene
814 .ucmd()
815 .arg("u+x")
816 .arg("does-not-exist")
817 .arg(TEST_FILE)
818 .fails_with_code(1)
819 .stderr_contains("chmod: cannot access 'does-not-exist': No such file or directory");
820
821 assert_eq!(at.metadata(TEST_FILE).permissions().mode(), 0o100_764);
822
823 scene
824 .ucmd()
825 .arg("u+x")
826 .arg("--q")
827 .arg("does-not-exist")
828 .arg("file2")
829 .fails_with_code(1)
830 .no_stderr();
831 assert_eq!(at.metadata("file2").permissions().mode(), 0o100_764);
832 }
833
834 #[test]
835 fn test_chmod_file_symlink_after_non_existing_file() {
836 let scene = TestScenario::new(util_name!());
837 let at = &scene.fixtures;
838 let existing = "file";
839 let test_existing_symlink = "file_symlink";
840
841 let non_existing = "test_chmod_symlink_non_existing_file";
842 let test_dangling_symlink = "test_chmod_symlink_non_existing_file_symlink";
843 let expected_stdout = &format!(
844 "failed to change mode of '{test_dangling_symlink}' from 0000 (---------) to 1500 (r-x-----T)"
845 );
846 let expected_stderr = &format!("cannot operate on dangling symlink '{test_dangling_symlink}'");
847
848 at.touch(existing);
849 set_permissions(at.plus(existing), Permissions::from_mode(0o664)).unwrap();
850 at.symlink_file(non_existing, test_dangling_symlink);
851 at.symlink_file(existing, test_existing_symlink);
852
853 // this cannot succeed since the symbolic link dangles
854 // but the metadata for the existing target should change
855 scene
856 .ucmd()
857 .arg("u+x")
858 .arg("-v")
859 .arg(test_dangling_symlink)
860 .arg(test_existing_symlink)
861 .fails_with_code(1)
862 .stdout_contains(expected_stdout)
863 .stderr_contains(expected_stderr);
864 assert_eq!(
865 at.metadata(test_existing_symlink).permissions().mode(),
866 0o100_764,
867 "Expected mode: {:o}, but got: {:o}",
868 0o100_764,
869 at.metadata(test_existing_symlink).permissions().mode()
870 );
871 }
872
873 #[test]
874 fn test_quiet_n_verbose_used_multiple_times() {
875 let scene = TestScenario::new(util_name!());
876 let at = &scene.fixtures;
877 at.touch("file");
878 scene
879 .ucmd()
880 .arg("u+x")
881 .arg("--verbose")
882 .arg("--verbose")
883 .arg("file")
884 .succeeds();
885 scene
886 .ucmd()
887 .arg("u+x")
888 .arg("--quiet")
889 .arg("--quiet")
890 .arg("file")
891 .succeeds();
892 }
893
894 #[test]
895 fn test_changes_from_identical_reference() {
896 let scene = TestScenario::new(util_name!());
897 let at = &scene.fixtures;
898 at.touch("file");
899 scene
900 .ucmd()
901 .arg("-c")
902 .arg("--reference=file")
903 .arg("file")
904 .succeeds()
905 .no_stdout();
906 }
907
908 #[test]
909 fn test_gnu_invalid_mode() {
910 let scene = TestScenario::new(util_name!());
911 let at = &scene.fixtures;
912 at.touch("file");
913 scene.ucmd().arg("u+gr").arg("file").fails();
914 }
915
916 #[test]
917 #[cfg(not(target_os = "android"))]
918 fn test_gnu_options() {
919 let scene = TestScenario::new(util_name!());
920 let at = &scene.fixtures;
921 at.touch("file");
922 scene.ucmd().arg("-w").arg("file").succeeds();
923 scene.ucmd().arg("file").arg("-w").succeeds();
924 scene.ucmd().arg("-w").arg("--").arg("file").succeeds();
925 }
926
927 #[test]
928 fn test_gnu_repeating_options() {
929 let scene = TestScenario::new(util_name!());
930 let at = &scene.fixtures;
931 at.touch("file");
932 scene.ucmd().arg("-w").arg("-w").arg("file").succeeds();
933 scene
934 .ucmd()
935 .arg("-w")
936 .arg("-w")
937 .arg("-w")
938 .arg("file")
939 .succeeds();
940 }
941
942 #[test]
943 fn test_gnu_special_filenames() {
944 let scene = TestScenario::new(util_name!());
945 let at = &scene.fixtures;
946 let perms_before = Permissions::from_mode(0o100_640);
947 let perms_after = Permissions::from_mode(0o100_440);
948
949 make_file(&at.plus_as_string("--"), perms_before.mode());
950 scene.ucmd().arg("-w").arg("--").arg("--").succeeds();
951 assert_eq!(at.metadata("--").permissions(), perms_after);
952 set_permissions(at.plus("--"), perms_before.clone()).unwrap();
953 scene.ucmd().arg("--").arg("-w").arg("--").succeeds();
954 assert_eq!(at.metadata("--").permissions(), perms_after);
955 at.remove("--");
956
957 make_file(&at.plus_as_string("-w"), perms_before.mode());
958 scene.ucmd().arg("-w").arg("--").arg("-w").succeeds();
959 assert_eq!(at.metadata("-w").permissions(), perms_after);
960 set_permissions(at.plus("-w"), perms_before).unwrap();
961 scene.ucmd().arg("--").arg("-w").arg("-w").succeeds();
962 assert_eq!(at.metadata("-w").permissions(), perms_after);
963 }
964
965 #[test]
966 fn test_gnu_special_options() {
967 let scene = TestScenario::new(util_name!());
968 let at = &scene.fixtures;
969 at.touch("file");
970 scene.ucmd().arg("--").arg("--").arg("file").succeeds();
971 scene.ucmd().arg("--").arg("--").fails();
972 }
973
974 /// Every row of the operand matrix from
975 /// <https://github.com/uutils/coreutils/issues/3147>.
976 ///
977 /// The left column is the argument list, the right column is the exact list of operands, in order,
978 /// that must end up being changed. Three files named `f`, `--` and `-w` exist in every case, so a
979 /// row that expects `[]` is asserting that the arguments are rejected outright rather than being
980 /// resolved to some file that happens to exist. None of the rows are redundant: they only differ
981 /// pairwise in where a `--` sits, which is precisely what decides whether a leading-hyphen argument
982 /// is a mode or a file name.
983 #[test]
984 #[cfg(not(target_os = "android"))]
985 fn test_gnu_usage_matrix() {
986 let matrix: &[(&[&str], &[&str])] = &[
987 (&["--"], &[]),
988 (&["--", "--"], &[]),
989 (&["--", "--", "--", "f"], &["--", "f"]),
990 (&["--", "--", "-w", "f"], &["-w", "f"]),
991 (&["--", "--", "f"], &["f"]),
992 (&["--", "-w"], &[]),
993 (&["--", "-w", "--", "f"], &["--", "f"]),
994 (&["--", "-w", "-w", "f"], &["-w", "f"]),
995 (&["--", "-w", "f"], &["f"]),
996 (&["--", "f"], &[]),
997 (&["-w"], &[]),
998 (&["-w", "--"], &[]),
999 (&["-w", "--", "--", "f"], &["--", "f"]),
1000 (&["-w", "--", "-w", "f"], &["-w", "f"]),
1001 (&["-w", "--", "f"], &["f"]),
1002 (&["-w", "-w"], &[]),
1003 (&["-w", "-w", "--", "f"], &["f"]),
1004 (&["-w", "-w", "-w", "f"], &["f"]),
1005 (&["-w", "-w", "f"], &["f"]),
1006 (&["-w", "f"], &["f"]),
1007 (&["f"], &[]),
1008 (&["f", "--"], &[]),
1009 (&["f", "-w"], &["f"]),
1010 (&["f", "f"], &[]),
1011 (&["u+gr", "f"], &[]),
1012 (&["ug,+x", "f"], &[]),
1013 ];
1014
1015 for (args, expected) in matrix {
1016 let scene = TestScenario::new(util_name!());
1017 let at = &scene.fixtures;
1018 // 0o644 has no group or other write bit, so `-w` lands on 0o444 under any umask. This test
1019 // is about which operands get picked, not about umask arithmetic.
1020 for name in ["f", "--", "-w"] {
1021 make_file(&at.plus_as_string(name), 0o644);
1022 }
1023
1024 let result = scene.ucmd().arg("-v").args(args).run();
1025 let context = format!("chmod -v {}", args.join(" "));
1026
1027 // `-v` names every operand it visits, whether or not the mode ends up changing anything.
1028 let visited: Vec<&str> = result
1029 .stdout_str()
1030 .lines()
1031 .filter_map(|line| line.strip_prefix("mode of '"))
1032 .filter_map(|rest| rest.split('\'').next())
1033 .collect();
1034 assert_eq!(visited, *expected, "{context}: acted on the wrong operands");
1035
1036 // A row that names no operand is an error (a missing or invalid mode), never a silent
1037 // no-op.
1038 assert_eq!(
1039 result.succeeded(),
1040 !expected.is_empty(),
1041 "{context}: unexpected exit status"
1042 );
1043
1044 // Independently of `-v`, nothing outside the expected list may be touched. This is what
1045 // catches an implementation that mistakes the file named `--` for a separator.
1046 for name in ["f", "--", "-w"] {
1047 if !expected.contains(&name) {
1048 assert_eq!(
1049 at.metadata(name).permissions().mode() & 0o7777,
1050 0o644,
1051 "{context}: {name} should have been left alone"
1052 );
1053 }
1054 }
1055 }
1056 }
1057
1058 /// `chmod` warns that the umask kept bits the mode asked to remove only when the mode was written
1059 /// in the option-like form, i.e. as a leading-hyphen argument before any `--`. Once `--` has been
1060 /// seen the operand is unambiguously a mode, and the change is applied silently.
1061 #[test]
1062 #[cfg(not(target_os = "android"))]
1063 fn test_umask_conflict_reported_only_for_option_like_mode() {
1064 // (arguments, resulting permission bits, whether the umask conflict is reported)
1065 let cases: &[(&[&str], u32, bool)] = &[
1066 (&["-w", "file"], 0o466, true),
1067 // A `--` after the mode does not retroactively make it an ordinary operand.
1068 (&["-w", "--", "file"], 0o466, true),
1069 (&["file", "-w"], 0o466, true),
1070 (&["-w", "-w", "--", "file"], 0o466, true),
1071 (&["--", "-w", "file"], 0o466, false),
1072 (&["--", "-rw", "file"], 0o022, false),
1073 // What matters is whether the argument itself began with a hyphen, not whether the mode
1074 // contains an umask-relative clause: these two modes do the same thing, and only the one
1075 // that looks like an option is reported.
1076 (&["u+x,-w", "file"], 0o566, false),
1077 (&["-w,u+x", "file"], 0o566, true),
1078 (&["--", "-w,u+x", "file"], 0o566, false),
1079 ];
1080
1081 for (args, expected_mode, reported) in cases {
1082 let scene = TestScenario::new(util_name!());
1083 let at = &scene.fixtures;
1084 // 0o666 is required: on 0o644 the umask has nothing left to keep, so the conflict never
1085 // arises and every one of these cases would pass vacuously.
1086 make_file(&at.plus_as_string("file"), 0o666);
1087
1088 let result = scene.ucmd().umask(0o022).args(args).run();
1089 let context = format!("chmod {}", args.join(" "));
1090
1091 assert_eq!(
1092 at.metadata("file").permissions().mode() & 0o7777,
1093 *expected_mode,
1094 "{context}: wrong resulting permissions"
1095 );
1096 if *reported {
1097 result.code_is(1);
1098 assert!(
1099 result.stderr_str().contains("new permissions are"),
1100 "{context}: expected the umask conflict to be reported, got {:?}",
1101 result.stderr_str()
1102 );
1103 } else {
1104 result.success().no_stderr();
1105 }
1106 }
1107 }
1108
1109 #[test]
1110 fn test_chmod_dereference_symlink() {
1111 let scene = TestScenario::new(util_name!());
1112 let at = &scene.fixtures;
1113
1114 let target = "file";
1115 let symlink = "symlink";
1116
1117 at.touch(target);
1118 set_permissions(at.plus(target), Permissions::from_mode(0o664)).unwrap();
1119 at.symlink_file(target, symlink);
1120
1121 // Use --dereference: should modify the target file's permissions
1122 scene
1123 .ucmd()
1124 .arg("--dereference")
1125 .arg("u+x")
1126 .arg(symlink)
1127 .succeeds()
1128 .no_stderr();
1129 assert_eq!(at.metadata(target).permissions().mode(), 0o100_764);
1130 assert_eq!(
1131 at.symlink_metadata(symlink).permissions().mode(),
1132 get_expected_symlink_permissions()
1133 );
1134 }
1135
1136 #[test]
1137 fn test_chmod_no_dereference_symlink() {
1138 let scene = TestScenario::new(util_name!());
1139 let at = &scene.fixtures;
1140
1141 let target = "file";
1142 let symlink = "symlink";
1143
1144 at.touch(target);
1145 set_permissions(at.plus(target), Permissions::from_mode(0o664)).unwrap();
1146 at.symlink_file(target, symlink);
1147
1148 scene
1149 .ucmd()
1150 .arg("--no-dereference")
1151 .arg("u+x")
1152 .arg(symlink)
1153 .succeeds()
1154 .no_stderr();
1155 assert_eq!(at.metadata(target).permissions().mode(), 0o100_664);
1156 assert_eq!(
1157 at.symlink_metadata(symlink).permissions().mode(),
1158 get_expected_symlink_permissions()
1159 );
1160 }
1161
1162 #[test]
1163 fn test_chmod_symlink_to_dangling_target_dereference() {
1164 let scene = TestScenario::new(util_name!());
1165 let at = &scene.fixtures;
1166
1167 let dangling_target = "nonexistent_file";
1168 let symlink = "symlink";
1169
1170 at.symlink_file(dangling_target, symlink);
1171
1172 // Use --dereference: should fail due to dangling symlink
1173 scene
1174 .ucmd()
1175 .arg("--dereference")
1176 .arg("u+x")
1177 .arg(symlink)
1178 .fails()
1179 .stderr_contains(format!("cannot operate on dangling symlink '{symlink}'"));
1180 }
1181
1182 #[test]
1183 fn test_chmod_symlink_target_no_dereference() {
1184 let scene = TestScenario::new(util_name!());
1185 let at = &scene.fixtures;
1186
1187 let file = "a";
1188 let symlink = "symlink";
1189 at.touch(file);
1190 at.symlink_file(file, symlink);
1191 set_permissions(at.plus(file), Permissions::from_mode(0o644)).unwrap();
1192
1193 scene
1194 .ucmd()
1195 .arg("--no-dereference")
1196 .arg("755")
1197 .arg(symlink)
1198 .succeeds()
1199 .no_stderr();
1200 assert_eq!(
1201 at.symlink_metadata(file).permissions().mode(),
1202 0o100_644,
1203 "Expected symlink permissions: {:o}, but got: {:o}",
1204 0o100_644,
1205 at.symlink_metadata(file).permissions().mode()
1206 );
1207 }
1208
1209 #[test]
1210 fn test_chmod_symlink_recursive_final_traversal_flag() {
1211 let scene = TestScenario::new(util_name!());
1212 let at = &scene.fixtures;
1213
1214 let dangling_target = "nonexistent_file";
1215 let symlink = "symlink";
1216
1217 at.symlink_file(dangling_target, symlink);
1218
1219 scene
1220 .ucmd()
1221 .arg("755")
1222 .arg("-R")
1223 .arg("-H")
1224 .arg("-L")
1225 .arg("-H")
1226 .arg("-L")
1227 .arg("-P")
1228 .arg(symlink)
1229 .succeeds()
1230 .no_output();
1231 assert_eq!(
1232 at.symlink_metadata(symlink).permissions().mode(),
1233 get_expected_symlink_permissions(),
1234 "Expected symlink permissions: {:o}, but got: {:o}",
1235 get_expected_symlink_permissions(),
1236 at.symlink_metadata(symlink).permissions().mode()
1237 );
1238 }
1239
1240 #[test]
1241 fn test_chmod_symlink_to_dangling_recursive_no_traverse() {
1242 let scene = TestScenario::new(util_name!());
1243 let at = &scene.fixtures;
1244
1245 let dangling_target = "nonexistent_file";
1246 let symlink = "symlink";
1247
1248 at.symlink_file(dangling_target, symlink);
1249
1250 scene
1251 .ucmd()
1252 .arg("755")
1253 .arg("-R")
1254 .arg("-P")
1255 .arg(symlink)
1256 .succeeds()
1257 .no_output();
1258 assert_eq!(
1259 at.symlink_metadata(symlink).permissions().mode(),
1260 get_expected_symlink_permissions(),
1261 "Expected symlink permissions: {:o}, but got: {:o}",
1262 get_expected_symlink_permissions(),
1263 at.symlink_metadata(symlink).permissions().mode()
1264 );
1265 }
1266
1267 #[test]
1268 fn test_chmod_dangling_symlink_recursive_combos() {
1269 let error_scenarios = [vec!["-R"], vec!["-R", "-H"], vec!["-R", "-L"]];
1270
1271 for flags in error_scenarios {
1272 let scene = TestScenario::new(util_name!());
1273 let at = &scene.fixtures;
1274
1275 let dangling_target = "nonexistent_file";
1276 let symlink = "symlink";
1277
1278 at.symlink_file(dangling_target, symlink);
1279
1280 let mut ucmd = scene.ucmd();
1281 ucmd.args(&flags)
1282 .arg("u+x")
1283 .umask(0o022)
1284 .arg(symlink)
1285 .fails()
1286 .stderr_is("chmod: cannot operate on dangling symlink 'symlink'\n");
1287 assert_eq!(
1288 at.symlink_metadata(symlink).permissions().mode(),
1289 get_expected_symlink_permissions(),
1290 "Expected symlink permissions: {:o}, but got: {:o}",
1291 get_expected_symlink_permissions(),
1292 at.symlink_metadata(symlink).permissions().mode()
1293 );
1294 }
1295 }
1296
1297 #[test]
1298 fn test_chmod_traverse_symlink_combo() {
1299 let scenarios = [
1300 (
1301 vec!["-R"], // Should default to "-H"
1302 0o100_664,
1303 get_expected_symlink_permissions(),
1304 ),
1305 (
1306 vec!["-R", "-H"],
1307 0o100_664,
1308 get_expected_symlink_permissions(),
1309 ),
1310 (
1311 vec!["-R", "-L"],
1312 0o100_764,
1313 get_expected_symlink_permissions(),
1314 ),
1315 (
1316 vec!["-R", "-P"],
1317 0o100_664,
1318 get_expected_symlink_permissions(),
1319 ),
1320 ];
1321
1322 for (flags, expected_target_perms, expected_symlink_perms) in scenarios {
1323 let scene = TestScenario::new(util_name!());
1324 let at = &scene.fixtures;
1325
1326 let directory = "dir";
1327 let target = "file";
1328 let symlink = "symlink";
1329
1330 at.mkdir(directory);
1331 at.touch(target);
1332 at.symlink_file(target, &format!("{directory}/{symlink}"));
1333
1334 set_permissions(at.plus(target), Permissions::from_mode(0o664)).unwrap();
1335
1336 let mut ucmd = scene.ucmd();
1337 ucmd.args(&flags)
1338 .arg("u+x")
1339 .umask(0o022)
1340 .arg(directory)
1341 .succeeds()
1342 .no_stderr();
1343
1344 let actual_target = at.metadata(target).permissions().mode();
1345 assert_eq!(
1346 actual_target, expected_target_perms,
1347 "For flags {flags:?}, expected target perms = {expected_target_perms:o}, got = {actual_target:o}",
1348 );
1349
1350 let actual_symlink = at
1351 .symlink_metadata(&format!("{directory}/{symlink}"))
1352 .permissions()
1353 .mode();
1354 assert_eq!(
1355 actual_symlink, expected_symlink_perms,
1356 "For flags {flags:?}, expected symlink perms = {expected_symlink_perms:o}, got = {actual_symlink:o}",
1357 );
1358 }
1359 }
1360
1361 #[test]
1362 fn test_chmod_recursive_symlink_to_directory_command_line() {
1363 // Test behavior when the symlink itself is a command-line argument
1364 let scenarios = [
1365 (vec!["-R"], true), // Default behavior (-H): follow symlinks that are command line args
1366 (vec!["-R", "-H"], true), // Explicit -H: follow symlinks that are command line args
1367 (vec!["-R", "-L"], true), // -L: follow all symlinks
1368 (vec!["-R", "-P"], false), // -P: never follow symlinks
1369 ];
1370
1371 for (flags, should_follow_symlink_dir) in scenarios {
1372 let scene = TestScenario::new(util_name!());
1373 let at = &scene.fixtures;
1374
1375 let target_dir = "target_dir";
1376 let symlink_to_dir = "link_dir";
1377 let file_in_target = "file_in_target";
1378
1379 at.mkdir(target_dir);
1380 at.touch(format!("{target_dir}/{file_in_target}"));
1381 at.symlink_dir(target_dir, symlink_to_dir);
1382
1383 set_permissions(
1384 at.plus(format!("{target_dir}/{file_in_target}")),
1385 Permissions::from_mode(0o644),
1386 )
1387 .unwrap();
1388
1389 let mut ucmd = scene.ucmd();
1390 ucmd.args(&flags)
1391 .arg("go-rwx")
1392 .arg(symlink_to_dir) // The symlink itself is the command-line argument
1393 .succeeds()
1394 .no_stderr();
1395
1396 let actual_file_perms = at
1397 .metadata(&format!("{target_dir}/{file_in_target}"))
1398 .permissions()
1399 .mode();
1400
1401 if should_follow_symlink_dir {
1402 // When following symlinks, the file inside the target directory should have its permissions changed
1403 assert_eq!(
1404 actual_file_perms, 0o100_600,
1405 "For flags {flags:?}, expected file perms when following symlinks = 600, got = {actual_file_perms:o}",
1406 );
1407 } else {
1408 // When not following symlinks, the file inside the target directory should be unchanged
1409 assert_eq!(
1410 actual_file_perms, 0o100_644,
1411 "For flags {flags:?}, expected file perms when not following symlinks = 644, got = {actual_file_perms:o}",
1412 );
1413 }
1414 }
1415 }
1416
1417 #[test]
1418 fn test_chmod_recursive_symlink_during_traversal() {
1419 // Test behavior when symlinks are encountered during directory traversal
1420 let scenarios = [
1421 (vec!["-R"], false), // Default behavior (-H): don't follow symlinks encountered during traversal
1422 (vec!["-R", "-H"], false), // Explicit -H: don't follow symlinks encountered during traversal
1423 (vec!["-R", "-L"], true), // -L: follow all symlinks including those found during traversal
1424 (vec!["-R", "-P"], false), // -P: never follow symlinks
1425 ];
1426
1427 for (flags, should_follow_symlink_dir) in scenarios {
1428 let scene = TestScenario::new(util_name!());
1429 let at = &scene.fixtures;
1430
1431 let directory = "dir";
1432 let target_dir = "target_dir";
1433 let symlink_to_dir = "link_dir";
1434 let file_in_target = "file_in_target";
1435
1436 at.mkdir(directory);
1437 at.mkdir(target_dir);
1438 at.touch(format!("{target_dir}/{file_in_target}"));
1439 at.symlink_dir(target_dir, &format!("{directory}/{symlink_to_dir}"));
1440
1441 set_permissions(
1442 at.plus(format!("{target_dir}/{file_in_target}")),
1443 Permissions::from_mode(0o644),
1444 )
1445 .unwrap();
1446
1447 let mut ucmd = scene.ucmd();
1448 ucmd.args(&flags)
1449 .arg("go-rwx")
1450 .arg(directory) // The directory is the command-line argument
1451 .succeeds()
1452 .no_stderr();
1453
1454 let actual_file_perms = at
1455 .metadata(&format!("{target_dir}/{file_in_target}"))
1456 .permissions()
1457 .mode();
1458
1459 if should_follow_symlink_dir {
1460 // When following symlinks, the file inside the target directory should have its permissions changed
1461 assert_eq!(
1462 actual_file_perms, 0o100_600,
1463 "For flags {flags:?}, expected file perms when following symlinks = 600, got = {actual_file_perms:o}",
1464 );
1465 } else {
1466 // When not following symlinks, the file inside the target directory should be unchanged
1467 assert_eq!(
1468 actual_file_perms, 0o100_644,
1469 "For flags {flags:?}, expected file perms when not following symlinks = 644, got = {actual_file_perms:o}",
1470 );
1471 }
1472 }
1473 }
1474
1475 #[test]
1476 fn test_chmod_recursive_symlink_combinations() {
1477 let scene = TestScenario::new(util_name!());
1478 let at = &scene.fixtures;
1479
1480 let directory = "dir";
1481 let target_dir = "target_dir";
1482 let target_file = "target_file";
1483 let symlink_to_dir = "link_dir";
1484 let symlink_to_file = "link_file";
1485 let file_in_target = "file";
1486
1487 at.mkdir(directory);
1488 at.mkdir(target_dir);
1489 at.touch(target_file);
1490 at.touch(format!("{target_dir}/{file_in_target}"));
1491 at.symlink_dir(target_dir, &format!("{directory}/{symlink_to_dir}"));
1492 at.symlink_file(target_file, &format!("{directory}/{symlink_to_file}"));
1493
1494 set_permissions(at.plus(target_file), Permissions::from_mode(0o644)).unwrap();
1495 set_permissions(
1496 at.plus(format!("{target_dir}/{file_in_target}")),
1497 Permissions::from_mode(0o644),
1498 )
1499 .unwrap();
1500
1501 // Test with -R -L (follow all symlinks)
1502 scene
1503 .ucmd()
1504 .arg("-R")
1505 .arg("-L")
1506 .arg("go-rwx")
1507 .arg(directory)
1508 .succeeds()
1509 .no_stderr();
1510
1511 // Both target file and file in target directory should have permissions changed
1512 assert_eq!(at.metadata(target_file).permissions().mode(), 0o100_600);
1513 assert_eq!(
1514 at.metadata(&format!("{target_dir}/{file_in_target}"))
1515 .permissions()
1516 .mode(),
1517 0o100_600
1518 );
1519 }
1520
1521 #[test]
1522 #[cfg(target_os = "linux")]
1523 fn test_chmod_non_utf8_paths() {
1524 use std::ffi::OsStr;
1525 use std::os::unix::ffi::OsStrExt;
1526
1527 let scene = TestScenario::new(util_name!());
1528 let at = &scene.fixtures;
1529
1530 // Create a file with non-UTF-8 name
1531 // Using bytes that form an invalid UTF-8 sequence
1532 let non_utf8_bytes = b"test_\xFF\xFE.txt";
1533 let non_utf8_name = OsStr::from_bytes(non_utf8_bytes);
1534
1535 // Create the file using OpenOptions with the non-UTF-8 name
1536 OpenOptions::new()
1537 .mode(0o644)
1538 .create(true)
1539 .write(true)
1540 .truncate(true)
1541 .open(at.plus(non_utf8_name))
1542 .unwrap();
1543
1544 // Verify initial permissions
1545 let initial_perms = metadata(at.plus(non_utf8_name))
1546 .unwrap()
1547 .permissions()
1548 .mode();
1549 assert_eq!(initial_perms & 0o777, 0o644);
1550
1551 // Test chmod with the non-UTF-8 filename
1552 scene
1553 .ucmd()
1554 .arg("755")
1555 .arg(non_utf8_name)
1556 .succeeds()
1557 .no_stderr();
1558
1559 // Verify permissions were changed
1560 let new_perms = metadata(at.plus(non_utf8_name))
1561 .unwrap()
1562 .permissions()
1563 .mode();
1564 assert_eq!(new_perms & 0o777, 0o755);
1565
1566 // Test with multiple non-UTF-8 files
1567 let non_utf8_bytes2 = b"file_\xC0\x80.dat";
1568 let non_utf8_name2 = OsStr::from_bytes(non_utf8_bytes2);
1569
1570 OpenOptions::new()
1571 .mode(0o666)
1572 .create(true)
1573 .write(true)
1574 .truncate(true)
1575 .open(at.plus(non_utf8_name2))
1576 .unwrap();
1577
1578 // Change permissions on both files at once
1579 scene
1580 .ucmd()
1581 .arg("644")
1582 .arg(non_utf8_name)
1583 .arg(non_utf8_name2)
1584 .succeeds()
1585 .no_stderr();
1586
1587 // Verify both files have the new permissions
1588 assert_eq!(
1589 metadata(at.plus(non_utf8_name))
1590 .unwrap()
1591 .permissions()
1592 .mode()
1593 & 0o777,
1594 0o644
1595 );
1596 assert_eq!(
1597 metadata(at.plus(non_utf8_name2))
1598 .unwrap()
1599 .permissions()
1600 .mode()
1601 & 0o777,
1602 0o644
1603 );
1604 }
1605
1606 #[test]
1607 fn test_chmod_operator_only_still_calls_syscall() {
1608 use rustix::process::geteuid;
1609
1610 // An operator with no permission letters ('+', '-', '=') leaves the mode
1611 // bits unchanged, yet chmod must still issue the chmod(2) call so that a
1612 // lack of permission is reported instead of silently succeeding. As a
1613 // non-root user, '/' (owned by root) is a file we cannot chmod.
1614 if geteuid().is_root() {
1615 return;
1616 }
1617 if metadata("/").map_or(0, |m| m.uid()) != 0 {
1618 return; // '/' is not root-owned in this environment
1619 }
1620
1621 for op in ["+", "-", "="] {
1622 new_ucmd!()
1623 .arg(op)
1624 .arg("/")
1625 .fails()
1626 .code_is(1)
1627 .stderr_contains("changing permissions of '/'");
1628 }
1629 }
1630
1631 #[test]
1632 fn test_chmod_colored_output() {
1633 // Test colored help message
1634 new_ucmd!()
1635 .arg("--help")
1636 .env("CLICOLOR_FORCE", "1")
1637 .env("LANG", "en_US.UTF-8")
1638 .succeeds()
1639 .stdout_contains("\x1b[1m\x1b[4mUsage:\x1b[0m") // Bold+underline "Usage:"
1640 .stdout_contains("\x1b[1m\x1b[4mArguments:\x1b[0m"); // Bold+underline "Arguments:"
1641
1642 // Test colored error message for invalid option
1643 new_ucmd!()
1644 .arg("--invalid-option")
1645 .env("CLICOLOR_FORCE", "1")
1646 .env("LANG", "en_US.UTF-8")
1647 .fails()
1648 .code_is(1)
1649 .stderr_contains("\x1b[31merror\x1b[0m") // Red "error"
1650 .stderr_contains("\x1b[33m--invalid-option\x1b[0m"); // Yellow invalid option
1651
1652 // Test French localized colored error message
1653 new_ucmd!()
1654 .arg("--invalid-option")
1655 .env("CLICOLOR_FORCE", "1")
1656 .env("LANG", "fr_FR.UTF-8")
1657 .fails()
1658 .code_is(1)
1659 .stderr_contains("\x1b[31merreur\x1b[0m") // Red "erreur" in French
1660 .stderr_contains("\x1b[33m--invalid-option\x1b[0m"); // Yellow invalid option
1661 }
1662
1663 #[test]
1664 fn test_chmod_symlink_cycles() {
1665 let scene = TestScenario::new(util_name!());
1666 let at = &scene.fixtures;
1667
1668 at.mkdir_all("a/b/c");
1669 at.symlink_dir("a", "a/b/c/d");
1670
1671 // Pin the directory modes so the assertions below don't depend on the ambient
1672 // umask (a fresh mkdir under umask 077/027 would not be 0755).
1673 at.set_mode("a", 0o755);
1674 at.set_mode("a/b", 0o755);
1675 at.set_mode("a/b/c", 0o755);
1676
1677 scene
1678 .ucmd()
1679 .arg("-vRL")
1680 .arg("+r")
1681 .arg("a")
1682 .run()
1683 // cSpell:disable
1684 .stdout_contains_line("mode of 'a' retained as 0755 (rwxr-xr-x)")
1685 .stdout_contains_line("mode of 'a/b' retained as 0755 (rwxr-xr-x)")
1686 .stdout_contains_line("mode of 'a/b/c' retained as 0755 (rwxr-xr-x)")
1687 .stdout_contains_line("mode of 'a/b/c/d' retained as 0755 (rwxr-xr-x)")
1688 .stdout_does_not_contain("mode of 'a/b/c/d/b' retained as 0755 (rwxr-xr-x)")
1689 .stdout_does_not_contain("mode of 'a/b/c/d/b/c' retained as 0755 (rwxr-xr-x)")
1690 .stdout_does_not_contain("mode of 'a/b/c/d/b/c/d' retained as 0755 (rwxr-xr-x)");
1691 // cSpell:enable
1692 }
1693
1694 #[test]
1695 fn test_chmod_symlink_two_links_same_dir() {
1696 // Two symlinks pointing at the same directory is NOT a cycle: neither link is
1697 // an ancestor of the other, so the target's contents must be visited through
1698 // *both* links (and through the real directory). This guards the backtracking
1699 // in the cycle-detection logic against false positives.
1700 let scene = TestScenario::new(util_name!());
1701 let at = &scene.fixtures;
1702
1703 // cSpell:disable
1704 at.mkdir_all("base/realdir");
1705 at.touch("base/realdir/file");
1706 at.symlink_dir("base/realdir", "base/link1");
1707 at.symlink_dir("base/realdir", "base/link2");
1708
1709 // Assert on the path only (not the mode bits), so the test is robust to the
1710 // file's umask-dependent permissions across platforms.
1711 scene
1712 .ucmd()
1713 .arg("-vRL")
1714 .arg("+r")
1715 .arg("base")
1716 .run()
1717 .stdout_contains("mode of 'base/realdir/file'")
1718 .stdout_contains("mode of 'base/link1/file'")
1719 .stdout_contains("mode of 'base/link2/file'");
1720 // cSpell:enable
1721 }
1722
1723 #[cfg(all(feature = "feat_diagnostics", not(wasi_runner)))]
1724 mod diagnostics {
1725 use super::*;
1726 #[cfg(unix)]
1727 #[test]
1728 fn test_snippet_points_at_the_bad_operator() {
1729 let (at, mut ucmd) = at_and_ucmd!();
1730 at.touch("probe");
1731
1732 let result = ucmd
1733 .terminal_sim_stderr()
1734 .args(&["g+rw?x", "probe"])
1735 .fails_with_code(1);
1736 let stderr = result.stderr_str();
1737
1738 assert!(stderr.contains("invalid operator"), "{stderr}");
1739 // The caret lands on `?`, the fifth character of the mode.
1740 assert_eq!(result.caret_column(), Some(5), "{stderr}");
1741 }
1742
1743 #[cfg(unix)]
1744 #[test]
1745 fn test_snippet_points_into_the_second_clause() {
1746 let (at, mut ucmd) = at_and_ucmd!();
1747 at.touch("probe");
1748
1749 let result = ucmd
1750 .terminal_sim_stderr()
1751 .args(&["o=r,ug!w", "probe"])
1752 .fails_with_code(1);
1753 let stderr = result.stderr_str();
1754
1755 // Clauses are parsed one at a time, but the caret is placed in the
1756 // whole mode: `!` is its seventh character.
1757 assert_eq!(result.caret_column(), Some(7), "{stderr}");
1758 }
1759
1760 #[cfg(unix)]
1761 #[test]
1762 fn test_snippet_marks_a_clause_with_no_operator() {
1763 let (at, mut ucmd) = at_and_ucmd!();
1764 at.touch("probe");
1765
1766 let result = ucmd
1767 .terminal_sim_stderr()
1768 .args(&["go", "probe"])
1769 .fails_with_code(1);
1770 let stderr = result.stderr_str();
1771
1772 assert!(stderr.contains("invalid mode"), "{stderr}");
1773 assert_eq!(result.caret_column(), Some(1), "{stderr}");
1774 }
1775
1776 #[cfg(unix)]
1777 #[test]
1778 fn test_snippet_marks_a_non_octal_mode() {
1779 let (at, mut ucmd) = at_and_ucmd!();
1780 at.touch("probe");
1781
1782 ucmd.terminal_sim_stderr()
1783 .args(&["779", "probe"])
1784 .fails_with_code(1)
1785 .stderr_contains("779");
1786 }
1787
1788 #[cfg(unix)]
1789 #[test]
1790 fn test_snippet_points_into_a_negative_mode() {
1791 let (at, mut ucmd) = at_and_ucmd!();
1792 at.touch("probe");
1793
1794 // A leading-dash mode is pulled out of the argument list before clap
1795 // sees it, but the caret still lands on `%`, its fourth character.
1796 let result = ucmd
1797 .terminal_sim_stderr()
1798 .args(&["-rw%x", "probe"])
1799 .fails_with_code(1);
1800 let stderr = result.stderr_str();
1801
1802 assert!(stderr.contains("invalid operator"), "{stderr}");
1803 assert_eq!(result.caret_column(), Some(4), "{stderr}");
1804 }
1805
1806 #[cfg(unix)]
1807 #[test]
1808 fn test_snippet_points_into_the_right_negative_mode() {
1809 let (at, mut ucmd) = at_and_ucmd!();
1810 at.touch("probe");
1811
1812 // Several negative modes are joined into one mode string before being
1813 // parsed, but the caret still lands on `%` inside the one argument
1814 // that carries the bad clause.
1815 let result = ucmd
1816 .terminal_sim_stderr()
1817 .args(&["-w", "-r%x", "probe"])
1818 .fails_with_code(1);
1819 let stderr = result.stderr_str();
1820
1821 assert!(stderr.contains("invalid operator"), "{stderr}");
1822 // Column 6 of `-w -r%x probe` is the `%`.
1823 assert_eq!(result.caret_column(), Some(6), "{stderr}");
1824 }
1825
1826 #[cfg(unix)]
1827 #[test]
1828 fn test_snippet_points_at_the_mode_not_a_file_with_the_same_name() {
1829 let (at, mut ucmd) = at_and_ucmd!();
1830 at.touch("g+rw?x");
1831
1832 // The file is named exactly like the mode; the caret belongs to the
1833 // mode operand, the first of the two.
1834 let result = ucmd
1835 .terminal_sim_stderr()
1836 .args(&["g+rw?x", "g+rw?x"])
1837 .fails_with_code(1);
1838 let stderr = result.stderr_str();
1839
1840 assert!(stderr.contains("invalid operator"), "{stderr}");
1841 assert_eq!(result.caret_column(), Some(5), "{stderr}");
1842 }
1843
1844 #[test]
1845 fn test_plain_message_when_stderr_is_a_pipe() {
1846 let (at, mut ucmd) = at_and_ucmd!();
1847 at.touch("probe");
1848
1849 // The test harness pipes stderr, so the report must not appear.
1850 ucmd.args(&["g+rw?x", "probe"])
1851 .fails_with_code(1)
1852 .stderr_only("chmod: invalid operator (expected +, -, or =, but found ?)\n");
1853 }
1854
1855 #[cfg(unix)]
1856 #[test]
1857 fn test_quiet_stays_quiet() {
1858 let (at, mut ucmd) = at_and_ucmd!();
1859 at.touch("probe");
1860
1861 // -f suppresses the message entirely, report included.
1862 ucmd.terminal_sim_stderr()
1863 .args(&["-f", "g+rw?x", "probe"])
1864 .fails_with_code(1)
1865 .no_output();
1866 }
1867 }