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