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