(install_file_to_path): Copy the file after creating any leading directories.
[platform/upstream/coreutils.git] / src / install.c
1 /* install - copy files and set attributes
2    Copyright (C) 89, 90, 91, 95, 96, 97, 1998 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 0755).
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 "modechange.h"
77 #include "makepath.h"
78 #include "closeout.h"
79 #include "error.h"
80 #include "xstrtol.h"
81 #include "path-concat.h"
82 #include "cp-hash.h"
83 #include "copy.h"
84
85 #if HAVE_SYS_WAIT_H
86 # include <sys/wait.h>
87 #endif
88
89 #if HAVE_VALUES_H
90 # include <values.h>
91 #endif
92
93 struct passwd *getpwnam ();
94 struct group *getgrnam ();
95
96 #ifndef _POSIX_VERSION
97 uid_t getuid ();
98 gid_t getgid ();
99 #endif
100
101 #if ! HAVE_ENDGRENT
102 # define endgrent() ((void) 0)
103 #endif
104
105 #if ! HAVE_ENDPWENT
106 # define endpwent() ((void) 0)
107 #endif
108
109 /* Initial number of entries in each hash table entry's table of inodes.  */
110 #define INITIAL_HASH_MODULE 100
111
112 /* Initial number of entries in the inode hash table.  */
113 #define INITIAL_ENTRY_TAB_SIZE 70
114
115 /* True if C is an ASCII octal digit. */
116 #define isodigit(c) ((c) >= '0' && c <= '7')
117
118 /* Number of bytes of a file to copy at a time. */
119 #define READ_SIZE (32 * 1024)
120
121 #ifndef UID_T_MAX
122 # define UID_T_MAX TYPE_MAXIMUM (uid_t)
123 #endif
124
125 #ifndef GID_T_MAX
126 # define GID_T_MAX TYPE_MAXIMUM (gid_t)
127 #endif
128
129 char *base_name ();
130 char *dirname ();
131 int full_write ();
132 int isdir ();
133 enum backup_type get_version ();
134
135 int stat ();
136
137 static int change_timestamps PARAMS ((const char *from, const char *to));
138 static int change_attributes PARAMS ((const char *path));
139 static int copy_file PARAMS ((const char *from, const char *to,
140                               const struct cp_options *x));
141 static int install_file_to_path PARAMS ((const char *from, const char *to,
142                                          const struct cp_options *x));
143 static int install_file_in_dir PARAMS ((const char *from, const char *to_dir,
144                                         const struct cp_options *x));
145 static int install_file_in_file PARAMS ((const char *from, const char *to,
146                                          const struct cp_options *x));
147 static void get_ids PARAMS ((void));
148 static void strip PARAMS ((const char *path));
149 static void usage PARAMS ((int status));
150
151 /* The name this program was run with, for error messages. */
152 char *program_name;
153
154 /* FIXME: document */
155 enum backup_type backup_type;
156
157 /* The user name that will own the files, or NULL to make the owner
158    the current user ID. */
159 static char *owner_name;
160
161 /* The user ID corresponding to `owner_name'. */
162 static uid_t owner_id;
163
164 /* The group name that will own the files, or NULL to make the group
165    the current group ID. */
166 static char *group_name;
167
168 /* The group ID corresponding to `group_name'. */
169 static gid_t group_id;
170
171 /* The permissions to which the files will be set.  The umask has
172    no effect. */
173 static mode_t mode = 0755;
174
175 /* If nonzero, strip executable files after copying them. */
176 static int strip_files;
177
178 /* If nonzero, install a directory instead of a regular file. */
179 static int dir_arg;
180
181 /* If nonzero, display usage information and exit.  */
182 static int show_help;
183
184 /* If nonzero, print the version on standard output and exit.  */
185 static int show_version;
186
187 static struct option const long_options[] =
188 {
189   {"strip", no_argument, NULL, 's'},
190   {"directory", no_argument, NULL, 'd'},
191   {"group", required_argument, NULL, 'g'},
192   {"mode", required_argument, NULL, 'm'},
193   {"owner", required_argument, NULL, 'o'},
194   {"preserve-timestamps", no_argument, NULL, 'p'},
195   {"backup", no_argument, NULL, 'b'},
196   {"version-control", required_argument, NULL, 'V'},
197   {"verbose", no_argument, NULL, 'v'},
198   {"help", no_argument, &show_help, 1},
199   {"version", no_argument, &show_version, 1},
200   {NULL, 0, NULL, 0}
201 };
202
203 static void
204 cp_option_init (struct cp_options *x)
205 {
206   x->copy_as_regular = 1;
207   x->dereference = 1;
208   x->force = 1;
209
210   /* If unlink fails, try to proceed anyway.  */
211   x->failed_unlink_is_fatal = 0;
212
213   x->hard_link = 0;
214   x->interactive = 0;
215   x->move_mode = 0;
216   x->myeuid = geteuid ();
217   x->one_file_system = 0;
218   x->preserve_owner_and_group = 0;
219   x->preserve_chmod_bits = 0;
220   x->preserve_timestamps = 0;
221   x->require_preserve = 0;
222   x->recursive = 0;
223   x->sparse_mode = SPARSE_AUTO;
224   x->symbolic_link = 0;
225
226   /* Create destination files initially writable so we can run strip on them.
227      Although GNU strip works fine on read-only files, some others
228      would fail.  */
229   x->set_mode = 1;
230   x->mode = 0600;
231
232   x->umask_kill = 0;
233   x->update = 0;
234   x->verbose = 0;
235   x->xstat = stat;
236 }
237
238 int
239 main (int argc, char **argv)
240 {
241   int optc;
242   int errors = 0;
243   char *symbolic_mode = NULL;
244   int make_backups = 0;
245   char *version;
246   int mkdir_and_install = 0;
247   struct cp_options x;
248   int n_files;
249   char **file;
250
251   program_name = argv[0];
252   setlocale (LC_ALL, "");
253   bindtextdomain (PACKAGE, LOCALEDIR);
254   textdomain (PACKAGE);
255
256   cp_option_init (&x);
257
258   owner_name = NULL;
259   group_name = NULL;
260   strip_files = 0;
261   dir_arg = 0;
262   umask (0);
263
264   version = getenv ("SIMPLE_BACKUP_SUFFIX");
265   if (version)
266     simple_backup_suffix = version;
267   version = getenv ("VERSION_CONTROL");
268
269   while ((optc = getopt_long (argc, argv, "bcsDdg:m:o:pvV:S:", long_options,
270                               NULL)) != -1)
271     {
272       switch (optc)
273         {
274         case 0:
275           break;
276         case 'b':
277           make_backups = 1;
278           break;
279         case 'c':
280           break;
281         case 's':
282           strip_files = 1;
283           break;
284         case 'd':
285           dir_arg = 1;
286           break;
287         case 'D':
288           mkdir_and_install = 1;
289           break;
290         case 'v':
291           x.verbose = 1;
292           break;
293         case 'g':
294           group_name = optarg;
295           break;
296         case 'm':
297           symbolic_mode = optarg;
298           break;
299         case 'o':
300           owner_name = optarg;
301           break;
302         case 'p':
303           x.preserve_timestamps = 1;
304           break;
305         case 'S':
306           simple_backup_suffix = optarg;
307           break;
308         case 'V':
309           version = optarg;
310           break;
311         default:
312           usage (1);
313         }
314     }
315
316   if (show_version)
317     {
318       printf ("install (%s) %s\n", GNU_PACKAGE, VERSION);
319       close_stdout ();
320       exit (0);
321     }
322
323   if (show_help)
324     usage (0);
325
326   /* Check for invalid combinations of arguments. */
327   if (dir_arg && strip_files)
328     error (1, 0,
329            _("the strip option may not be used when installing a directory"));
330
331   x.backup_type = (make_backups ? get_version (version) : none);
332
333   n_files = argc - optind;
334   file = argv + optind;
335
336   if (n_files == 0 || (n_files == 1 && !dir_arg))
337     {
338       error (0, 0, _("too few arguments"));
339       usage (1);
340     }
341
342   if (symbolic_mode)
343     {
344       struct mode_change *change = mode_compile (symbolic_mode, 0);
345       if (change == MODE_INVALID)
346         error (1, 0, _("invalid mode `%s'"), symbolic_mode);
347       else if (change == MODE_MEMORY_EXHAUSTED)
348         error (1, 0, _("virtual memory exhausted"));
349       mode = mode_adjust (0, change);
350     }
351
352   get_ids ();
353
354   if (dir_arg)
355     {
356       int i;
357       for (i = 0; i < n_files; i++)
358         {
359           errors |=
360             make_path (file[i], mode, mode, owner_id, group_id, 0,
361                        (x.verbose ? "creating directory `%s'" : NULL));
362         }
363     }
364   else
365     {
366       /* FIXME: it's a little gross that this initialization is
367          required by copy.c::copy. */
368       hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
369
370       if (n_files == 2)
371         {
372           if (mkdir_and_install)
373             errors = install_file_to_path (file[0], file[1], &x);
374           else if (!isdir (file[1]))
375             errors = install_file_in_file (file[0], file[1], &x);
376           else
377             errors = install_file_in_dir (file[0], file[1], &x);
378         }
379       else
380         {
381           int i;
382           const char *dest = file[n_files - 1];
383           if (!isdir (dest))
384             {
385               error (0, 0,
386                      _("installing multiple files, but last argument (%s) \
387 is not a directory"),
388                      dest);
389               usage (1);
390             }
391           for (i = 0; i < n_files - 1; i++)
392             {
393               errors |= install_file_in_dir (file[i], dest, &x);
394             }
395         }
396     }
397
398   if (x.verbose)
399     close_stdout ();
400   exit (errors);
401 }
402
403 /* Copy file FROM onto file TO, creating any missing parent directories of TO.
404    Return 0 if successful, 1 if an error occurs */
405
406 static int
407 install_file_to_path (const char *from, const char *to,
408                       const struct cp_options *x)
409 {
410   char *dest_dir;
411   int fail;
412
413   dest_dir = dirname (to);
414
415   /* check to make sure this is a path (not install a b ) */
416   if (!STREQ (dest_dir, ".")
417       && !isdir (dest_dir))
418     {
419       /* FIXME: Note that it's a little kludgey (even dangerous) that we
420          derive the permissions for parent directories from the permissions
421          specfied for the file, but since this option is intended mainly to
422          help installers when the distribution doesn't provide proper install
423          rules, it's not so bad.  Maybe use something like this instead:
424          int parent_dir_mode = (mode | (S_IRUGO | S_IXUGO)) & (~SPECIAL_BITS);
425          */
426       fail = make_path (dest_dir, mode, mode, owner_id, group_id, 0,
427                         (x->verbose ? _("creating directory `%s'") : NULL));
428
429       if (fail == 0)
430         fail = install_file_in_dir (from, dest_dir, x);
431     }
432   else
433     {
434       fail = install_file_in_file (from, to, x);
435     }
436
437   free (dest_dir);
438
439   return fail;
440 }
441
442 /* Copy file FROM onto file TO and give TO the appropriate
443    attributes.
444    Return 0 if successful, 1 if an error occurs. */
445
446 static int
447 install_file_in_file (const char *from, const char *to,
448                       const struct cp_options *x)
449 {
450   if (copy_file (from, to, x))
451     return 1;
452   if (strip_files)
453     strip (to);
454   if (change_attributes (to))
455     return 1;
456   if (x->preserve_timestamps)
457     return change_timestamps (from, to);
458   return 0;
459 }
460
461 /* Copy file FROM into directory TO_DIR, keeping its same name,
462    and give the copy the appropriate attributes.
463    Return 0 if successful, 1 if not. */
464
465 static int
466 install_file_in_dir (const char *from, const char *to_dir,
467                      const struct cp_options *x)
468 {
469   char *from_base;
470   char *to;
471   int ret;
472
473   from_base = base_name (from);
474   to = path_concat (to_dir, from_base, NULL);
475   ret = install_file_in_file (from, to, x);
476   free (to);
477   return ret;
478 }
479
480 /* Copy file FROM onto file TO, creating TO if necessary.
481    Return 0 if the copy is successful, 1 if not.  */
482
483 static int
484 copy_file (const char *from, const char *to, const struct cp_options *x)
485 {
486   int fail;
487   int nonexistent_dst = 0;
488   int copy_into_self;
489
490   /* Allow installing from non-regular files like /dev/null.
491      Charles Karney reported that some Sun version of install allows that
492      and that sendmail's installation process relies on the behavior.  */
493   if (isdir (from))
494     {
495       error (0, 0, _("`%s' is a directory"), from);
496       return 1;
497     }
498
499   fail = copy (from, to, nonexistent_dst, x, &copy_into_self, NULL);
500
501   return fail;
502 }
503
504 /* Set the attributes of file or directory PATH.
505    Return 0 if successful, 1 if not. */
506
507 static int
508 change_attributes (const char *path)
509 {
510   int err = 0;
511
512   /* chown must precede chmod because on some systems,
513      chown clears the set[ug]id bits for non-superusers,
514      resulting in incorrect permissions.
515      On System V, users can give away files with chown and then not
516      be able to chmod them.  So don't give files away.
517
518      We don't normally ignore errors from chown because the idea of
519      the install command is that the file is supposed to end up with
520      precisely the attributes that the user specified (or defaulted).
521      If the file doesn't end up with the group they asked for, they'll
522      want to know.  But AFS returns EPERM when you try to change a
523      file's group; thus the kludge.  */
524
525   if (chown (path, owner_id, group_id)
526 #ifdef AFS
527       && errno != EPERM
528 #endif
529       )
530     err = errno;
531   if (chmod (path, mode))
532     err = errno;
533   if (err)
534     {
535       error (0, err, "%s", path);
536       return 1;
537     }
538   return 0;
539 }
540
541 /* Set the timestamps of file TO to match those of file FROM.
542    Return 0 if successful, 1 if not. */
543
544 static int
545 change_timestamps (const char *from, const char *to)
546 {
547   struct stat stb;
548   struct utimbuf utb;
549
550   if (stat (from, &stb))
551     {
552       error (0, errno, "%s", from);
553       return 1;
554     }
555
556   /* There's currently no interface to set file timestamps with
557      better than 1-second resolution, so discard any fractional
558      part of the source timestamp.  */
559
560   utb.actime = stb.st_atime;
561   utb.modtime = stb.st_mtime;
562   if (utime (to, &utb))
563     {
564       error (0, errno, "%s", to);
565       return 1;
566     }
567   return 0;
568 }
569
570 /* Strip the symbol table from the file PATH.
571    We could dig the magic number out of the file first to
572    determine whether to strip it, but the header files and
573    magic numbers vary so much from system to system that making
574    it portable would be very difficult.  Not worth the effort. */
575
576 static void
577 strip (const char *path)
578 {
579   int pid, status;
580
581   pid = fork ();
582   switch (pid)
583     {
584     case -1:
585       error (1, errno, _("fork system call failed"));
586       break;
587     case 0:                     /* Child. */
588       execlp ("strip", "strip", path, NULL);
589       error (1, errno, _("cannot run strip"));
590       break;
591     default:                    /* Parent. */
592       /* Parent process. */
593       while (pid != wait (&status))     /* Wait for kid to finish. */
594         /* Do nothing. */ ;
595       break;
596     }
597 }
598
599 /* Initialize the user and group ownership of the files to install. */
600
601 static void
602 get_ids (void)
603 {
604   struct passwd *pw;
605   struct group *gr;
606
607   if (owner_name)
608     {
609       pw = getpwnam (owner_name);
610       if (pw == NULL)
611         {
612           long int tmp_long;
613           if (xstrtol (owner_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
614               || tmp_long < 0 || tmp_long > UID_T_MAX)
615             error (1, 0, _("invalid user `%s'"), owner_name);
616           owner_id = (uid_t) tmp_long;
617         }
618       else
619         owner_id = pw->pw_uid;
620       endpwent ();
621     }
622   else
623     owner_id = (uid_t) -1;
624
625   if (group_name)
626     {
627       gr = getgrnam (group_name);
628       if (gr == NULL)
629         {
630           long int tmp_long;
631           if (xstrtol (group_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
632               || tmp_long < 0 || tmp_long > GID_T_MAX)
633             error (1, 0, _("invalid group `%s'"), group_name);
634           group_id = (gid_t) tmp_long;
635         }
636       else
637         group_id = gr->gr_gid;
638       endgrent ();
639     }
640   else
641     group_id = (gid_t) -1;
642 }
643
644 static void
645 usage (int status)
646 {
647   if (status != 0)
648     fprintf (stderr, _("Try `%s --help' for more information.\n"),
649              program_name);
650   else
651     {
652       printf (_("\
653 Usage: %s [OPTION]... SOURCE DEST           (1st format)\n\
654   or:  %s [OPTION]... SOURCE... DIRECTORY   (2nd format)\n\
655   or:  %s -d [OPTION]... DIRECTORY...       (3rd format)\n\
656 "),
657               program_name, program_name, program_name);
658       printf (_("\
659 In the first two formats, copy SOURCE to DEST or multiple SOURCE(s) to\n\
660 the existing DIRECTORY, while setting permission modes and owner/group.\n\
661 In the third format, create all components of the given DIRECTORY(ies).\n\
662 \n\
663   -b, --backup        make backup before removal\n\
664   -c                  (ignored)\n\
665   -d, --directory     treat all arguments as directory names; create all\n\
666                         components of the specified directories\n\
667   -D                  create all leading components of DEST except the last,\n\
668                         then copy SOURCE to DEST;  useful in the 1st format\n\
669   -g, --group=GROUP   set group ownership, instead of process' current group\n\
670   -m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x\n\
671   -o, --owner=OWNER   set ownership (super-user only)\n\
672   -p, --preserve-timestamps   apply access/modification times of SOURCE files\n\
673                         to corresponding destination files\n\
674   -s, --strip         strip symbol tables, only for 1st and 2nd formats\n\
675   -S, --suffix=SUFFIX override the usual backup suffix\n\
676       --verbose       print the name of each directory as it is created\n\
677   -V, --version-control=WORD   override the usual version control\n\
678       --help          display this help and exit\n\
679       --version       output version information and exit\n\
680 \n\
681 "));
682       printf (_("\
683 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX.  The\n\
684 version control may be set with VERSION_CONTROL, values are:\n\
685 \n\
686   t, numbered     make numbered backups\n\
687   nil, existing   numbered if numbered backups exist, simple otherwise\n\
688   never, simple   always make simple backups\n\
689 "));
690       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
691       close_stdout ();
692     }
693   exit (status);
694 }