Fix bug reported today by Mike Frysinger: mkdir -pv is logging the
[platform/upstream/coreutils.git] / src / install.c
1 /* install - copy files and set attributes
2    Copyright (C) 89, 90, 91, 1995-2006 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #include <signal.h>
25 #include <pwd.h>
26 #include <grp.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 "quote.h"
38 #include "savewd.h"
39 #include "stat-time.h"
40 #include "utimens.h"
41 #include "xstrtol.h"
42
43 /* The official name of this program (e.g., no `g' prefix).  */
44 #define PROGRAM_NAME "install"
45
46 #define AUTHORS "David MacKenzie"
47
48 #if HAVE_SYS_WAIT_H
49 # include <sys/wait.h>
50 #endif
51
52 #if ! HAVE_ENDGRENT
53 # define endgrent() ((void) 0)
54 #endif
55
56 #if ! HAVE_ENDPWENT
57 # define endpwent() ((void) 0)
58 #endif
59
60 /* Initial number of entries in each hash table entry's table of inodes.  */
61 #define INITIAL_HASH_MODULE 100
62
63 /* Initial number of entries in the inode hash table.  */
64 #define INITIAL_ENTRY_TAB_SIZE 70
65
66 /* Number of bytes of a file to copy at a time. */
67 #define READ_SIZE (32 * 1024)
68
69 /* Options passed to subsidiary functions.  */
70 struct install_options
71 {
72   /* Full name of file being installed.  */
73   char const *full_name;
74
75   /* Options for cp-related code.  */
76   struct cp_options cp;
77 };
78
79 static bool change_timestamps (struct stat const *from_sb, char const *to);
80 static bool change_attributes (char const *name);
81 static bool copy_file (const char *from, const char *to,
82                        const struct cp_options *x);
83 static bool install_file_in_file_parents (char const *from, char *to,
84                                           struct install_options *x);
85 static bool install_file_in_dir (const char *from, const char *to_dir,
86                                  const struct cp_options *x);
87 static bool install_file_in_file (const char *from, const char *to,
88                                   const struct cp_options *x);
89 static void get_ids (void);
90 static void strip (char const *name);
91 static void announce_mkdir (char const *dir, void *options);
92 static int make_ancestor (char const *dir, void *options);
93 void usage (int status);
94
95 /* The name this program was run with, for error messages. */
96 char *program_name;
97
98 /* The user name that will own the files, or NULL to make the owner
99    the current user ID. */
100 static char *owner_name;
101
102 /* The user ID corresponding to `owner_name'. */
103 static uid_t owner_id;
104
105 /* The group name that will own the files, or NULL to make the group
106    the current group ID. */
107 static char *group_name;
108
109 /* The group ID corresponding to `group_name'. */
110 static gid_t group_id;
111
112 #define DEFAULT_MODE (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
113
114 /* The file mode bits to which non-directory files will be set.  The umask has
115    no effect. */
116 static mode_t mode = DEFAULT_MODE;
117
118 /* Similar, but for directories.  */
119 static mode_t dir_mode = DEFAULT_MODE;
120
121 /* The file mode bits that the user cares about.  This should be a
122    superset of DIR_MODE and a subset of CHMOD_MODE_BITS.  This matters
123    for directories, since otherwise directories may keep their S_ISUID
124    or S_ISGID bits.  */
125 static mode_t dir_mode_bits = CHMOD_MODE_BITS;
126
127 /* If true, strip executable files after copying them. */
128 static bool strip_files;
129
130 /* If true, install a directory instead of a regular file. */
131 static bool dir_arg;
132
133 static struct option const long_options[] =
134 {
135   {"backup", optional_argument, NULL, 'b'},
136   {"directory", no_argument, NULL, 'd'},
137   {"group", required_argument, NULL, 'g'},
138   {"mode", required_argument, NULL, 'm'},
139   {"no-target-directory", no_argument, NULL, 'T'},
140   {"owner", required_argument, NULL, 'o'},
141   {"preserve-timestamps", no_argument, NULL, 'p'},
142   {"strip", no_argument, NULL, 's'},
143   {"suffix", required_argument, NULL, 'S'},
144   {"target-directory", required_argument, NULL, 't'},
145   {"verbose", no_argument, NULL, 'v'},
146   {GETOPT_HELP_OPTION_DECL},
147   {GETOPT_VERSION_OPTION_DECL},
148   {NULL, 0, NULL, 0}
149 };
150
151 static void
152 cp_option_init (struct cp_options *x)
153 {
154   x->copy_as_regular = true;
155   x->dereference = DEREF_ALWAYS;
156   x->unlink_dest_before_opening = true;
157   x->unlink_dest_after_failed_open = false;
158   x->hard_link = false;
159   x->interactive = I_UNSPECIFIED;
160   x->move_mode = false;
161   x->chown_privileges = chown_privileges ();
162   x->one_file_system = false;
163   x->preserve_ownership = false;
164   x->preserve_links = false;
165   x->preserve_mode = false;
166   x->preserve_timestamps = false;
167   x->require_preserve = false;
168   x->recursive = false;
169   x->sparse_mode = SPARSE_AUTO;
170   x->symbolic_link = false;
171   x->backup_type = no_backups;
172
173   /* Create destination files initially writable so we can run strip on them.
174      Although GNU strip works fine on read-only files, some others
175      would fail.  */
176   x->set_mode = true;
177   x->mode = S_IRUSR | S_IWUSR;
178   x->stdin_tty = false;
179
180   x->update = false;
181   x->verbose = false;
182   x->dest_info = NULL;
183   x->src_info = NULL;
184 }
185
186 /* FILE is the last operand of this command.  Return true if FILE is a
187    directory.  But report an error there is a problem accessing FILE,
188    or if FILE does not exist but would have to refer to an existing
189    directory if it referred to anything at all.  */
190
191 static bool
192 target_directory_operand (char const *file)
193 {
194   char const *b = last_component (file);
195   size_t blen = strlen (b);
196   bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
197   struct stat st;
198   int err = (stat (file, &st) == 0 ? 0 : errno);
199   bool is_a_dir = !err && S_ISDIR (st.st_mode);
200   if (err && err != ENOENT)
201     error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
202   if (is_a_dir < looks_like_a_dir)
203     error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
204   return is_a_dir;
205 }
206
207 /* Process a command-line file name, for the -d option.  */
208 static int
209 process_dir (char *dir, struct savewd *wd, void *options)
210 {
211   struct install_options *o = options;
212   o->full_name = dir;
213   return (make_dir_parents (dir, wd,
214                             make_ancestor, options,
215                             dir_mode, announce_mkdir,
216                             dir_mode_bits, owner_id, group_id, false)
217           ? EXIT_SUCCESS
218           : EXIT_FAILURE);
219 }
220
221 int
222 main (int argc, char **argv)
223 {
224   int optc;
225   int exit_status = EXIT_SUCCESS;
226   const char *specified_mode = NULL;
227   bool make_backups = false;
228   char *backup_suffix_string;
229   char *version_control_string = NULL;
230   bool mkdir_and_install = false;
231   struct install_options x;
232   char const *target_directory = NULL;
233   bool no_target_directory = false;
234   int n_files;
235   char **file;
236
237   initialize_main (&argc, &argv);
238   program_name = argv[0];
239   setlocale (LC_ALL, "");
240   bindtextdomain (PACKAGE, LOCALEDIR);
241   textdomain (PACKAGE);
242
243   atexit (close_stdout);
244
245   cp_option_init (&x.cp);
246
247   owner_name = NULL;
248   group_name = NULL;
249   strip_files = false;
250   dir_arg = false;
251   umask (0);
252
253   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
254      we'll actually use backup_suffix_string.  */
255   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
256
257   while ((optc = getopt_long (argc, argv, "bcsDdg:m:o:pt:TvS:", long_options,
258                               NULL)) != -1)
259     {
260       switch (optc)
261         {
262         case 'b':
263           make_backups = true;
264           if (optarg)
265             version_control_string = optarg;
266           break;
267         case 'c':
268           break;
269         case 's':
270           strip_files = true;
271 #ifdef SIGCHLD
272           /* System V fork+wait does not work if SIGCHLD is ignored.  */
273           signal (SIGCHLD, SIG_DFL);
274 #endif
275           break;
276         case 'd':
277           dir_arg = true;
278           break;
279         case 'D':
280           mkdir_and_install = true;
281           break;
282         case 'v':
283           x.cp.verbose = true;
284           break;
285         case 'g':
286           group_name = optarg;
287           break;
288         case 'm':
289           specified_mode = optarg;
290           break;
291         case 'o':
292           owner_name = optarg;
293           break;
294         case 'p':
295           x.cp.preserve_timestamps = true;
296           break;
297         case 'S':
298           make_backups = true;
299           backup_suffix_string = optarg;
300           break;
301         case 't':
302           if (target_directory)
303             error (EXIT_FAILURE, 0,
304                    _("multiple target directories specified"));
305           else
306             {
307               struct stat st;
308               if (stat (optarg, &st) != 0)
309                 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
310               if (! S_ISDIR (st.st_mode))
311                 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
312                        quote (optarg));
313             }
314           target_directory = optarg;
315           break;
316         case 'T':
317           no_target_directory = true;
318           break;
319         case_GETOPT_HELP_CHAR;
320         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
321         default:
322           usage (EXIT_FAILURE);
323         }
324     }
325
326   /* Check for invalid combinations of arguments. */
327   if (dir_arg & strip_files)
328     error (EXIT_FAILURE, 0,
329            _("the strip option may not be used when installing a directory"));
330   if (dir_arg && target_directory)
331     error (EXIT_FAILURE, 0,
332            _("target directory not allowed when installing a directory"));
333
334   if (backup_suffix_string)
335     simple_backup_suffix = xstrdup (backup_suffix_string);
336
337   x.cp.backup_type = (make_backups
338                       ? xget_version (_("backup type"),
339                                       version_control_string)
340                       : no_backups);
341
342   n_files = argc - optind;
343   file = argv + optind;
344
345   if (n_files <= ! (dir_arg || target_directory))
346     {
347       if (n_files <= 0)
348         error (0, 0, _("missing file operand"));
349       else
350         error (0, 0, _("missing destination file operand after %s"),
351                quote (file[0]));
352       usage (EXIT_FAILURE);
353     }
354
355   if (no_target_directory)
356     {
357       if (target_directory)
358         error (EXIT_FAILURE, 0,
359                _("Cannot combine --target-directory (-t) "
360                  "and --no-target-directory (-T)"));
361       if (2 < n_files)
362         {
363           error (0, 0, _("extra operand %s"), quote (file[2]));
364           usage (EXIT_FAILURE);
365         }
366     }
367   else if (! (dir_arg || target_directory))
368     {
369       if (2 <= n_files && target_directory_operand (file[n_files - 1]))
370         target_directory = file[--n_files];
371       else if (2 < n_files)
372         error (EXIT_FAILURE, 0, _("target %s is not a directory"),
373                quote (file[n_files - 1]));
374     }
375
376   if (specified_mode)
377     {
378       struct mode_change *change = mode_compile (specified_mode);
379       if (!change)
380         error (EXIT_FAILURE, 0, _("invalid mode %s"), quote (specified_mode));
381       mode = mode_adjust (0, false, 0, change, NULL);
382       dir_mode = mode_adjust (0, true, 0, change, &dir_mode_bits);
383       free (change);
384     }
385
386   get_ids ();
387
388   if (dir_arg)
389     exit_status = savewd_process_files (n_files, file, process_dir, &x);
390   else
391     {
392       /* FIXME: it's a little gross that this initialization is
393          required by copy.c::copy. */
394       hash_init ();
395
396       if (!target_directory)
397         {
398           if (! (mkdir_and_install
399                  ? install_file_in_file_parents (file[0], file[1], &x)
400                  : install_file_in_file (file[0], file[1], &x.cp)))
401             exit_status = EXIT_FAILURE;
402         }
403       else
404         {
405           int i;
406           dest_info_init (&x.cp);
407           for (i = 0; i < n_files; i++)
408             if (! install_file_in_dir (file[i], target_directory, &x.cp))
409               exit_status = EXIT_FAILURE;
410         }
411     }
412
413   exit (exit_status);
414 }
415
416 /* Copy file FROM onto file TO, creating any missing parent directories of TO.
417    Return true if successful.  */
418
419 static bool
420 install_file_in_file_parents (char const *from, char *to,
421                               struct install_options *x)
422 {
423   bool save_working_directory =
424     ! (IS_ABSOLUTE_FILE_NAME (from) && IS_ABSOLUTE_FILE_NAME (to));
425   int status = EXIT_SUCCESS;
426
427   struct savewd wd;
428   savewd_init (&wd);
429   if (! save_working_directory)
430     savewd_finish (&wd);
431
432   if (mkancesdirs (to, &wd, make_ancestor, x) == -1)
433     {
434       error (0, errno, _("cannot create directory %s"), to);
435       status = EXIT_FAILURE;
436     }
437
438   if (save_working_directory)
439     {
440       int restore_result = savewd_restore (&wd, status);
441       int restore_errno = errno;
442       savewd_finish (&wd);
443       if (EXIT_SUCCESS < restore_result)
444         return false;
445       if (restore_result < 0 && status == EXIT_SUCCESS)
446         {
447           error (0, restore_errno, _("cannot create directory %s"), to);
448           return false;
449         }
450     }
451
452   return (status == EXIT_SUCCESS && install_file_in_file (from, to, &x->cp));
453 }
454
455 /* Copy file FROM onto file TO and give TO the appropriate
456    attributes.
457    Return true if successful.  */
458
459 static bool
460 install_file_in_file (const char *from, const char *to,
461                       const struct cp_options *x)
462 {
463   struct stat from_sb;
464   if (x->preserve_timestamps && stat (from, &from_sb) != 0)
465     {
466       error (0, errno, _("cannot stat %s"), quote (from));
467       return false;
468     }
469   if (! copy_file (from, to, x))
470     return false;
471   if (strip_files)
472     strip (to);
473   if (! change_attributes (to))
474     return false;
475   if (x->preserve_timestamps && (strip_files || ! S_ISREG (from_sb.st_mode)))
476     return change_timestamps (&from_sb, to);
477   return true;
478 }
479
480 /* Copy file FROM into directory TO_DIR, keeping its same name,
481    and give the copy the appropriate attributes.
482    Return true if successful.  */
483
484 static bool
485 install_file_in_dir (const char *from, const char *to_dir,
486                      const struct cp_options *x)
487 {
488   const char *from_base = last_component (from);
489   char *to = file_name_concat (to_dir, from_base, NULL);
490   bool ret = install_file_in_file (from, to, x);
491   free (to);
492   return ret;
493 }
494
495 /* Copy file FROM onto file TO, creating TO if necessary.
496    Return true if successful.  */
497
498 static bool
499 copy_file (const char *from, const char *to, const struct cp_options *x)
500 {
501   bool copy_into_self;
502
503   /* Allow installing from non-regular files like /dev/null.
504      Charles Karney reported that some Sun version of install allows that
505      and that sendmail's installation process relies on the behavior.
506      However, since !x->recursive, the call to "copy" will fail if FROM
507      is a directory.  */
508
509   return copy (from, to, false, x, &copy_into_self, NULL);
510 }
511
512 /* Set the attributes of file or directory NAME.
513    Return true if successful.  */
514
515 static bool
516 change_attributes (char const *name)
517 {
518   /* chown must precede chmod because on some systems,
519      chown clears the set[ug]id bits for non-superusers,
520      resulting in incorrect permissions.
521      On System V, users can give away files with chown and then not
522      be able to chmod them.  So don't give files away.
523
524      We don't normally ignore errors from chown because the idea of
525      the install command is that the file is supposed to end up with
526      precisely the attributes that the user specified (or defaulted).
527      If the file doesn't end up with the group they asked for, they'll
528      want to know.  */
529
530   if (! (owner_id == (uid_t) -1 && group_id == (gid_t) -1)
531       && chown (name, owner_id, group_id) != 0)
532     error (0, errno, _("cannot change ownership of %s"), quote (name));
533   else if (chmod (name, mode) != 0)
534     error (0, errno, _("cannot change permissions of %s"), quote (name));
535   else
536     return true;
537
538   return false;
539 }
540
541 /* Set the timestamps of file TO to match those of file FROM.
542    Return true if successful.  */
543
544 static bool
545 change_timestamps (struct stat const *from_sb, char const *to)
546 {
547   struct timespec timespec[2];
548   timespec[0] = get_stat_atime (from_sb);
549   timespec[1] = get_stat_mtime (from_sb);
550
551   if (utimens (to, timespec))
552     {
553       error (0, errno, _("cannot set time stamps for %s"), quote (to));
554       return false;
555     }
556   return true;
557 }
558
559 /* Strip the symbol table from the file NAME.
560    We could dig the magic number out of the file first to
561    determine whether to strip it, but the header files and
562    magic numbers vary so much from system to system that making
563    it portable would be very difficult.  Not worth the effort. */
564
565 static void
566 strip (char const *name)
567 {
568   int status;
569   pid_t pid = fork ();
570
571   switch (pid)
572     {
573     case -1:
574       error (EXIT_FAILURE, errno, _("fork system call failed"));
575       break;
576     case 0:                     /* Child. */
577       execlp ("strip", "strip", name, NULL);
578       error (EXIT_FAILURE, errno, _("cannot run strip"));
579       break;
580     default:                    /* Parent. */
581       /* Parent process. */
582       while (pid != wait (&status))     /* Wait for kid to finish. */
583         /* Do nothing. */ ;
584       if (status)
585         error (EXIT_FAILURE, 0, _("strip failed"));
586       break;
587     }
588 }
589
590 /* Initialize the user and group ownership of the files to install. */
591
592 static void
593 get_ids (void)
594 {
595   struct passwd *pw;
596   struct group *gr;
597
598   if (owner_name)
599     {
600       pw = getpwnam (owner_name);
601       if (pw == NULL)
602         {
603           unsigned long int tmp;
604           if (xstrtoul (owner_name, NULL, 0, &tmp, NULL) != LONGINT_OK
605               || UID_T_MAX < tmp)
606             error (EXIT_FAILURE, 0, _("invalid user %s"), quote (owner_name));
607           owner_id = tmp;
608         }
609       else
610         owner_id = pw->pw_uid;
611       endpwent ();
612     }
613   else
614     owner_id = (uid_t) -1;
615
616   if (group_name)
617     {
618       gr = getgrnam (group_name);
619       if (gr == NULL)
620         {
621           unsigned long int tmp;
622           if (xstrtoul (group_name, NULL, 0, &tmp, NULL) != LONGINT_OK
623               || GID_T_MAX < tmp)
624             error (EXIT_FAILURE, 0, _("invalid group %s"), quote (group_name));
625           group_id = tmp;
626         }
627       else
628         group_id = gr->gr_gid;
629       endgrent ();
630     }
631   else
632     group_id = (gid_t) -1;
633 }
634
635 /* Report that directory DIR was made, if OPTIONS requests this.  */
636 static void
637 announce_mkdir (char const *dir, void *options)
638 {
639   struct install_options const *x = options;
640   if (x->cp.verbose)
641     error (0, 0, _("creating directory %s"), quote (dir));
642 }
643
644 /* Make ancestor directory DIR, with options OPTIONS.  */
645 static int
646 make_ancestor (char const *dir, void *options)
647 {
648   struct install_options const *x = options;
649   int r = mkdir (dir, DEFAULT_MODE);
650   if (r == 0)
651     announce_mkdir (x->full_name, options);
652   return r;
653 }
654
655 void
656 usage (int status)
657 {
658   if (status != EXIT_SUCCESS)
659     fprintf (stderr, _("Try `%s --help' for more information.\n"),
660              program_name);
661   else
662     {
663       printf (_("\
664 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
665   or:  %s [OPTION]... SOURCE... DIRECTORY\n\
666   or:  %s [OPTION]... -t DIRECTORY SOURCE...\n\
667   or:  %s [OPTION]... -d DIRECTORY...\n\
668 "),
669               program_name, program_name, program_name, program_name);
670       fputs (_("\
671 In the first three forms, copy SOURCE to DEST or multiple SOURCE(s) to\n\
672 the existing DIRECTORY, while setting permission modes and owner/group.\n\
673 In the 4th form, create all components of the given DIRECTORY(ies).\n\
674 \n\
675 "), stdout);
676       fputs (_("\
677 Mandatory arguments to long options are mandatory for short options too.\n\
678 "), stdout);
679       fputs (_("\
680       --backup[=CONTROL]  make a backup of each existing destination file\n\
681   -b                  like --backup but does not accept an argument\n\
682   -c                  (ignored)\n\
683   -d, --directory     treat all arguments as directory names; create all\n\
684                         components of the specified directories\n\
685 "), stdout);
686       fputs (_("\
687   -D                  create all leading components of DEST except the last,\n\
688                         then copy SOURCE to DEST\n\
689   -g, --group=GROUP   set group ownership, instead of process' current group\n\
690   -m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x\n\
691   -o, --owner=OWNER   set ownership (super-user only)\n\
692 "), stdout);
693       fputs (_("\
694   -p, --preserve-timestamps   apply access/modification times of SOURCE files\n\
695                         to corresponding destination files\n\
696   -s, --strip         strip symbol tables\n\
697   -S, --suffix=SUFFIX override the usual backup suffix\n\
698   -t, --target-directory=DIRECTORY  copy all SOURCE arguments into DIRECTORY\n\
699   -T, --no-target-directory  treat DEST as a normal file\n\
700   -v, --verbose       print the name of each directory as it is created\n\
701 "), stdout);
702       fputs (HELP_OPTION_DESCRIPTION, stdout);
703       fputs (VERSION_OPTION_DESCRIPTION, stdout);
704       fputs (_("\
705 \n\
706 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
707 The version control method may be selected via the --backup option or through\n\
708 the VERSION_CONTROL environment variable.  Here are the values:\n\
709 \n\
710 "), stdout);
711       fputs (_("\
712   none, off       never make backups (even if --backup is given)\n\
713   numbered, t     make numbered backups\n\
714   existing, nil   numbered if numbered backups exist, simple otherwise\n\
715   simple, never   always make simple backups\n\
716 "), stdout);
717       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
718     }
719   exit (status);
720 }