accommodate older SELinux which lacks matchpathcon_init_prefix
[platform/upstream/coreutils.git] / src / install.c
1 /* install - copy files and set attributes
2    Copyright (C) 89, 90, 91, 1995-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
18
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <signal.h>
24 #include <pwd.h>
25 #include <grp.h>
26 #include <selinux/selinux.h>
27
28 #include "system.h"
29 #include "backupfile.h"
30 #include "error.h"
31 #include "cp-hash.h"
32 #include "copy.h"
33 #include "filenamecat.h"
34 #include "mkancesdirs.h"
35 #include "mkdir-p.h"
36 #include "modechange.h"
37 #include "prog-fprintf.h"
38 #include "quote.h"
39 #include "quotearg.h"
40 #include "savewd.h"
41 #include "stat-time.h"
42 #include "utimens.h"
43 #include "xstrtol.h"
44
45 /* The official name of this program (e.g., no `g' prefix).  */
46 #define PROGRAM_NAME "install"
47
48 #define AUTHORS proper_name ("David MacKenzie")
49
50 #if HAVE_SYS_WAIT_H
51 # include <sys/wait.h>
52 #endif
53
54 static int selinux_enabled = 0;
55 static bool use_default_selinux_context = true;
56
57 #if ! HAVE_ENDGRENT
58 # define endgrent() ((void) 0)
59 #endif
60
61 #if ! HAVE_ENDPWENT
62 # define endpwent() ((void) 0)
63 #endif
64
65 #if ! HAVE_LCHOWN
66 # define lchown(name, uid, gid) chown (name, uid, gid)
67 #endif
68
69 #if ! HAVE_MATCHPATHCON_INIT_PREFIX
70 # define matchpathcon_init_prefix(a, p) /* empty */
71 #endif
72
73 /* Initial number of entries in each hash table entry's table of inodes.  */
74 #define INITIAL_HASH_MODULE 100
75
76 /* Initial number of entries in the inode hash table.  */
77 #define INITIAL_ENTRY_TAB_SIZE 70
78
79 /* Number of bytes of a file to copy at a time. */
80 #define READ_SIZE (32 * 1024)
81
82 static bool change_timestamps (struct stat const *from_sb, char const *to);
83 static bool change_attributes (char const *name);
84 static bool copy_file (const char *from, const char *to,
85                        const struct cp_options *x);
86 static bool install_file_in_file_parents (char const *from, char *to,
87                                           struct cp_options *x);
88 static bool install_file_in_dir (const char *from, const char *to_dir,
89                                  const struct cp_options *x);
90 static bool install_file_in_file (const char *from, const char *to,
91                                   const struct cp_options *x);
92 static void get_ids (void);
93 static void strip (char const *name);
94 static void announce_mkdir (char const *dir, void *options);
95 static int make_ancestor (char const *dir, char const *component,
96                           void *options);
97 void usage (int status);
98
99 /* The name this program was run with, for error messages. */
100 char const *program_name;
101
102 /* The user name that will own the files, or NULL to make the owner
103    the current user ID. */
104 static char *owner_name;
105
106 /* The user ID corresponding to `owner_name'. */
107 static uid_t owner_id;
108
109 /* The group name that will own the files, or NULL to make the group
110    the current group ID. */
111 static char *group_name;
112
113 /* The group ID corresponding to `group_name'. */
114 static gid_t group_id;
115
116 #define DEFAULT_MODE (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
117
118 /* The file mode bits to which non-directory files will be set.  The umask has
119    no effect. */
120 static mode_t mode = DEFAULT_MODE;
121
122 /* Similar, but for directories.  */
123 static mode_t dir_mode = DEFAULT_MODE;
124
125 /* The file mode bits that the user cares about.  This should be a
126    superset of DIR_MODE and a subset of CHMOD_MODE_BITS.  This matters
127    for directories, since otherwise directories may keep their S_ISUID
128    or S_ISGID bits.  */
129 static mode_t dir_mode_bits = CHMOD_MODE_BITS;
130
131 /* If true, strip executable files after copying them. */
132 static bool strip_files;
133
134 /* If true, install a directory instead of a regular file. */
135 static bool dir_arg;
136
137 /* For long options that have no equivalent short option, use a
138    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
139 enum
140 {
141   PRESERVE_CONTEXT_OPTION = CHAR_MAX + 1
142 };
143
144 static struct option const long_options[] =
145 {
146   {"backup", optional_argument, NULL, 'b'},
147   {GETOPT_SELINUX_CONTEXT_OPTION_DECL},
148   {"directory", no_argument, NULL, 'd'},
149   {"group", required_argument, NULL, 'g'},
150   {"mode", required_argument, NULL, 'm'},
151   {"no-target-directory", no_argument, NULL, 'T'},
152   {"owner", required_argument, NULL, 'o'},
153   {"preserve-timestamps", no_argument, NULL, 'p'},
154   {"preserve-context", no_argument, NULL, PRESERVE_CONTEXT_OPTION},
155   /* Continue silent support for --preserve_context until Jan 2008. FIXME-obs
156      After that, FIXME-obs: warn in, say, late 2008, and disable altogether
157      a year or two later.  */
158   {"preserve_context", no_argument, NULL, PRESERVE_CONTEXT_OPTION},
159   {"strip", no_argument, NULL, 's'},
160   {"suffix", required_argument, NULL, 'S'},
161   {"target-directory", required_argument, NULL, 't'},
162   {"verbose", no_argument, NULL, 'v'},
163   {GETOPT_HELP_OPTION_DECL},
164   {GETOPT_VERSION_OPTION_DECL},
165   {NULL, 0, NULL, 0}
166 };
167
168 static void
169 cp_option_init (struct cp_options *x)
170 {
171   cp_options_default (x);
172   x->copy_as_regular = true;
173   x->dereference = DEREF_ALWAYS;
174   x->unlink_dest_before_opening = true;
175   x->unlink_dest_after_failed_open = false;
176   x->hard_link = false;
177   x->interactive = I_UNSPECIFIED;
178   x->move_mode = false;
179   x->one_file_system = false;
180   x->preserve_ownership = false;
181   x->preserve_links = false;
182   x->preserve_mode = false;
183   x->preserve_timestamps = false;
184   x->require_preserve = false;
185   x->require_preserve_context = false;
186   x->recursive = false;
187   x->sparse_mode = SPARSE_AUTO;
188   x->symbolic_link = false;
189   x->backup_type = no_backups;
190
191   /* Create destination files initially writable so we can run strip on them.
192      Although GNU strip works fine on read-only files, some others
193      would fail.  */
194   x->set_mode = true;
195   x->mode = S_IRUSR | S_IWUSR;
196   x->stdin_tty = false;
197
198   x->open_dangling_dest_symlink = false;
199   x->update = false;
200   x->preserve_security_context = false;
201   x->verbose = false;
202   x->dest_info = NULL;
203   x->src_info = NULL;
204 }
205
206 #ifdef ENABLE_MATCHPATHCON
207 /* Modify file context to match the specified policy.
208    If an error occurs the file will remain with the default directory
209    context.  */
210 static void
211 setdefaultfilecon (char const *file)
212 {
213   struct stat st;
214   security_context_t scontext = NULL;
215   static bool first_call = true;
216
217   if (selinux_enabled != 1)
218     {
219       /* Indicate no context found. */
220       return;
221     }
222   if (lstat (file, &st) != 0)
223     return;
224
225   if (first_call && IS_ABSOLUTE_FILE_NAME (file))
226     {
227       /* Calling matchpathcon_init_prefix (NULL, "/first_component/")
228          is an optimization to minimize the expense of the following
229          matchpathcon call.  Do it only once, just before the first
230          matchpathcon call.  We *could* call matchpathcon_fini after
231          the final matchpathcon call, but that's not necessary, since
232          by then we're about to exit, and besides, the buffers it
233          would free are still reachable.  */
234       char const *p0;
235       char const *p = file + 1;
236       while (ISSLASH (*p))
237         ++p;
238
239       /* Record final leading slash, for when FILE starts with two or more.  */
240       p0 = p - 1;
241
242       if (*p)
243         {
244           char *prefix;
245           do
246             {
247               ++p;
248             }
249           while (*p && !ISSLASH (*p));
250
251           prefix = malloc (p - p0 + 2);
252           if (prefix)
253             {
254               stpcpy (stpncpy (prefix, p0, p - p0), "/");
255               matchpathcon_init_prefix (NULL, prefix);
256               free (prefix);
257             }
258         }
259     }
260   first_call = false;
261
262   /* If there's an error determining the context, or it has none,
263      return to allow default context */
264   if ((matchpathcon (file, st.st_mode, &scontext) != 0) ||
265       STREQ (scontext, "<<none>>"))
266     {
267       if (scontext != NULL)
268         freecon (scontext);
269       return;
270     }
271
272   if (lsetfilecon (file, scontext) < 0 && errno != ENOTSUP)
273     error (0, errno,
274            _("warning: %s: failed to change context to %s"),
275            quotearg_colon (file), scontext);
276
277   freecon (scontext);
278   return;
279 }
280 #else
281 static void
282 setdefaultfilecon (char const *file)
283 {
284   (void) file;
285 }
286 #endif
287
288 /* FILE is the last operand of this command.  Return true if FILE is a
289    directory.  But report an error there is a problem accessing FILE,
290    or if FILE does not exist but would have to refer to an existing
291    directory if it referred to anything at all.  */
292
293 static bool
294 target_directory_operand (char const *file)
295 {
296   char const *b = last_component (file);
297   size_t blen = strlen (b);
298   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
299   struct stat st;
300   int err = (stat (file, &st) == 0 ? 0 : errno);
301   bool is_a_dir = !err && S_ISDIR (st.st_mode);
302   if (err && err != ENOENT)
303     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
304   if (is_a_dir < looks_like_a_dir)
305     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
306   return is_a_dir;
307 }
308
309 /* Process a command-line file name, for the -d option.  */
310 static int
311 process_dir (char *dir, struct savewd *wd, void *options)
312 {
313   return (make_dir_parents (dir, wd,
314                             make_ancestor, options,
315                             dir_mode, announce_mkdir,
316                             dir_mode_bits, owner_id, group_id, false)
317           ? EXIT_SUCCESS
318           : EXIT_FAILURE);
319 }
320
321 int
322 main (int argc, char **argv)
323 {
324   int optc;
325   int exit_status = EXIT_SUCCESS;
326   const char *specified_mode = NULL;
327   bool make_backups = false;
328   char *backup_suffix_string;
329   char *version_control_string = NULL;
330   bool mkdir_and_install = false;
331   struct cp_options x;
332   char const *target_directory = NULL;
333   bool no_target_directory = false;
334   int n_files;
335   char **file;
336   security_context_t scontext = NULL;
337   /* set iff kernel has extra selinux system calls */
338   selinux_enabled = (0 < is_selinux_enabled ());
339
340   initialize_main (&argc, &argv);
341   program_name = argv[0];
342   setlocale (LC_ALL, "");
343   bindtextdomain (PACKAGE, LOCALEDIR);
344   textdomain (PACKAGE);
345
346   atexit (close_stdin);
347
348   cp_option_init (&x);
349
350   owner_name = NULL;
351   group_name = NULL;
352   strip_files = false;
353   dir_arg = false;
354   umask (0);
355
356   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
357      we'll actually use backup_suffix_string.  */
358   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
359
360   while ((optc = getopt_long (argc, argv, "bcsDdg:m:o:pt:TvS:Z:", long_options,
361                               NULL)) != -1)
362     {
363       switch (optc)
364         {
365         case 'b':
366           make_backups = true;
367           if (optarg)
368             version_control_string = optarg;
369           break;
370         case 'c':
371           break;
372         case 's':
373           strip_files = true;
374 #ifdef SIGCHLD
375           /* System V fork+wait does not work if SIGCHLD is ignored.  */
376           signal (SIGCHLD, SIG_DFL);
377 #endif
378           break;
379         case 'd':
380           dir_arg = true;
381           break;
382         case 'D':
383           mkdir_and_install = true;
384           break;
385         case 'v':
386           x.verbose = true;
387           break;
388         case 'g':
389           group_name = optarg;
390           break;
391         case 'm':
392           specified_mode = optarg;
393           break;
394         case 'o':
395           owner_name = optarg;
396           break;
397         case 'p':
398           x.preserve_timestamps = true;
399           break;
400         case 'S':
401           make_backups = true;
402           backup_suffix_string = optarg;
403           break;
404         case 't':
405           if (target_directory)
406             error (EXIT_FAILURE, 0,
407                    _("multiple target directories specified"));
408           else
409             {
410               struct stat st;
411               if (stat (optarg, &st) != 0)
412                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
413               if (! S_ISDIR (st.st_mode))
414                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
415                        quote (optarg));
416             }
417           target_directory = optarg;
418           break;
419         case 'T':
420           no_target_directory = true;
421           break;
422
423         case PRESERVE_CONTEXT_OPTION:
424           if ( ! selinux_enabled)
425             {
426               error (0, 0, _("Warning: ignoring --preserve-context; "
427                              "this kernel is not SELinux-enabled."));
428               break;
429             }
430           x.preserve_security_context = true;
431           use_default_selinux_context = false;
432           break;
433         case 'Z':
434           if ( ! selinux_enabled)
435             {
436               error (0, 0, _("Warning: ignoring --context (-Z); "
437                              "this kernel is not SELinux-enabled."));
438               break;
439             }
440           scontext = optarg;
441           use_default_selinux_context = false;
442           break;
443         case_GETOPT_HELP_CHAR;
444         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
445         default:
446           usage (EXIT_FAILURE);
447         }
448     }
449
450   /* Check for invalid combinations of arguments. */
451   if (dir_arg & strip_files)
452     error (EXIT_FAILURE, 0,
453            _("the strip option may not be used when installing a directory"));
454   if (dir_arg && target_directory)
455     error (EXIT_FAILURE, 0,
456            _("target directory not allowed when installing a directory"));
457
458   if (x.preserve_security_context && scontext != NULL)
459     error (EXIT_FAILURE, 0,
460            _("cannot force target context to %s and preserve it"),
461            quote (scontext));
462
463   if (backup_suffix_string)
464     simple_backup_suffix = xstrdup (backup_suffix_string);
465
466   x.backup_type = (make_backups
467                    ? xget_version (_("backup type"),
468                                    version_control_string)
469                    : no_backups);
470
471   if (scontext && setfscreatecon (scontext) < 0)
472     error (EXIT_FAILURE, errno,
473            _("failed to set default file creation context to %s"),
474            quote (scontext));
475
476   n_files = argc - optind;
477   file = argv + optind;
478
479   if (n_files <= ! (dir_arg || target_directory))
480     {
481       if (n_files <= 0)
482         error (0, 0, _("missing file operand"));
483       else
484         error (0, 0, _("missing destination file operand after %s"),
485                quote (file[0]));
486       usage (EXIT_FAILURE);
487     }
488
489   if (no_target_directory)
490     {
491       if (target_directory)
492         error (EXIT_FAILURE, 0,
493                _("Cannot combine --target-directory (-t) "
494                  "and --no-target-directory (-T)"));
495       if (2 < n_files)
496         {
497           error (0, 0, _("extra operand %s"), quote (file[2]));
498           usage (EXIT_FAILURE);
499         }
500     }
501   else if (! (dir_arg || target_directory))
502     {
503       if (2 <= n_files && target_directory_operand (file[n_files - 1]))
504         target_directory = file[--n_files];
505       else if (2 < n_files)
506         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
507                quote (file[n_files - 1]));
508     }
509
510   if (specified_mode)
511     {
512       struct mode_change *change = mode_compile (specified_mode);
513       if (!change)
514         error (EXIT_FAILURE, 0, _("invalid mode %s"), quote (specified_mode));
515       mode = mode_adjust (0, false, 0, change, NULL);
516       dir_mode = mode_adjust (0, true, 0, change, &dir_mode_bits);
517       free (change);
518     }
519
520   get_ids ();
521
522   if (dir_arg)
523     exit_status = savewd_process_files (n_files, file, process_dir, &x);
524   else
525     {
526       /* FIXME: it's a little gross that this initialization is
527          required by copy.c::copy. */
528       hash_init ();
529
530       if (!target_directory)
531         {
532           if (! (mkdir_and_install
533                  ? install_file_in_file_parents (file[0], file[1], &x)
534                  : install_file_in_file (file[0], file[1], &x)))
535             exit_status = EXIT_FAILURE;
536         }
537       else
538         {
539           int i;
540           dest_info_init (&x);
541           for (i = 0; i < n_files; i++)
542             if (! install_file_in_dir (file[i], target_directory, &x))
543               exit_status = EXIT_FAILURE;
544         }
545     }
546
547   exit (exit_status);
548 }
549
550 /* Copy file FROM onto file TO, creating any missing parent directories of TO.
551    Return true if successful.  */
552
553 static bool
554 install_file_in_file_parents (char const *from, char *to,
555                               struct cp_options *x)
556 {
557   bool save_working_directory =
558     ! (IS_ABSOLUTE_FILE_NAME (from) && IS_ABSOLUTE_FILE_NAME (to));
559   int status = EXIT_SUCCESS;
560
561   struct savewd wd;
562   savewd_init (&wd);
563   if (! save_working_directory)
564     savewd_finish (&wd);
565
566   if (mkancesdirs (to, &wd, make_ancestor, x) == -1)
567     {
568       error (0, errno, _("cannot create directory %s"), to);
569       status = EXIT_FAILURE;
570     }
571
572   if (save_working_directory)
573     {
574       int restore_result = savewd_restore (&wd, status);
575       int restore_errno = errno;
576       savewd_finish (&wd);
577       if (EXIT_SUCCESS < restore_result)
578         return false;
579       if (restore_result < 0 && status == EXIT_SUCCESS)
580         {
581           error (0, restore_errno, _("cannot create directory %s"), to);
582           return false;
583         }
584     }
585
586   return (status == EXIT_SUCCESS && install_file_in_file (from, to, x));
587 }
588
589 /* Copy file FROM onto file TO and give TO the appropriate
590    attributes.
591    Return true if successful.  */
592
593 static bool
594 install_file_in_file (const char *from, const char *to,
595                       const struct cp_options *x)
596 {
597   struct stat from_sb;
598   if (x->preserve_timestamps && stat (from, &from_sb) != 0)
599     {
600       error (0, errno, _("cannot stat %s"), quote (from));
601       return false;
602     }
603   if (! copy_file (from, to, x))
604     return false;
605   if (strip_files)
606     strip (to);
607   if (x->preserve_timestamps && (strip_files || ! S_ISREG (from_sb.st_mode))
608       && ! change_timestamps (&from_sb, to))
609     return false;
610   return change_attributes (to);
611 }
612
613 /* Copy file FROM into directory TO_DIR, keeping its same name,
614    and give the copy the appropriate attributes.
615    Return true if successful.  */
616
617 static bool
618 install_file_in_dir (const char *from, const char *to_dir,
619                      const struct cp_options *x)
620 {
621   const char *from_base = last_component (from);
622   char *to = file_name_concat (to_dir, from_base, NULL);
623   bool ret = install_file_in_file (from, to, x);
624   free (to);
625   return ret;
626 }
627
628 /* Copy file FROM onto file TO, creating TO if necessary.
629    Return true if successful.  */
630
631 static bool
632 copy_file (const char *from, const char *to, const struct cp_options *x)
633 {
634   bool copy_into_self;
635
636   /* Allow installing from non-regular files like /dev/null.
637      Charles Karney reported that some Sun version of install allows that
638      and that sendmail's installation process relies on the behavior.
639      However, since !x->recursive, the call to "copy" will fail if FROM
640      is a directory.  */
641
642   return copy (from, to, false, x, &copy_into_self, NULL);
643 }
644
645 /* Set the attributes of file or directory NAME.
646    Return true if successful.  */
647
648 static bool
649 change_attributes (char const *name)
650 {
651   bool ok = false;
652   /* chown must precede chmod because on some systems,
653      chown clears the set[ug]id bits for non-superusers,
654      resulting in incorrect permissions.
655      On System V, users can give away files with chown and then not
656      be able to chmod them.  So don't give files away.
657
658      We don't normally ignore errors from chown because the idea of
659      the install command is that the file is supposed to end up with
660      precisely the attributes that the user specified (or defaulted).
661      If the file doesn't end up with the group they asked for, they'll
662      want to know.  */
663
664   if (! (owner_id == (uid_t) -1 && group_id == (gid_t) -1)
665       && lchown (name, owner_id, group_id) != 0)
666     error (0, errno, _("cannot change ownership of %s"), quote (name));
667   else if (chmod (name, mode) != 0)
668     error (0, errno, _("cannot change permissions of %s"), quote (name));
669   else
670     ok = true;
671
672   if (use_default_selinux_context)
673     setdefaultfilecon (name);
674
675   return ok;
676 }
677
678 /* Set the timestamps of file TO to match those of file FROM.
679    Return true if successful.  */
680
681 static bool
682 change_timestamps (struct stat const *from_sb, char const *to)
683 {
684   struct timespec timespec[2];
685   timespec[0] = get_stat_atime (from_sb);
686   timespec[1] = get_stat_mtime (from_sb);
687
688   if (utimens (to, timespec))
689     {
690       error (0, errno, _("cannot set time stamps for %s"), quote (to));
691       return false;
692     }
693   return true;
694 }
695
696 /* Strip the symbol table from the file NAME.
697    We could dig the magic number out of the file first to
698    determine whether to strip it, but the header files and
699    magic numbers vary so much from system to system that making
700    it portable would be very difficult.  Not worth the effort. */
701
702 static void
703 strip (char const *name)
704 {
705   int status;
706   pid_t pid = fork ();
707
708   switch (pid)
709     {
710     case -1:
711       error (EXIT_FAILURE, errno, _("fork system call failed"));
712       break;
713     case 0:                     /* Child. */
714       execlp ("strip", "strip", name, NULL);
715       error (EXIT_FAILURE, errno, _("cannot run strip"));
716       break;
717     default:                    /* Parent. */
718       if (waitpid (pid, &status, 0) < 0)
719         error (EXIT_FAILURE, errno, _("waiting for strip"));
720       else if (! WIFEXITED (status) || WEXITSTATUS (status))
721         error (EXIT_FAILURE, 0, _("strip process terminated abnormally"));
722       break;
723     }
724 }
725
726 /* Initialize the user and group ownership of the files to install. */
727
728 static void
729 get_ids (void)
730 {
731   struct passwd *pw;
732   struct group *gr;
733
734   if (owner_name)
735     {
736       pw = getpwnam (owner_name);
737       if (pw == NULL)
738         {
739           unsigned long int tmp;
740           if (xstrtoul (owner_name, NULL, 0, &tmp, NULL) != LONGINT_OK
741               || UID_T_MAX < tmp)
742             error (EXIT_FAILURE, 0, _("invalid user %s"), quote (owner_name));
743           owner_id = tmp;
744         }
745       else
746         owner_id = pw->pw_uid;
747       endpwent ();
748     }
749   else
750     owner_id = (uid_t) -1;
751
752   if (group_name)
753     {
754       gr = getgrnam (group_name);
755       if (gr == NULL)
756         {
757           unsigned long int tmp;
758           if (xstrtoul (group_name, NULL, 0, &tmp, NULL) != LONGINT_OK
759               || GID_T_MAX < tmp)
760             error (EXIT_FAILURE, 0, _("invalid group %s"), quote (group_name));
761           group_id = tmp;
762         }
763       else
764         group_id = gr->gr_gid;
765       endgrent ();
766     }
767   else
768     group_id = (gid_t) -1;
769 }
770
771 /* Report that directory DIR was made, if OPTIONS requests this.  */
772 static void
773 announce_mkdir (char const *dir, void *options)
774 {
775   struct cp_options const *x = options;
776   if (x->verbose)
777     prog_fprintf (stdout, _("creating directory %s"), quote (dir));
778 }
779
780 /* Make ancestor directory DIR, whose last file name component is
781    COMPONENT, with options OPTIONS.  Assume the working directory is
782    COMPONENT's parent.  */
783 static int
784 make_ancestor (char const *dir, char const *component, void *options)
785 {
786   int r = mkdir (component, DEFAULT_MODE);
787   if (r == 0)
788     announce_mkdir (dir, options);
789   return r;
790 }
791
792 void
793 usage (int status)
794 {
795   if (status != EXIT_SUCCESS)
796     fprintf (stderr, _("Try `%s --help' for more information.\n"),
797              program_name);
798   else
799     {
800       printf (_("\
801 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
802   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
803   or:  %s [OPTION]... -t DIRECTORY SOURCE...\n\
804   or:  %s [OPTION]... -d DIRECTORY...\n\
805 "),
806               program_name, program_name, program_name, program_name);
807       fputs (_("\
808 In the first three forms, copy SOURCE to DEST or multiple SOURCE(s) to\n\
809 the existing DIRECTORY, while setting permission modes and owner/group.\n\
810 In the 4th form, create all components of the given DIRECTORY(ies).\n\
811 \n\
812 "), stdout);
813       fputs (_("\
814 Mandatory arguments to long options are mandatory for short options too.\n\
815 "), stdout);
816       fputs (_("\
817       --backup[=CONTROL]  make a backup of each existing destination file\n\
818   -b                  like --backup but does not accept an argument\n\
819   -c                  (ignored)\n\
820   -d, --directory     treat all arguments as directory names; create all\n\
821                         components of the specified directories\n\
822 "), stdout);
823       fputs (_("\
824   -D                  create all leading components of DEST except the last,\n\
825                         then copy SOURCE to DEST\n\
826   -g, --group=GROUP   set group ownership, instead of process' current group\n\
827   -m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x\n\
828   -o, --owner=OWNER   set ownership (super-user only)\n\
829 "), stdout);
830       fputs (_("\
831   -p, --preserve-timestamps   apply access/modification times of SOURCE files\n\
832                         to corresponding destination files\n\
833   -s, --strip         strip symbol tables\n\
834   -S, --suffix=SUFFIX  override the usual backup suffix\n\
835   -t, --target-directory=DIRECTORY  copy all SOURCE arguments into DIRECTORY\n\
836   -T, --no-target-directory  treat DEST as a normal file\n\
837   -v, --verbose       print the name of each directory as it is created\n\
838 "), stdout);
839       fputs (_("\
840       --preserve-context  preserve SELinux security context\n\
841   -Z, --context=CONTEXT  set SELinux security context of files and directories\n\
842 "), stdout);
843
844       fputs (HELP_OPTION_DESCRIPTION, stdout);
845       fputs (VERSION_OPTION_DESCRIPTION, stdout);
846       fputs (_("\
847 \n\
848 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
849 The version control method may be selected via the --backup option or through\n\
850 the VERSION_CONTROL environment variable.  Here are the values:\n\
851 \n\
852 "), stdout);
853       fputs (_("\
854   none, off       never make backups (even if --backup is given)\n\
855   numbered, t     make numbered backups\n\
856   existing, nil   numbered if numbered backups exist, simple otherwise\n\
857   simple, never   always make simple backups\n\
858 "), stdout);
859       emit_bug_reporting_address ();
860     }
861   exit (status);
862 }