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