(change_attributes): Don't remove the destination file upon failure.
[platform/upstream/coreutils.git] / src / install.c
1 /* install - copy files and set attributes
2    Copyright (C) 89, 90, 91, 1995-2000 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
17
18 /* Copy files and set their permission modes and, if possible,
19    their owner and group.  Used similarly to `cp'; typically
20    used in Makefiles to copy programs into their destination
21    directories.  It can also be used to create the destination
22    directories and any leading directories, and to set the final
23    directory's modes.  It refuses to copy files onto themselves.
24
25    Options:
26    -g, --group=GROUP
27         Set the group ownership of the installed file or directory
28         to the group ID of GROUP (default is process's current
29         group).  GROUP may also be a numeric group ID.
30
31    -m, --mode=MODE
32         Set the permission mode for the installed file or directory
33         to MODE, which is an octal number (default is u=rwx,g=rx,o=rx).
34
35    -o, --owner=OWNER
36         If run as root, set the ownership of the installed file to
37         the user ID of OWNER (default is root).  OWNER may also be
38         a numeric user ID.
39
40    -c   No effect.  For compatibility with old Unix versions of install.
41
42    -s, --strip
43         Strip the symbol tables from installed files.
44
45    -p, --preserve-timestamps
46         Retain creation and modification timestamps when installing files.
47
48    -d, --directory
49         Create a directory and its leading directories, if they
50         do not already exist.  Set the owner, group and mode
51         as given on the command line.  Any leading directories
52         that are created are also given those attributes.
53         This is different from the SunOS 4.0 install, which gives
54         directories that it creates the default attributes.
55
56   -D
57         Like the -d option, but a file is installed, along with the directory.
58         Useful when installing into a new directory, and the install
59         process doesn't properly comprehend making directories.
60
61    David MacKenzie <djm@gnu.ai.mit.edu> */
62
63 #ifdef _AIX
64  #pragma alloca
65 #endif
66
67 #include <config.h>
68 #include <stdio.h>
69 #include <getopt.h>
70 #include <sys/types.h>
71 #include <pwd.h>
72 #include <grp.h>
73
74 #include "system.h"
75 #include "backupfile.h"
76 #include "error.h"
77 #include "cp-hash.h"
78 #include "copy.h"
79 #include "dirname.h"
80 #include "makepath.h"
81 #include "modechange.h"
82 #include "path-concat.h"
83 #include "xstrtol.h"
84
85 /* The official name of this program (e.g., no `g' prefix).  */
86 #define PROGRAM_NAME "install"
87
88 #define AUTHORS "David MacKenzie"
89
90 #if HAVE_SYS_WAIT_H
91 # include <sys/wait.h>
92 #endif
93
94 #if HAVE_VALUES_H
95 # include <values.h>
96 #endif
97
98 struct passwd *getpwnam ();
99 struct group *getgrnam ();
100
101 #ifndef _POSIX_VERSION
102 uid_t getuid ();
103 gid_t getgid ();
104 #endif
105
106 #if ! HAVE_ENDGRENT
107 # define endgrent() ((void) 0)
108 #endif
109
110 #if ! HAVE_ENDPWENT
111 # define endpwent() ((void) 0)
112 #endif
113
114 /* Initial number of entries in each hash table entry's table of inodes.  */
115 #define INITIAL_HASH_MODULE 100
116
117 /* Initial number of entries in the inode hash table.  */
118 #define INITIAL_ENTRY_TAB_SIZE 70
119
120 /* Number of bytes of a file to copy at a time. */
121 #define READ_SIZE (32 * 1024)
122
123 int full_write ();
124 int isdir ();
125
126 int stat ();
127
128 static int change_timestamps PARAMS ((const char *from, const char *to));
129 static int change_attributes PARAMS ((const char *path));
130 static int copy_file PARAMS ((const char *from, const char *to,
131                               const struct cp_options *x));
132 static int install_file_to_path PARAMS ((const char *from, const char *to,
133                                          const struct cp_options *x));
134 static int install_file_in_dir PARAMS ((const char *from, const char *to_dir,
135                                         const struct cp_options *x));
136 static int install_file_in_file PARAMS ((const char *from, const char *to,
137                                          const struct cp_options *x));
138 static void get_ids PARAMS ((void));
139 static void strip PARAMS ((const char *path));
140 void usage PARAMS ((int status));
141
142 /* The name this program was run with, for error messages. */
143 char *program_name;
144
145 /* The user name that will own the files, or NULL to make the owner
146    the current user ID. */
147 static char *owner_name;
148
149 /* The user ID corresponding to `owner_name'. */
150 static uid_t owner_id;
151
152 /* The group name that will own the files, or NULL to make the group
153    the current group ID. */
154 static char *group_name;
155
156 /* The group ID corresponding to `group_name'. */
157 static gid_t group_id;
158
159 /* The permissions to which the files will be set.  The umask has
160    no effect. */
161 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
162
163 /* If nonzero, strip executable files after copying them. */
164 static int strip_files;
165
166 /* If nonzero, install a directory instead of a regular file. */
167 static int dir_arg;
168
169 static struct option const long_options[] =
170 {
171   {"backup", optional_argument, NULL, 'b'},
172   {"directory", no_argument, NULL, 'd'},
173   {"group", required_argument, NULL, 'g'},
174   {"mode", required_argument, NULL, 'm'},
175   {"owner", required_argument, NULL, 'o'},
176   {"preserve-timestamps", no_argument, NULL, 'p'},
177   {"strip", no_argument, NULL, 's'},
178   {"suffix", required_argument, NULL, 'S'},
179   {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
180   {"verbose", no_argument, NULL, 'v'},
181   {GETOPT_HELP_OPTION_DECL},
182   {GETOPT_VERSION_OPTION_DECL},
183   {NULL, 0, NULL, 0}
184 };
185
186 static void
187 cp_option_init (struct cp_options *x)
188 {
189   x->copy_as_regular = 1;
190   x->dereference = 1;
191   x->force = 1;
192
193   /* If unlink fails, try to proceed anyway.  */
194   x->failed_unlink_is_fatal = 0;
195
196   x->hard_link = 0;
197   x->interactive = 0;
198   x->move_mode = 0;
199   x->myeuid = geteuid ();
200   x->one_file_system = 0;
201   x->preserve_owner_and_group = 0;
202   x->preserve_chmod_bits = 0;
203   x->preserve_timestamps = 0;
204   x->require_preserve = 0;
205   x->recursive = 0;
206   x->sparse_mode = SPARSE_AUTO;
207   x->symbolic_link = 0;
208   x->backup_type = none;
209
210   /* Create destination files initially writable so we can run strip on them.
211      Although GNU strip works fine on read-only files, some others
212      would fail.  */
213   x->set_mode = 1;
214   x->mode = S_IRUSR | S_IWUSR;
215
216   x->umask_kill = 0;
217   x->update = 0;
218   x->verbose = 0;
219   x->xstat = stat;
220 }
221
222 int
223 main (int argc, char **argv)
224 {
225   int optc;
226   int errors = 0;
227   const char *symbolic_mode = NULL;
228   int make_backups = 0;
229   char *backup_suffix_string;
230   char *version_control_string = NULL;
231   int mkdir_and_install = 0;
232   struct cp_options x;
233   int n_files;
234   char **file;
235
236   program_name = argv[0];
237   setlocale (LC_ALL, "");
238   bindtextdomain (PACKAGE, LOCALEDIR);
239   textdomain (PACKAGE);
240
241   cp_option_init (&x);
242
243   owner_name = NULL;
244   group_name = NULL;
245   strip_files = 0;
246   dir_arg = 0;
247   umask (0);
248
249   /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
250      we'll actually use backup_suffix_string.  */
251   backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
252
253   while ((optc = getopt_long (argc, argv, "bcsDdg:m:o:pvV:S:", long_options,
254                               NULL)) != -1)
255     {
256       switch (optc)
257         {
258         case 0:
259           break;
260
261         case 'V':  /* FIXME: this is deprecated.  Remove it in 2001.  */
262           error (0, 0,
263                  _("warning: --version-control (-V) is obsolete;  support for\
264  it\nwill be removed in some future release.  Use --backup=%s instead."
265                    ), optarg);
266           /* Fall through.  */
267
268         case 'b':
269           make_backups = 1;
270           if (optarg)
271             version_control_string = optarg;
272           break;
273         case 'c':
274           break;
275         case 's':
276           strip_files = 1;
277           break;
278         case 'd':
279           dir_arg = 1;
280           break;
281         case 'D':
282           mkdir_and_install = 1;
283           break;
284         case 'v':
285           x.verbose = 1;
286           break;
287         case 'g':
288           group_name = optarg;
289           break;
290         case 'm':
291           symbolic_mode = optarg;
292           break;
293         case 'o':
294           owner_name = optarg;
295           break;
296         case 'p':
297           x.preserve_timestamps = 1;
298           break;
299         case 'S':
300           make_backups = 1;
301           backup_suffix_string = optarg;
302           break;
303         case_GETOPT_HELP_CHAR;
304         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
305         default:
306           usage (1);
307         }
308     }
309
310   /* Check for invalid combinations of arguments. */
311   if (dir_arg && strip_files)
312     error (1, 0,
313            _("the strip option may not be used when installing a directory"));
314
315   if (make_backups)
316     x.backup_type = xget_version ("backup type", version_control_string);
317
318   n_files = argc - optind;
319   file = argv + optind;
320
321   if (n_files == 0 || (n_files == 1 && !dir_arg))
322     {
323       error (0, 0, _("too few arguments"));
324       usage (1);
325     }
326
327   if (symbolic_mode)
328     {
329       struct mode_change *change = mode_compile (symbolic_mode, 0);
330       if (change == MODE_INVALID)
331         error (1, 0, _("invalid mode `%s'"), symbolic_mode);
332       else if (change == MODE_MEMORY_EXHAUSTED)
333         error (1, 0, _("virtual memory exhausted"));
334       mode = mode_adjust (0, change);
335     }
336
337   get_ids ();
338
339   if (dir_arg)
340     {
341       int i;
342       for (i = 0; i < n_files; i++)
343         {
344           errors |=
345             make_path (file[i], mode, mode, owner_id, group_id, 0,
346                        (x.verbose ? "creating directory `%s'" : NULL));
347         }
348     }
349   else
350     {
351       /* FIXME: it's a little gross that this initialization is
352          required by copy.c::copy. */
353       hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
354
355       if (n_files == 2)
356         {
357           if (mkdir_and_install)
358             errors = install_file_to_path (file[0], file[1], &x);
359           else if (!isdir (file[1]))
360             errors = install_file_in_file (file[0], file[1], &x);
361           else
362             errors = install_file_in_dir (file[0], file[1], &x);
363         }
364       else
365         {
366           int i;
367           const char *dest = file[n_files - 1];
368           if (!isdir (dest))
369             {
370               error (0, 0,
371                      _("installing multiple files, but last argument (%s) \
372 is not a directory"),
373                      dest);
374               usage (1);
375             }
376           for (i = 0; i < n_files - 1; i++)
377             {
378               errors |= install_file_in_dir (file[i], dest, &x);
379             }
380         }
381     }
382
383   if (x.verbose)
384     close_stdout ();
385   exit (errors);
386 }
387
388 /* Copy file FROM onto file TO, creating any missing parent directories of TO.
389    Return 0 if successful, 1 if an error occurs */
390
391 static int
392 install_file_to_path (const char *from, const char *to,
393                       const struct cp_options *x)
394 {
395   char *dest_dir;
396   int fail = 0;
397
398   dest_dir = dir_name (to);
399
400   /* check to make sure this is a path (not install a b ) */
401   if (!STREQ (dest_dir, ".")
402       && !isdir (dest_dir))
403     {
404       /* Someone will probably ask for a new option or three to specify
405          owner, group, and permissions for parent directories.  Remember
406          that this option is intended mainly to help installers when the
407          distribution doesn't provide proper install rules.  */
408 #define DIR_MODE (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
409       fail = make_path (dest_dir, DIR_MODE, DIR_MODE, owner_id, group_id, 0,
410                         (x->verbose ? _("creating directory `%s'") : NULL));
411     }
412
413   if (fail == 0)
414     fail = install_file_in_file (from, to, x);
415
416   free (dest_dir);
417
418   return fail;
419 }
420
421 /* Copy file FROM onto file TO and give TO the appropriate
422    attributes.
423    Return 0 if successful, 1 if an error occurs. */
424
425 static int
426 install_file_in_file (const char *from, const char *to,
427                       const struct cp_options *x)
428 {
429   if (copy_file (from, to, x))
430     return 1;
431   if (strip_files)
432     strip (to);
433   if (change_attributes (to))
434     return 1;
435   if (x->preserve_timestamps)
436     return change_timestamps (from, to);
437   return 0;
438 }
439
440 /* Copy file FROM into directory TO_DIR, keeping its same name,
441    and give the copy the appropriate attributes.
442    Return 0 if successful, 1 if not. */
443
444 static int
445 install_file_in_dir (const char *from, const char *to_dir,
446                      const struct cp_options *x)
447 {
448   const char *from_base;
449   char *to;
450   int ret;
451
452   from_base = base_name (from);
453   to = path_concat (to_dir, from_base, NULL);
454   ret = install_file_in_file (from, to, x);
455   free (to);
456   return ret;
457 }
458
459 /* Copy file FROM onto file TO, creating TO if necessary.
460    Return 0 if the copy is successful, 1 if not.  */
461
462 static int
463 copy_file (const char *from, const char *to, const struct cp_options *x)
464 {
465   int fail;
466   int nonexistent_dst = 0;
467   int copy_into_self;
468
469   /* Allow installing from non-regular files like /dev/null.
470      Charles Karney reported that some Sun version of install allows that
471      and that sendmail's installation process relies on the behavior.  */
472   if (isdir (from))
473     {
474       error (0, 0, _("`%s' is a directory"), from);
475       return 1;
476     }
477
478   fail = copy (from, to, nonexistent_dst, x, &copy_into_self, NULL);
479
480   return fail;
481 }
482
483 /* Set the attributes of file or directory PATH.
484    Return 0 if successful, 1 if not. */
485
486 static int
487 change_attributes (const char *path)
488 {
489   int err = 0;
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'", path);
511       err = 1;
512     }
513
514   if (!err && chmod (path, mode))
515     {
516       error (0, errno, "cannot change permissions of `%s'", path);
517       err = 1;
518     }
519
520   return err;
521 }
522
523 /* Set the timestamps of file TO to match those of file FROM.
524    Return 0 if successful, 1 if not. */
525
526 static int
527 change_timestamps (const char *from, const char *to)
528 {
529   struct stat stb;
530   struct utimbuf utb;
531
532   if (stat (from, &stb))
533     {
534       error (0, errno, "%s", from);
535       return 1;
536     }
537
538   /* There's currently no interface to set file timestamps with
539      better than 1-second resolution, so discard any fractional
540      part of the source timestamp.  */
541
542   utb.actime = stb.st_atime;
543   utb.modtime = stb.st_mtime;
544   if (utime (to, &utb))
545     {
546       error (0, errno, "%s", to);
547       return 1;
548     }
549   return 0;
550 }
551
552 /* Strip the symbol table from the file PATH.
553    We could dig the magic number out of the file first to
554    determine whether to strip it, but the header files and
555    magic numbers vary so much from system to system that making
556    it portable would be very difficult.  Not worth the effort. */
557
558 static void
559 strip (const char *path)
560 {
561   int status;
562   pid_t pid = fork ();
563
564   switch (pid)
565     {
566     case -1:
567       error (1, errno, _("cannot fork"));
568       break;
569     case 0:                     /* Child. */
570       execlp ("strip", "strip", path, NULL);
571       error (1, errno, _("cannot run strip"));
572       break;
573     default:                    /* Parent. */
574       /* Parent process. */
575       while (pid != wait (&status))     /* Wait for kid to finish. */
576         /* Do nothing. */ ;
577       if (status)
578         error (1, 0, _("strip failed"));
579       break;
580     }
581 }
582
583 /* Initialize the user and group ownership of the files to install. */
584
585 static void
586 get_ids (void)
587 {
588   struct passwd *pw;
589   struct group *gr;
590
591   if (owner_name)
592     {
593       pw = getpwnam (owner_name);
594       if (pw == NULL)
595         {
596           long int tmp_long;
597           if (xstrtol (owner_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
598               || tmp_long < 0 || tmp_long > UID_T_MAX)
599             error (1, 0, _("invalid user `%s'"), owner_name);
600           owner_id = (uid_t) tmp_long;
601         }
602       else
603         owner_id = pw->pw_uid;
604       endpwent ();
605     }
606   else
607     owner_id = (uid_t) -1;
608
609   if (group_name)
610     {
611       gr = getgrnam (group_name);
612       if (gr == NULL)
613         {
614           long int tmp_long;
615           if (xstrtol (group_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
616               || tmp_long < 0 || tmp_long > GID_T_MAX)
617             error (1, 0, _("invalid group `%s'"), group_name);
618           group_id = (gid_t) tmp_long;
619         }
620       else
621         group_id = gr->gr_gid;
622       endgrent ();
623     }
624   else
625     group_id = (gid_t) -1;
626 }
627
628 void
629 usage (int status)
630 {
631   if (status != 0)
632     fprintf (stderr, _("Try `%s --help' for more information.\n"),
633              program_name);
634   else
635     {
636       printf (_("\
637 Usage: %s [OPTION]... SOURCE DEST           (1st format)\n\
638   or:  %s [OPTION]... SOURCE... DIRECTORY   (2nd format)\n\
639   or:  %s -d [OPTION]... DIRECTORY...       (3rd format)\n\
640 "),
641               program_name, program_name, program_name);
642       printf (_("\
643 In the first two formats, copy SOURCE to DEST or multiple SOURCE(s) to\n\
644 the existing DIRECTORY, while setting permission modes and owner/group.\n\
645 In the third format, create all components of the given DIRECTORY(ies).\n\
646 \n\
647       --backup[=CONTROL] make a backup of each existing destination file\n\
648   -b                  like --backup but does not accept an argument\n\
649   -c                  (ignored)\n\
650   -d, --directory     treat all arguments as directory names; create all\n\
651                         components of the specified directories\n\
652   -D                  create all leading components of DEST except the last,\n\
653                         then copy SOURCE to DEST;  useful in the 1st format\n\
654   -g, --group=GROUP   set group ownership, instead of process' current group\n\
655   -m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x\n\
656   -o, --owner=OWNER   set ownership (super-user only)\n\
657   -p, --preserve-timestamps   apply access/modification times of SOURCE files\n\
658                         to corresponding destination files\n\
659   -s, --strip         strip symbol tables, only for 1st and 2nd formats\n\
660   -S, --suffix=SUFFIX override the usual backup suffix\n\
661       --verbose       print the name of each directory as it is created\n\
662       --help          display this help and exit\n\
663       --version       output version information and exit\n\
664 \n\
665 "));
666       printf (_("\
667 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
668 The version control method may be selected via the --backup option or through\n\
669 the VERSION_CONTROL environment variable.  Here are the values:\n\
670 \n\
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 "));
676       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
677       close_stdout ();
678     }
679   exit (status);
680 }