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