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