Remove option-describing comment block.
[platform/upstream/coreutils.git] / src / install.c
1 /* install - copy files and set attributes
2    Copyright (C) 89, 90, 91, 1995-2000 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 full_write ();
82 int isdir ();
83
84 int stat ();
85
86 static int change_timestamps PARAMS ((const char *from, const char *to));
87 static int change_attributes PARAMS ((const char *path));
88 static int copy_file PARAMS ((const char *from, const char *to,
89                               const struct cp_options *x));
90 static int install_file_to_path PARAMS ((const char *from, const char *to,
91                                          const struct cp_options *x));
92 static int install_file_in_dir PARAMS ((const char *from, const char *to_dir,
93                                         const struct cp_options *x));
94 static int install_file_in_file PARAMS ((const char *from, const char *to,
95                                          const struct cp_options *x));
96 static void get_ids PARAMS ((void));
97 static void strip PARAMS ((const char *path));
98 void usage PARAMS ((int status));
99
100 /* The name this program was run with, for error messages. */
101 char *program_name;
102
103 /* The user name that will own the files, or NULL to make the owner
104    the current user ID. */
105 static char *owner_name;
106
107 /* The user ID corresponding to `owner_name'. */
108 static uid_t owner_id;
109
110 /* The group name that will own the files, or NULL to make the group
111    the current group ID. */
112 static char *group_name;
113
114 /* The group ID corresponding to `group_name'. */
115 static gid_t group_id;
116
117 /* The permissions to which the files will be set.  The umask has
118    no effect. */
119 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
120
121 /* If nonzero, strip executable files after copying them. */
122 static int strip_files;
123
124 /* If nonzero, install a directory instead of a regular file. */
125 static int dir_arg;
126
127 static struct option const long_options[] =
128 {
129   {"backup", optional_argument, NULL, 'b'},
130   {"directory", no_argument, NULL, 'd'},
131   {"group", required_argument, NULL, 'g'},
132   {"mode", required_argument, NULL, 'm'},
133   {"owner", required_argument, NULL, 'o'},
134   {"preserve-timestamps", no_argument, NULL, 'p'},
135   {"strip", no_argument, NULL, 's'},
136   {"suffix", required_argument, NULL, 'S'},
137   {"version-control", required_argument, NULL, 'V'}, /* Deprecated. FIXME. */
138   {"verbose", no_argument, NULL, 'v'},
139   {GETOPT_HELP_OPTION_DECL},
140   {GETOPT_VERSION_OPTION_DECL},
141   {NULL, 0, NULL, 0}
142 };
143
144 static void
145 cp_option_init (struct cp_options *x)
146 {
147   x->copy_as_regular = 1;
148   x->dereference = DEREF_ALWAYS;
149   x->unlink_dest_before_opening = 1;
150   x->unlink_dest_after_failed_open = 0;
151
152   /* If unlink fails, try to proceed anyway.  */
153   x->failed_unlink_is_fatal = 0;
154
155   x->hard_link = 0;
156   x->interactive = 0;
157   x->move_mode = 0;
158   x->myeuid = geteuid ();
159   x->one_file_system = 0;
160   x->preserve_owner_and_group = 0;
161   x->preserve_chmod_bits = 0;
162   x->preserve_timestamps = 0;
163   x->require_preserve = 0;
164   x->recursive = 0;
165   x->sparse_mode = SPARSE_AUTO;
166   x->symbolic_link = 0;
167   x->backup_type = none;
168
169   /* Create destination files initially writable so we can run strip on them.
170      Although GNU strip works fine on read-only files, some others
171      would fail.  */
172   x->set_mode = 1;
173   x->mode = S_IRUSR | S_IWUSR;
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 *symbolic_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           symbolic_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 (make_backups)
277     x.backup_type = xget_version ("backup type", version_control_string);
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 (1);
286     }
287
288   if (symbolic_mode)
289     {
290       struct mode_change *change = mode_compile (symbolic_mode, 0);
291       if (change == MODE_INVALID)
292         error (1, 0, _("invalid mode %s"), quote (symbolic_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 (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
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 (1);
336             }
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 utimbuf utb;
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   /* There's currently no interface to set file timestamps with
498      better than 1-second resolution, so discard any fractional
499      part of the source timestamp.  */
500
501   utb.actime = stb.st_atime;
502   utb.modtime = stb.st_mtime;
503   if (utime (to, &utb))
504     {
505       error (0, errno, _("cannot set time stamps for %s"), quote (to));
506       return 1;
507     }
508   return 0;
509 }
510
511 /* Strip the symbol table from the file PATH.
512    We could dig the magic number out of the file first to
513    determine whether to strip it, but the header files and
514    magic numbers vary so much from system to system that making
515    it portable would be very difficult.  Not worth the effort. */
516
517 static void
518 strip (const char *path)
519 {
520   int status;
521   pid_t pid = fork ();
522
523   switch (pid)
524     {
525     case -1:
526       error (1, errno, _("cannot fork"));
527       break;
528     case 0:                     /* Child. */
529       execlp ("strip", "strip", path, NULL);
530       error (1, errno, _("cannot run strip"));
531       break;
532     default:                    /* Parent. */
533       /* Parent process. */
534       while (pid != wait (&status))     /* Wait for kid to finish. */
535         /* Do nothing. */ ;
536       if (status)
537         error (1, 0, _("strip failed"));
538       break;
539     }
540 }
541
542 /* Initialize the user and group ownership of the files to install. */
543
544 static void
545 get_ids (void)
546 {
547   struct passwd *pw;
548   struct group *gr;
549
550   if (owner_name)
551     {
552       pw = getpwnam (owner_name);
553       if (pw == NULL)
554         {
555           long int tmp_long;
556           if (xstrtol (owner_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
557               || tmp_long < 0 || tmp_long > UID_T_MAX)
558             error (1, 0, _("invalid user %s"), quote (owner_name));
559           owner_id = (uid_t) tmp_long;
560         }
561       else
562         owner_id = pw->pw_uid;
563       endpwent ();
564     }
565   else
566     owner_id = (uid_t) -1;
567
568   if (group_name)
569     {
570       gr = getgrnam (group_name);
571       if (gr == NULL)
572         {
573           long int tmp_long;
574           if (xstrtol (group_name, NULL, 0, &tmp_long, NULL) != LONGINT_OK
575               || tmp_long < 0 || tmp_long > GID_T_MAX)
576             error (1, 0, _("invalid group %s"), quote (group_name));
577           group_id = (gid_t) tmp_long;
578         }
579       else
580         group_id = gr->gr_gid;
581       endgrent ();
582     }
583   else
584     group_id = (gid_t) -1;
585 }
586
587 void
588 usage (int status)
589 {
590   if (status != 0)
591     fprintf (stderr, _("Try `%s --help' for more information.\n"),
592              program_name);
593   else
594     {
595       printf (_("\
596 Usage: %s [OPTION]... SOURCE DEST           (1st format)\n\
597   or:  %s [OPTION]... SOURCE... DIRECTORY   (2nd format)\n\
598   or:  %s -d [OPTION]... DIRECTORY...       (3rd format)\n\
599 "),
600               program_name, program_name, program_name);
601       printf (_("\
602 In the first two formats, copy SOURCE to DEST or multiple SOURCE(s) to\n\
603 the existing DIRECTORY, while setting permission modes and owner/group.\n\
604 In the third format, create all components of the given DIRECTORY(ies).\n\
605 \n\
606       --backup[=CONTROL] make a backup of each existing destination file\n\
607   -b                  like --backup but does not accept an argument\n\
608   -c                  (ignored)\n\
609   -d, --directory     treat all arguments as directory names; create all\n\
610                         components of the specified directories\n\
611   -D                  create all leading components of DEST except the last,\n\
612                         then copy SOURCE to DEST;  useful in the 1st format\n\
613   -g, --group=GROUP   set group ownership, instead of process' current group\n\
614   -m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x\n\
615   -o, --owner=OWNER   set ownership (super-user only)\n\
616   -p, --preserve-timestamps   apply access/modification times of SOURCE files\n\
617                         to corresponding destination files\n\
618   -s, --strip         strip symbol tables, only for 1st and 2nd formats\n\
619   -S, --suffix=SUFFIX override the usual backup suffix\n\
620   -v, --verbose       print the name of each directory as it is created\n\
621       --help          display this help and exit\n\
622       --version       output version information and exit\n\
623 \n\
624 "));
625       printf (_("\
626 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
627 The version control method may be selected via the --backup option or through\n\
628 the VERSION_CONTROL environment variable.  Here are the values:\n\
629 \n\
630   none, off       never make backups (even if --backup is given)\n\
631   numbered, t     make numbered backups\n\
632   existing, nil   numbered if numbered backups exist, simple otherwise\n\
633   simple, never   always make simple backups\n\
634 "));
635       puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
636     }
637   exit (status);
638 }