1 /* chmod -- change permission modes of files
2 Copyright (C) 89, 90, 91, 1995-2006 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
23 #include <sys/types.h>
29 #include "modechange.h"
33 #include "root-dev-ino.h"
36 /* The official name of this program (e.g., no `g' prefix). */
37 #define PROGRAM_NAME "chmod"
39 #define AUTHORS "David MacKenzie", "Jim Meyering"
46 CH_NO_CHANGE_REQUESTED
51 /* Print a message for each file that is processed. */
54 /* Print a message for each file whose attributes we change. */
57 /* Do not be verbose. This is the default. */
61 /* The name the program was run with. */
64 /* The desired change to the mode. */
65 static struct mode_change *change;
67 /* The initial umask value, if it might be needed. */
68 static mode_t umask_value;
70 /* If true, change the modes of directories recursively. */
73 /* If true, force silence (no error messages). */
74 static bool force_silent;
76 /* If true, diagnose surprises from naive misuses like "chmod -r file".
77 POSIX allows diagnostics here, as portable code is supposed to use
78 "chmod -- -r file". */
79 static bool diagnose_surprises;
81 /* Level of verbosity. */
82 static enum Verbosity verbosity = V_off;
84 /* Pointer to the device and inode numbers of `/', when --recursive.
86 static struct dev_ino *root_dev_ino;
88 /* Error number associated with the working directory, or 0 if no
89 error has been found. */
92 /* For long options that have no equivalent short option, use a
93 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
96 NO_PRESERVE_ROOT = CHAR_MAX + 1,
101 static struct option const long_options[] =
103 {"changes", no_argument, NULL, 'c'},
104 {"recursive", no_argument, NULL, 'R'},
105 {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
106 {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
107 {"quiet", no_argument, NULL, 'f'},
108 {"reference", required_argument, NULL, REFERENCE_FILE_OPTION},
109 {"silent", no_argument, NULL, 'f'},
110 {"verbose", no_argument, NULL, 'v'},
111 {GETOPT_HELP_OPTION_DECL},
112 {GETOPT_VERSION_OPTION_DECL},
116 /* Return true if the chmodable permission bits of FILE changed.
117 The old mode was OLD_MODE, but it was changed to NEW_MODE. */
120 mode_changed (char const *file, mode_t old_mode, mode_t new_mode)
122 if (new_mode & (S_ISUID | S_ISGID | S_ISVTX))
124 /* The new mode contains unusual bits that the call to chmod may
125 have silently cleared. Check whether they actually changed. */
127 struct stat new_stats;
129 if (stat (file, &new_stats) != 0)
132 error (0, errno, _("getting new attributes of %s"), quote (file));
136 new_mode = new_stats.st_mode;
139 return ((old_mode ^ new_mode) & CHMOD_MODE_BITS) != 0;
142 /* Tell the user how/if the MODE of FILE has been changed.
143 CHANGED describes what (if anything) has happened. */
146 describe_change (const char *file, mode_t mode,
147 enum Change_status changed)
149 char perms[12]; /* "-rwxrwxrwx" ls-style modes. */
152 if (changed == CH_NOT_APPLIED)
154 printf (_("neither symbolic link %s nor referent has been changed\n"),
159 strmode (mode, perms);
160 perms[10] = '\0'; /* Remove trailing space. */
164 fmt = _("mode of %s changed to %04lo (%s)\n");
167 fmt = _("failed to change mode of %s to %04lo (%s)\n");
169 case CH_NO_CHANGE_REQUESTED:
170 fmt = _("mode of %s retained as %04lo (%s)\n");
175 printf (fmt, quote (file),
176 (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]);
179 /* Change the mode of FILE.
180 Return true if successful. This function is called
181 once for every file system object that fts encounters. */
184 process_file (FTS *fts, FTSENT *ent)
186 char const *file_full_name = ent->fts_path;
187 char const *file = ent->fts_accpath;
188 const struct stat *file_stats = ent->fts_statp;
189 mode_t old_mode IF_LINT (= 0);
190 mode_t new_mode IF_LINT (= 0);
192 bool chmod_succeeded = false;
194 switch (ent->fts_info)
200 error (0, ent->fts_errno, _("cannot access %s"), quote (file_full_name));
205 error (0, ent->fts_errno, _("%s"), quote (file_full_name));
210 error (0, ent->fts_errno, _("cannot read directory %s"),
211 quote (file_full_name));
219 if (ok && ROOT_DEV_INO_CHECK (root_dev_ino, file_stats))
221 ROOT_DEV_INO_WARN (file_full_name);
227 old_mode = file_stats->st_mode;
228 new_mode = mode_adjust (old_mode, S_ISDIR (old_mode) != 0, umask_value,
231 if (! S_ISLNK (old_mode))
233 if (chmodat (fts->fts_cwd_fd, file, new_mode) == 0)
234 chmod_succeeded = true;
238 error (0, errno, _("changing permissions of %s"),
239 quote (file_full_name));
245 if (verbosity != V_off)
247 bool changed = (chmod_succeeded
248 && mode_changed (file, old_mode, new_mode));
250 if (changed || verbosity == V_high)
252 enum Change_status ch_status =
254 : !chmod_succeeded ? CH_NOT_APPLIED
255 : !changed ? CH_NO_CHANGE_REQUESTED
257 describe_change (file_full_name, new_mode, ch_status);
261 if (chmod_succeeded & diagnose_surprises)
263 mode_t naively_expected_mode =
264 mode_adjust (old_mode, S_ISDIR (old_mode) != 0, 0, change, NULL);
265 if (new_mode & ~naively_expected_mode)
268 char naively_expected_perms[12];
269 strmode (new_mode, new_perms);
270 strmode (naively_expected_mode, naively_expected_perms);
271 new_perms[10] = naively_expected_perms[10] = '\0';
273 _("%s: new permissions are %s, not %s"),
274 quotearg_colon (file_full_name),
275 new_perms + 1, naively_expected_perms + 1);
281 fts_set (fts, ent, FTS_SKIP);
286 /* Recursively change the modes of the command-line operand FILE.
287 BIT_FLAGS controls how fts works.
288 Return true if successful. */
291 chmod_file (char *file, int bit_flags)
298 fts = xfts_open (files, bit_flags, NULL);
304 ent = fts_read (fts);
309 /* FIXME: try to give a better message */
310 error (0, errno, _("fts_read failed"));
316 ok &= process_file (fts, ent);
319 if (fts_close (fts) != 0)
325 /* Recursively change the modes of the specified FILES (the last entry
326 of which is NULL). BIT_FLAGS controls how fts works.
327 Return true if successful. */
329 process_files (char **files, int bit_flags)
334 for (; *files; files++)
336 if (! IS_ABSOLUTE_FILE_NAME (*files) && wd_errno)
338 error (0, wd_errno, ".");
342 ok &= chmod_file (*files, bit_flags);
351 if (status != EXIT_SUCCESS)
352 fprintf (stderr, _("Try `%s --help' for more information.\n"),
357 Usage: %s [OPTION]... MODE[,MODE]... FILE...\n\
358 or: %s [OPTION]... OCTAL-MODE FILE...\n\
359 or: %s [OPTION]... --reference=RFILE FILE...\n\
361 program_name, program_name, program_name);
363 Change the mode of each FILE to MODE.\n\
365 -c, --changes like verbose but report only when a change is made\n\
368 --no-preserve-root do not treat `/' specially (the default)\n\
369 --preserve-root fail to operate recursively on `/'\n\
372 -f, --silent, --quiet suppress most error messages\n\
373 -v, --verbose output a diagnostic for every file processed\n\
374 --reference=RFILE use RFILE's mode instead of MODE values\n\
375 -R, --recursive change files and directories recursively\n\
377 fputs (HELP_OPTION_DESCRIPTION, stdout);
378 fputs (VERSION_OPTION_DESCRIPTION, stdout);
381 Each MODE is of the form `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'.\n\
383 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
388 /* Parse the ASCII mode given on the command line into a linked list
389 of `struct mode_change' and apply that to each file argument. */
392 main (int argc, char **argv)
396 size_t mode_alloc = 0;
398 bool preserve_root = false;
399 char const *reference_file = NULL;
402 initialize_main (&argc, &argv);
403 program_name = argv[0];
404 setlocale (LC_ALL, "");
405 bindtextdomain (PACKAGE, LOCALEDIR);
406 textdomain (PACKAGE);
408 atexit (close_stdout);
410 recurse = force_silent = diagnose_surprises = false;
412 while ((c = getopt_long (argc, argv,
413 "Rcfvr::w::x::X::s::t::u::g::o::a::,::+::=::",
432 /* Support nonportable uses like "chmod -w", but diagnose
433 surprises due to umask confusion. Even though "--", "--r",
434 etc., are valid modes, there is no "case '-'" here since
435 getopt_long reserves leading "--" for long options. */
437 /* Allocate a mode string (e.g., "-rwx") by concatenating
438 the argument containing this option. If a previous mode
439 string was given, concatenate the previous string, a
440 comma, and the new string (e.g., "-s,-rwx"). */
442 char const *arg = argv[optind - 1];
443 size_t arg_len = strlen (arg);
444 size_t mode_comma_len = mode_len + !!mode_len;
445 size_t new_mode_len = mode_comma_len + arg_len;
446 if (mode_alloc <= new_mode_len)
448 mode_alloc = new_mode_len + 1;
449 mode = X2REALLOC (mode, &mode_alloc);
451 mode[mode_len] = ',';
452 strcpy (mode + mode_comma_len, arg);
453 mode_len = new_mode_len;
455 diagnose_surprises = true;
458 case NO_PRESERVE_ROOT:
459 preserve_root = false;
462 preserve_root = true;
464 case REFERENCE_FILE_OPTION:
465 reference_file = optarg;
471 verbosity = V_changes_only;
479 case_GETOPT_HELP_CHAR;
480 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
482 usage (EXIT_FAILURE);
490 error (0, 0, _("cannot combine mode and --reference options"));
491 usage (EXIT_FAILURE);
497 mode = argv[optind++];
502 if (!mode || mode != argv[optind - 1])
503 error (0, 0, _("missing operand"));
505 error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
506 usage (EXIT_FAILURE);
511 change = mode_create_from_ref (reference_file);
513 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
514 quote (reference_file));
518 change = mode_compile (mode);
521 error (0, 0, _("invalid mode: %s"), quote (mode));
522 usage (EXIT_FAILURE);
524 umask_value = umask (0);
527 if (recurse & preserve_root)
529 static struct dev_ino dev_ino_buf;
530 root_dev_ino = get_root_dev_ino (&dev_ino_buf);
531 if (root_dev_ino == NULL)
532 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
540 ok = process_files (argv + optind, FTS_COMFOLLOW | FTS_PHYSICAL);
542 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);