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