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