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