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