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