Most .c files (AUTHORS): Revert the WRITTEN_BY/AUTHORS change
[platform/upstream/coreutils.git] / src / chmod.c
1 /* chmod -- change permission modes of files
2    Copyright (C) 89, 90, 91, 1995-2003 Free Software Foundation, Inc.
3
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)
7    any later version.
8
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.
13
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24
25 #include "system.h"
26 #include "dev-ino.h"
27 #include "dirname.h"
28 #include "error.h"
29 #include "filemode.h"
30 #include "modechange.h"
31 #include "quote.h"
32 #include "savedir.h"
33
34 /* The official name of this program (e.g., no `g' prefix).  */
35 #define PROGRAM_NAME "chmod"
36
37 #define AUTHORS "David MacKenzie"
38
39 enum Change_status
40 {
41   CH_SUCCEEDED,
42   CH_FAILED,
43   CH_NO_CHANGE_REQUESTED
44 };
45
46 enum Verbosity
47 {
48   /* Print a message for each file that is processed.  */
49   V_high,
50
51   /* Print a message for each file whose attributes we change.  */
52   V_changes_only,
53
54   /* Do not be verbose.  This is the default. */
55   V_off
56 };
57
58 static int change_dir_mode (const char *dir, const struct mode_change *changes);
59
60 /* The name the program was run with. */
61 char *program_name;
62
63 /* If nonzero, change the modes of directories recursively. */
64 static int recurse;
65
66 /* If nonzero, force silence (no error messages). */
67 static int force_silent;
68
69 /* Level of verbosity.  */
70 static enum Verbosity verbosity = V_off;
71
72 /* The argument to the --reference option.  Use the owner and group IDs
73    of this file.  This file must exist.  */
74 static char *reference_file;
75
76 /* Pointer to the device and inode numbers of `/', when --recursive.
77    Otherwise NULL.  */
78 static struct dev_ino *root_dev_ino;
79
80 /* For long options that have no equivalent short option, use a
81    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
82 enum
83 {
84   NO_PRESERVE_ROOT = CHAR_MAX + 1,
85   PRESERVE_ROOT,
86   REFERENCE_FILE_OPTION
87 };
88
89 static struct option const long_options[] =
90 {
91   {"recursive", no_argument, 0, 'R'},
92   {"changes", no_argument, 0, 'c'},
93   {"preserve-root", no_argument, 0, PRESERVE_ROOT},
94   {"no-preserve-root", no_argument, 0, NO_PRESERVE_ROOT},
95   {"quiet", no_argument, 0, 'f'},
96   {"reference", required_argument, 0, REFERENCE_FILE_OPTION},
97   {"silent", no_argument, 0, 'f'},
98   {"verbose", no_argument, 0, 'v'},
99   {GETOPT_HELP_OPTION_DECL},
100   {GETOPT_VERSION_OPTION_DECL},
101   {0, 0, 0, 0}
102 };
103
104 static int
105 mode_changed (const char *file, mode_t old_mode)
106 {
107   struct stat new_stats;
108
109   if (stat (file, &new_stats))
110     {
111       if (force_silent == 0)
112         error (0, errno, _("getting new attributes of %s"), quote (file));
113       return 0;
114     }
115
116   return old_mode != new_stats.st_mode;
117 }
118
119 /* Tell the user how/if the MODE of FILE has been changed.
120    CHANGED describes what (if anything) has happened. */
121
122 static void
123 describe_change (const char *file, mode_t mode,
124                  enum Change_status changed)
125 {
126   char perms[11];               /* "-rwxrwxrwx" ls-style modes. */
127   const char *fmt;
128
129   mode_string (mode, perms);
130   perms[10] = '\0';             /* `mode_string' does not null terminate. */
131   switch (changed)
132     {
133     case CH_SUCCEEDED:
134       fmt = _("mode of %s changed to %04lo (%s)\n");
135       break;
136     case CH_FAILED:
137       fmt = _("failed to change mode of %s to %04lo (%s)\n");
138       break;
139     case CH_NO_CHANGE_REQUESTED:
140       fmt = _("mode of %s retained as %04lo (%s)\n");
141       break;
142     default:
143       abort ();
144     }
145   printf (fmt, quote (file),
146           (unsigned long) (mode & CHMOD_MODE_BITS), &perms[1]);
147 }
148
149 /* Change the mode of FILE according to the list of operations CHANGES.
150    If DEREF_SYMLINK is nonzero and FILE is a symbolic link, change the
151    mode of the referenced file.  If DEREF_SYMLINK is zero, ignore symbolic
152    links.  Return 0 if successful, 1 if errors occurred. */
153
154 static int
155 change_file_mode (const char *file, const struct mode_change *changes,
156                   const int deref_symlink)
157 {
158   struct stat file_stats;
159   mode_t newmode;
160   int errors = 0;
161   int fail;
162   int saved_errno;
163
164   if (deref_symlink ? stat (file, &file_stats) : lstat (file, &file_stats))
165     {
166       if (force_silent == 0)
167         error (0, errno, _("failed to get attributes of %s"), quote (file));
168       return 1;
169     }
170
171   if (root_dev_ino && SAME_INODE (file_stats, *root_dev_ino))
172     {
173       if (STREQ (file, "/"))
174         error (0, 0, _("it is dangerous to operate recursively on %s"),
175                quote (file));
176       else
177         error (0, 0,
178                _("it is dangerous to operate recursively on %s (same as %s)"),
179                quote_n (0, file), quote_n (1, "/"));
180       error (0, 0, _("use --no-preserve-root to override this failsafe"));
181       return 1;
182     }
183
184   if (S_ISLNK (file_stats.st_mode))
185     return 0;
186
187   newmode = mode_adjust (file_stats.st_mode, changes);
188
189   fail = chmod (file, newmode);
190   saved_errno = errno;
191
192   if (verbosity == V_high
193       || (verbosity == V_changes_only
194           && !fail && mode_changed (file, file_stats.st_mode)))
195     describe_change (file, newmode, (fail ? CH_FAILED : CH_SUCCEEDED));
196
197   if (fail)
198     {
199       if (force_silent == 0)
200         error (0, saved_errno, _("changing permissions of %s"),
201                quote (file));
202       errors = 1;
203     }
204
205   if (recurse && S_ISDIR (file_stats.st_mode))
206     {
207       char *f;
208       ASSIGN_STRDUPA (f, file);
209       strip_trailing_slashes (f);
210       errors |= change_dir_mode (f, changes);
211     }
212   return errors;
213 }
214
215 /* Recursively change the modes of the files in directory DIR
216    according to the list of operations CHANGES.
217    Return 0 if successful, 1 if errors occurred. */
218
219 static int
220 change_dir_mode (const char *dir, const struct mode_change *changes)
221 {
222   char *name_space, *namep;
223   char *path;                   /* Full path of each entry to process. */
224   unsigned dirlength;           /* Length of DIR and '\0'. */
225   unsigned filelength;          /* Length of each pathname to process. */
226   unsigned pathlength;          /* Bytes allocated for `path'. */
227   int errors = 0;
228
229   name_space = savedir (dir);
230   if (name_space == NULL)
231     {
232       if (force_silent == 0)
233         error (0, errno, "%s", quote (dir));
234       return 1;
235     }
236
237   dirlength = strlen (dir) + 1; /* + 1 is for the trailing '/'. */
238   pathlength = dirlength + 1;
239   /* Give `path' a dummy value; it will be reallocated before first use. */
240   path = xmalloc (pathlength);
241   strcpy (path, dir);
242   path[dirlength - 1] = '/';
243
244   for (namep = name_space; *namep; namep += filelength - dirlength)
245     {
246       filelength = dirlength + strlen (namep) + 1;
247       if (filelength > pathlength)
248         {
249           pathlength = filelength * 2;
250           path = xrealloc (path, pathlength);
251         }
252       strcpy (path + dirlength, namep);
253       errors |= change_file_mode (path, changes, 0);
254     }
255   free (path);
256   free (name_space);
257   return errors;
258 }
259
260 void
261 usage (int status)
262 {
263   if (status != 0)
264     fprintf (stderr, _("Try `%s --help' for more information.\n"),
265              program_name);
266   else
267     {
268       printf (_("\
269 Usage: %s [OPTION]... MODE[,MODE]... FILE...\n\
270   or:  %s [OPTION]... OCTAL-MODE FILE...\n\
271   or:  %s [OPTION]... --reference=RFILE FILE...\n\
272 "),
273               program_name, program_name, program_name);
274       fputs (_("\
275 Change the mode of each FILE to MODE.\n\
276 \n\
277   -c, --changes           like verbose but report only when a change is made\n\
278       --preserve-root     fail to operate recursively on `/'\n\
279       --no-preserve-root  do not treat `/' specially (the default)\n\
280   -f, --silent, --quiet   suppress most error messages\n\
281   -v, --verbose           output a diagnostic for every file processed\n\
282       --reference=RFILE   use RFILE's mode instead of MODE values\n\
283   -R, --recursive         change files and directories recursively\n\
284 "), stdout);
285       fputs (HELP_OPTION_DESCRIPTION, stdout);
286       fputs (VERSION_OPTION_DESCRIPTION, stdout);
287       fputs (_("\
288 \n\
289 Each MODE is one or more of the letters ugoa, one of the symbols +-= and\n\
290 one or more of the letters rwxXstugo.\n\
291 "), stdout);
292       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
293     }
294   exit (status);
295 }
296
297 /* Call lstat to get the device and inode numbers for `/'.
298    Upon failure, return NULL.  Otherwise, set the members of
299    *ROOT_D_I accordingly and return ROOT_D_I.  */
300 static struct dev_ino *
301 get_root_dev_ino (struct dev_ino *root_d_i)
302 {
303   struct stat statbuf;
304   if (lstat ("/", &statbuf))
305     return NULL;
306   root_d_i->st_ino = statbuf.st_ino;
307   root_d_i->st_dev = statbuf.st_dev;
308   return root_d_i;
309 }
310
311 /* Parse the ASCII mode given on the command line into a linked list
312    of `struct mode_change' and apply that to each file argument. */
313
314 int
315 main (int argc, char **argv)
316 {
317   struct mode_change *changes;
318   int errors = 0;
319   int modeind = 0;              /* Index of the mode argument in `argv'. */
320   int thisind;
321   bool preserve_root = false;
322   int c;
323
324   initialize_main (&argc, &argv);
325   program_name = argv[0];
326   setlocale (LC_ALL, "");
327   bindtextdomain (PACKAGE, LOCALEDIR);
328   textdomain (PACKAGE);
329
330   atexit (close_stdout);
331
332   recurse = force_silent = 0;
333
334   while (1)
335     {
336       thisind = optind ? optind : 1;
337
338       c = getopt_long (argc, argv, "RcfvrwxXstugoa,+-=", long_options, NULL);
339       if (c == -1)
340         break;
341
342       switch (c)
343         {
344         case 0:
345           break;
346         case 'r':
347         case 'w':
348         case 'x':
349         case 'X':
350         case 's':
351         case 't':
352         case 'u':
353         case 'g':
354         case 'o':
355         case 'a':
356         case ',':
357         case '+':
358         case '-':
359         case '=':
360           if (modeind != 0 && modeind != thisind)
361             {
362               static char char_string[2] = {0, 0};
363               char_string[0] = c;
364               error (EXIT_FAILURE, 0,
365                      _("invalid character %s in mode string %s"),
366                      quote_n (0, char_string), quote_n (1, argv[thisind]));
367             }
368           modeind = thisind;
369           break;
370         case NO_PRESERVE_ROOT:
371           preserve_root = false;
372           break;
373         case PRESERVE_ROOT:
374           preserve_root = true;
375           break;
376         case REFERENCE_FILE_OPTION:
377           reference_file = optarg;
378           break;
379         case 'R':
380           recurse = 1;
381           break;
382         case 'c':
383           verbosity = V_changes_only;
384           break;
385         case 'f':
386           force_silent = 1;
387           break;
388         case 'v':
389           verbosity = V_high;
390           break;
391         case_GETOPT_HELP_CHAR;
392         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
393         default:
394           usage (EXIT_FAILURE);
395         }
396     }
397
398   if (modeind == 0 && reference_file == NULL)
399     modeind = optind++;
400
401   if (optind >= argc)
402     {
403       error (0, 0, _("too few arguments"));
404       usage (EXIT_FAILURE);
405     }
406
407   changes = (reference_file ? mode_create_from_ref (reference_file)
408              : mode_compile (argv[modeind], MODE_MASK_ALL));
409
410   if (changes == MODE_INVALID)
411     error (EXIT_FAILURE, 0,
412            _("invalid mode string: %s"), quote (argv[modeind]));
413   else if (changes == MODE_MEMORY_EXHAUSTED)
414     xalloc_die ();
415   else if (changes == MODE_BAD_REFERENCE)
416     error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
417            quote (reference_file));
418
419   if (recurse && preserve_root)
420     {
421       static struct dev_ino dev_ino_buf;
422       root_dev_ino = get_root_dev_ino (&dev_ino_buf);
423       if (root_dev_ino == NULL)
424         error (EXIT_FAILURE, errno, _("failed to get attributes of %s"),
425                quote ("/"));
426     }
427   else
428     {
429       root_dev_ino = NULL;
430     }
431
432   for (; optind < argc; ++optind)
433     errors |= change_file_mode (argv[optind], changes, 1);
434
435   exit (errors);
436 }