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