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