3a2e303c7a49abc77b7946300bf84665f9bf44fa
[platform/upstream/coreutils.git] / src / chgrp.c
1 /* chgrp -- change group ownership of files
2    Copyright (C) 89, 90, 91, 95, 1996 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 <sys/types.h>
23 #include <grp.h>
24 #include <getopt.h>
25
26 #if HAVE_LIMITS_H
27 # include <limits.h>
28 #endif
29
30 #ifndef UINT_MAX
31 # define UINT_MAX ((unsigned int) ~(unsigned int) 0)
32 #endif
33
34 #ifndef INT_MAX
35 # define INT_MAX ((int) (UINT_MAX >> 1))
36 #endif
37
38 #include "system.h"
39 #include "xstrtoul.h"
40 #include "error.h"
41
42 /* MAXUID may come from limits.h *or* sys/params.h (via system.h) above. */
43 #ifndef MAXUID
44 # define MAXUID INT_MAX
45 #endif
46
47 #ifndef _POSIX_VERSION
48 struct group *getgrnam ();
49 #endif
50
51 #ifndef HAVE_ENDGRENT
52 # define endgrent() ((void) 0)
53 #endif
54
55 #ifdef HAVE_LCHOWN
56 # define LCHOWN(FILE, OWNER, GROUP) lchown (FILE, OWNER, GROUP)
57 #else
58 # define LCHOWN(FILE, OWNER, GROUP) 1
59 #endif
60
61 char *group_member ();
62 char *savedir ();
63 char *xmalloc ();
64 char *xrealloc ();
65
66 static int change_dir_group __P ((const char *dir, int group,
67                                   const struct stat *statp));
68
69 /* The name the program was run with. */
70 char *program_name;
71
72 /* If nonzero, and the systems has support for it, change the ownership
73    of symbolic links rather than any files they point to.  */
74 static int change_symlinks;
75
76 /* If nonzero, change the ownership of directories recursively. */
77 static int recurse;
78
79 /* If nonzero, force silence (no error messages). */
80 static int force_silent;
81
82 /* If nonzero, describe the files we process. */
83 static int verbose;
84
85 /* If nonzero, describe only owners or groups that change. */
86 static int changes_only;
87
88 /* The name of the group to which ownership of the files is being given. */
89 static const char *groupname;
90
91 /* If nonzero, display usage information and exit.  */
92 static int show_help;
93
94 /* If nonzero, print the version on standard output and exit.  */
95 static int show_version;
96
97 static struct option const long_options[] =
98 {
99   {"recursive", no_argument, 0, 'R'},
100   {"changes", no_argument, 0, 'c'},
101   {"no-dereference", no_argument, 0, 'h'},
102   {"silent", no_argument, 0, 'f'},
103   {"quiet", no_argument, 0, 'f'},
104   {"verbose", no_argument, 0, 'v'},
105   {"help", no_argument, &show_help, 1},
106   {"version", no_argument, &show_version, 1},
107   {0, 0, 0, 0}
108 };
109
110 /* Tell the user the group name to which ownership of FILE
111    has been given; if CHANGED is zero, FILE was that group already. */
112
113 static void
114 describe_change (const char *file, int changed)
115 {
116   if (changed)
117     printf (_("group of %s changed to %s\n"), file, groupname);
118   else
119     printf (_("group of %s retained as %s\n"), file, groupname);
120 }
121
122 /* Set *G according to NAME. */
123
124 static void
125 parse_group (const char *name, int *g)
126 {
127   struct group *grp;
128
129   groupname = name;
130   if (*name == '\0')
131     error (1, 0, _("can not change to null group"));
132
133   grp = getgrnam (name);
134   if (grp == NULL)
135     {
136       strtol_error s_err;
137       unsigned long int tmp_long;
138
139       if (!ISDIGIT (*name))
140         error (1, 0, _("invalid group name `%s'"), name);
141
142       s_err = xstrtoul (name, NULL, 0, &tmp_long, NULL);
143       if (s_err != LONGINT_OK)
144         STRTOL_FATAL_ERROR (name, _("group number"), s_err);
145
146       if (tmp_long > INT_MAX)
147         error (1, 0, _("invalid group number `%s'"), name);
148
149       *g = tmp_long;
150     }
151   else
152     *g = grp->gr_gid;
153   endgrent ();          /* Save a file descriptor. */
154 }
155
156 /* Change the ownership of FILE to GID GROUP.
157    If it is a directory and -R is given, recurse.
158    Return 0 if successful, 1 if errors occurred. */
159
160 static int
161 change_file_group (const char *file, int group)
162 {
163   struct stat file_stats;
164   int errors = 0;
165
166   if (lstat (file, &file_stats))
167     {
168       if (force_silent == 0)
169         error (0, errno, "%s", file);
170       return 1;
171     }
172
173   if (group != file_stats.st_gid)
174     {
175       int fail;
176
177       if (verbose)
178         describe_change (file, 1);
179
180       if (change_symlinks)
181         fail = LCHOWN (file, file_stats.st_uid, group);
182       else
183         fail = chown (file, file_stats.st_uid, group);
184
185       if (fail)
186         {
187           errors = 1;
188           if (force_silent == 0)
189             {
190               /* Give a more specific message.  Some systems set errno
191                  to EPERM for both `inaccessible file' and `user not a member
192                  of the specified group' errors.  */
193               if (errno == EPERM && !group_member (group))
194                 {
195                   error (0, errno, _("you are not a member of group `%s'"),
196                          groupname);
197                 }
198               else if (errno == EINVAL && group > MAXUID)
199                 {
200                   error (0, 0, _("%s: invalid group number"), groupname);
201                 }
202               else
203                 {
204                   error (0, errno, "%s", file);
205                 }
206             }
207         }
208     }
209   else if (verbose && changes_only == 0)
210     describe_change (file, 0);
211
212   if (recurse && S_ISDIR (file_stats.st_mode))
213     errors |= change_dir_group (file, group, &file_stats);
214   return errors;
215 }
216
217 /* Recursively change the ownership of the files in directory DIR
218    to GID GROUP.
219    STATP points to the results of lstat on DIR.
220    Return 0 if successful, 1 if errors occurred. */
221
222 static int
223 change_dir_group (const char *dir, int group, const struct stat *statp)
224 {
225   char *name_space, *namep;
226   char *path;                   /* Full path of each entry to process. */
227   unsigned dirlength;           /* Length of `dir' and '\0'. */
228   unsigned filelength;          /* Length of each pathname to process. */
229   unsigned pathlength;          /* Bytes allocated for `path'. */
230   int errors = 0;
231
232   errno = 0;
233   name_space = savedir (dir, statp->st_size);
234   if (name_space == NULL)
235     {
236       if (errno)
237         {
238           if (force_silent == 0)
239             error (0, errno, "%s", dir);
240           return 1;
241         }
242       else
243         error (1, 0, _("virtual memory exhausted"));
244     }
245
246   dirlength = strlen (dir) + 1; /* + 1 is for the trailing '/'. */
247   pathlength = dirlength + 1;
248   /* Give `path' a dummy value; it will be reallocated before first use. */
249   path = xmalloc (pathlength);
250   strcpy (path, dir);
251   path[dirlength - 1] = '/';
252
253   for (namep = name_space; *namep; namep += filelength - dirlength)
254     {
255       filelength = dirlength + strlen (namep) + 1;
256       if (filelength > pathlength)
257         {
258           pathlength = filelength * 2;
259           path = xrealloc (path, pathlength);
260         }
261       strcpy (path + dirlength, namep);
262       errors |= change_file_group (path, group);
263     }
264   free (path);
265   free (name_space);
266   return errors;
267 }
268
269 static void
270 usage (int status)
271 {
272   if (status != 0)
273     fprintf (stderr, _("Try `%s --help' for more information.\n"),
274              program_name);
275   else
276     {
277       printf (_("Usage: %s [OPTION]... GROUP FILE...\n"), program_name);
278       printf (_("\
279 Change the group membership of each FILE to GROUP.\n\
280 \n\
281   -c, --changes           like verbose but report only when a change is made\n\
282   -h, --no-dereference    affect symbolic links instead of any referenced file\n\
283                           (available only on systems with lchown system call)\n\
284   -f, --silent, --quiet   suppress most error messages\n\
285   -v, --verbose           output a diagnostic for every file processed\n\
286   -R, --recursive         change files and directories recursively\n\
287       --help              display this help and exit\n\
288       --version           output version information and exit\n\
289 "));
290       puts (_("\nReport bugs to bug-gnu-utils@gnu.ai.mit.edu"));
291     }
292   exit (status);
293 }
294
295 int
296 main (int argc, char **argv)
297 {
298   int group;
299   int errors = 0;
300   int optc;
301
302   program_name = argv[0];
303   setlocale (LC_ALL, "");
304   bindtextdomain (PACKAGE, LOCALEDIR);
305   textdomain (PACKAGE);
306
307   recurse = force_silent = verbose = changes_only = 0;
308
309   while ((optc = getopt_long (argc, argv, "Rcfhv", long_options, (int *) 0))
310          != EOF)
311     {
312       switch (optc)
313         {
314         case 0:
315           break;
316         case 'R':
317           recurse = 1;
318           break;
319         case 'c':
320           verbose = 1;
321           changes_only = 1;
322           break;
323         case 'f':
324           force_silent = 1;
325           break;
326         case 'h':
327           change_symlinks = 1;
328           break;
329         case 'v':
330           verbose = 1;
331           break;
332         default:
333           usage (1);
334         }
335     }
336
337   if (show_version)
338     {
339       printf ("chgrp - %s\n", PACKAGE_VERSION);
340       exit (0);
341     }
342
343   if (show_help)
344     usage (0);
345
346   if (argc - optind <= 1)
347     {
348       error (0, 0, _("too few arguments"));
349       usage (1);
350     }
351
352 #ifndef HAVE_LCHOWN
353   if (change_symlinks)
354     {
355       error (1, 0, _("--no-dereference (-h) is not supported on this system"));
356     }
357 #endif
358
359   parse_group (argv[optind++], &group);
360
361   for (; optind < argc; ++optind)
362     errors |= change_file_group (argv[optind], group);
363
364   exit (errors);
365 }