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>
30 #include "modechange.h"
34 #include "root-dev-ino.h"
37 /* The official name of this program (e.g., no `g' prefix). */
38 #define PROGRAM_NAME "chmod"
40 #define AUTHORS "David MacKenzie", "Jim Meyering"
47 CH_NO_CHANGE_REQUESTED
52 /* Print a message for each file that is processed. */
55 /* Print a message for each file whose attributes we change. */
58 /* Do not be verbose. This is the default. */
62 /* The name the program was run with. */
65 /* The desired change to the mode. */
66 static struct mode_change *change;
68 /* The initial umask value, if it might be needed. */
69 static mode_t umask_value;
71 /* If true, change the modes of directories recursively. */
74 /* If true, force silence (no error messages). */
75 static bool force_silent;
77 /* If true, diagnose surprises from naive misuses like "chmod -r file".
78 POSIX allows diagnostics here, as portable code is supposed to use
79 "chmod -- -r file". */
80 static bool diagnose_surprises;
82 /* Level of verbosity. */
83 static enum Verbosity verbosity = V_off;
85 /* Pointer to the device and inode numbers of `/', when --recursive.
87 static struct dev_ino *root_dev_ino;
89 /* For long options that have no equivalent short option, use a
90 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
93 NO_PRESERVE_ROOT = CHAR_MAX + 1,
98 static struct option const long_options[] =
100 {"changes", no_argument, NULL, 'c'},
101 {"recursive", no_argument, NULL, 'R'},
102 {"no-preserve-root", no_argument, NULL, NO_PRESERVE_ROOT},
103 {"preserve-root", no_argument, NULL, PRESERVE_ROOT},
104 {"quiet", no_argument, NULL, 'f'},
105 {"reference", required_argument, NULL, REFERENCE_FILE_OPTION},
106 {"silent", no_argument, NULL, 'f'},
107 {"verbose", no_argument, NULL, 'v'},
108 {GETOPT_HELP_OPTION_DECL},
109 {GETOPT_VERSION_OPTION_DECL},
113 /* Return true if the chmodable permission bits of FILE changed.
114 The old mode was OLD_MODE, but it was changed to NEW_MODE. */
117 mode_changed (char const *file, mode_t old_mode, mode_t new_mode)
119 if (new_mode & (S_ISUID | S_ISGID | S_ISVTX))
121 /* The new mode contains unusual bits that the call to chmod may
122 have silently cleared. Check whether they actually changed. */
124 struct stat new_stats;
126 if (stat (file, &new_stats) != 0)
129 error (0, errno, _("getting new attributes of %s"), quote (file));
133 new_mode = new_stats.st_mode;
136 return ((old_mode ^ new_mode) & CHMOD_MODE_BITS) != 0;
139 /* Tell the user how/if the MODE of FILE has been changed.
140 CHANGED describes what (if anything) has happened. */
143 describe_change (const char *file, mode_t mode,
144 enum Change_status changed)
146 char perms[12]; /* "-rwxrwxrwx" ls-style modes. */
149 if (changed == CH_NOT_APPLIED)
151 printf (_("neither symbolic link %s nor referent has been changed\n"),
156 strmode (mode, perms);
157 perms[10] = '\0'; /* Remove trailing space. */
161 fmt = _("mode of %s changed to %04lo (%s)\n");
164 fmt = _("failed to change mode of %s to %04lo (%s)\n");
166 case CH_NO_CHANGE_REQUESTED:
167 fmt = _("mode of %s retained as %04lo (%s)\n");
172 printf (fmt, quote (file),
173 (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]);
176 /* Change the mode of FILE.
177 Return true if successful. This function is called
178 once for every file system object that fts encounters. */
181 process_file (FTS *fts, FTSENT *ent)
183 char const *file_full_name = ent->fts_path;
184 char const *file = ent->fts_accpath;
185 const struct stat *file_stats = ent->fts_statp;
186 mode_t old_mode IF_LINT (= 0);
187 mode_t new_mode IF_LINT (= 0);
189 bool chmod_succeeded = false;
191 switch (ent->fts_info)
197 error (0, ent->fts_errno, _("cannot access %s"), quote (file_full_name));
202 error (0, ent->fts_errno, _("%s"), quote (file_full_name));
207 error (0, ent->fts_errno, _("cannot read directory %s"),
208 quote (file_full_name));
216 if (ok && ROOT_DEV_INO_CHECK (root_dev_ino, file_stats))
218 ROOT_DEV_INO_WARN (file_full_name);
224 old_mode = file_stats->st_mode;
225 new_mode = mode_adjust (old_mode, change, umask_value);
227 if (! S_ISLNK (old_mode))
229 if (chmodat (fts->fts_cwd_fd, file, new_mode) == 0)
230 chmod_succeeded = true;
234 error (0, errno, _("changing permissions of %s"),
235 quote (file_full_name));
241 if (verbosity != V_off)
243 bool changed = (chmod_succeeded
244 && mode_changed (file, old_mode, new_mode));
246 if (changed || verbosity == V_high)
248 enum Change_status ch_status =
250 : !chmod_succeeded ? CH_NOT_APPLIED
251 : !changed ? CH_NO_CHANGE_REQUESTED
253 describe_change (file_full_name, new_mode, ch_status);
257 if (chmod_succeeded & diagnose_surprises)
259 mode_t naively_expected_mode = mode_adjust (old_mode, change, 0);
260 if (new_mode & ~naively_expected_mode)
263 char naively_expected_perms[12];
264 strmode (new_mode, new_perms);
265 strmode (naively_expected_mode, naively_expected_perms);
266 new_perms[10] = naively_expected_perms[10] = '\0';
268 _("%s: new permissions are %s, not %s"),
269 quotearg_colon (file_full_name),
270 new_perms + 1, naively_expected_perms + 1);
276 fts_set (fts, ent, FTS_SKIP);
281 /* Recursively change the modes of the specified FILES (the last entry
282 of which is NULL). BIT_FLAGS controls how fts works.
283 Return true if successful. */
286 process_files (char **files, int bit_flags)
290 FTS *fts = xfts_open (files, bit_flags, NULL);
296 ent = fts_read (fts);
301 /* FIXME: try to give a better message */
302 error (0, errno, _("fts_read failed"));
308 ok &= process_file (fts, ent);
311 /* Ignore failure, since the only way it can do so is in failing to
312 return to the original directory, and since we're about to exit,
313 that doesn't matter. */
322 if (status != EXIT_SUCCESS)
323 fprintf (stderr, _("Try `%s --help' for more information.\n"),
328 Usage: %s [OPTION]... MODE[,MODE]... FILE...\n\
329 or: %s [OPTION]... OCTAL-MODE FILE...\n\
330 or: %s [OPTION]... --reference=RFILE FILE...\n\
332 program_name, program_name, program_name);
334 Change the mode of each FILE to MODE.\n\
336 -c, --changes like verbose but report only when a change is made\n\
339 --no-preserve-root do not treat `/' specially (the default)\n\
340 --preserve-root fail to operate recursively on `/'\n\
343 -f, --silent, --quiet suppress most error messages\n\
344 -v, --verbose output a diagnostic for every file processed\n\
345 --reference=RFILE use RFILE's mode instead of MODE values\n\
346 -R, --recursive change files and directories recursively\n\
348 fputs (HELP_OPTION_DESCRIPTION, stdout);
349 fputs (VERSION_OPTION_DESCRIPTION, stdout);
352 Each MODE is of the form `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'.\n\
354 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
359 /* Parse the ASCII mode given on the command line into a linked list
360 of `struct mode_change' and apply that to each file argument. */
363 main (int argc, char **argv)
367 size_t mode_alloc = 0;
369 bool preserve_root = false;
370 char const *reference_file = NULL;
373 initialize_main (&argc, &argv);
374 program_name = argv[0];
375 setlocale (LC_ALL, "");
376 bindtextdomain (PACKAGE, LOCALEDIR);
377 textdomain (PACKAGE);
379 atexit (close_stdout);
381 recurse = force_silent = diagnose_surprises = false;
383 while ((c = getopt_long (argc, argv,
384 "Rcfvr::w::x::X::s::t::u::g::o::a::,::+::=::",
403 /* Support nonportable uses like "chmod -w", but diagnose
404 surprises due to umask confusion. Even though "--", "--r",
405 etc., are valid modes, there is no "case '-'" here since
406 getopt_long reserves leading "--" for long options. */
408 /* Allocate a mode string (e.g., "-rwx") by concatenating
409 the argument containing this option. If a previous mode
410 string was given, concatenate the previous string, a
411 comma, and the new string (e.g., "-s,-rwx"). */
413 char const *arg = argv[optind - 1];
414 size_t arg_len = strlen (arg);
415 size_t mode_comma_len = mode_len + !!mode_len;
416 size_t new_mode_len = mode_comma_len + arg_len;
417 if (mode_alloc <= new_mode_len)
419 mode_alloc = new_mode_len + 1;
420 mode = X2REALLOC (mode, &mode_alloc);
422 mode[mode_len] = ',';
423 strcpy (mode + mode_comma_len, arg);
424 mode_len = new_mode_len;
426 diagnose_surprises = true;
429 case NO_PRESERVE_ROOT:
430 preserve_root = false;
433 preserve_root = true;
435 case REFERENCE_FILE_OPTION:
436 reference_file = optarg;
442 verbosity = V_changes_only;
450 case_GETOPT_HELP_CHAR;
451 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
453 usage (EXIT_FAILURE);
461 error (0, 0, _("cannot combine mode and --reference options"));
462 usage (EXIT_FAILURE);
468 mode = argv[optind++];
473 if (!mode || mode != argv[optind - 1])
474 error (0, 0, _("missing operand"));
476 error (0, 0, _("missing operand after %s"), quote (argv[argc - 1]));
477 usage (EXIT_FAILURE);
482 change = mode_create_from_ref (reference_file);
484 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
485 quote (reference_file));
489 change = mode_compile (mode);
492 error (0, 0, _("invalid mode: %s"), quote (mode));
493 usage (EXIT_FAILURE);
495 umask_value = umask (0);
498 if (recurse & preserve_root)
500 static struct dev_ino dev_ino_buf;
501 root_dev_ino = get_root_dev_ino (&dev_ino_buf);
502 if (root_dev_ino == NULL)
503 error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
511 ok = process_files (argv + optind, FTS_COMFOLLOW | FTS_PHYSICAL);
513 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);