* src/dd.c (flags): noatime and nofollow now depend on
[coreutils/bo.git] / src / install.c
blob9c5150fbcf3a7e1efc3df6f2743ecd83d2fc57ba
1 /* install - copy files and set attributes
2 Copyright (C) 89, 90, 91, 1995-2006 Free Software Foundation, Inc.
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu> */
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #include <signal.h>
25 #include <pwd.h>
26 #include <grp.h>
28 #include "system.h"
29 #include "backupfile.h"
30 #include "error.h"
31 #include "cp-hash.h"
32 #include "copy.h"
33 #include "filenamecat.h"
34 #include "mkancesdirs.h"
35 #include "mkdir-p.h"
36 #include "modechange.h"
37 #include "quote.h"
38 #include "savewd.h"
39 #include "stat-time.h"
40 #include "utimens.h"
41 #include "xstrtol.h"
43 /* The official name of this program (e.g., no `g' prefix). */
44 #define PROGRAM_NAME "install"
46 #define AUTHORS "David MacKenzie"
48 #if HAVE_SYS_WAIT_H
49 # include <sys/wait.h>
50 #endif
52 #if ! HAVE_ENDGRENT
53 # define endgrent() ((void) 0)
54 #endif
56 #if ! HAVE_ENDPWENT
57 # define endpwent() ((void) 0)
58 #endif
60 /* Initial number of entries in each hash table entry's table of inodes. */
61 #define INITIAL_HASH_MODULE 100
63 /* Initial number of entries in the inode hash table. */
64 #define INITIAL_ENTRY_TAB_SIZE 70
66 /* Number of bytes of a file to copy at a time. */
67 #define READ_SIZE (32 * 1024)
69 static bool change_timestamps (struct stat const *from_sb, char const *to);
70 static bool change_attributes (char const *name);
71 static bool copy_file (const char *from, const char *to,
72 const struct cp_options *x);
73 static bool install_file_in_file_parents (char const *from, char *to,
74 struct cp_options *x);
75 static bool install_file_in_dir (const char *from, const char *to_dir,
76 const struct cp_options *x);
77 static bool install_file_in_file (const char *from, const char *to,
78 const struct cp_options *x);
79 static void get_ids (void);
80 static void strip (char const *name);
81 static void announce_mkdir (char const *dir, void *options);
82 static int make_ancestor (char const *dir, void *options);
83 void usage (int status);
85 /* The name this program was run with, for error messages. */
86 char *program_name;
88 /* The user name that will own the files, or NULL to make the owner
89 the current user ID. */
90 static char *owner_name;
92 /* The user ID corresponding to `owner_name'. */
93 static uid_t owner_id;
95 /* The group name that will own the files, or NULL to make the group
96 the current group ID. */
97 static char *group_name;
99 /* The group ID corresponding to `group_name'. */
100 static gid_t group_id;
102 #define DEFAULT_MODE (S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH)
104 /* The file mode bits to which non-directory files will be set. The umask has
105 no effect. */
106 static mode_t mode = DEFAULT_MODE;
108 /* Similar, but for directories. */
109 static mode_t dir_mode = DEFAULT_MODE;
111 /* The file mode bits that the user cares about. This should be a
112 superset of DIR_MODE and a subset of CHMOD_MODE_BITS. This matters
113 for directories, since otherwise directories may keep their S_ISUID
114 or S_ISGID bits. */
115 static mode_t dir_mode_bits = CHMOD_MODE_BITS;
117 /* If true, strip executable files after copying them. */
118 static bool strip_files;
120 /* If true, install a directory instead of a regular file. */
121 static bool dir_arg;
123 static struct option const long_options[] =
125 {"backup", optional_argument, NULL, 'b'},
126 {"directory", no_argument, NULL, 'd'},
127 {"group", required_argument, NULL, 'g'},
128 {"mode", required_argument, NULL, 'm'},
129 {"no-target-directory", no_argument, NULL, 'T'},
130 {"owner", required_argument, NULL, 'o'},
131 {"preserve-timestamps", no_argument, NULL, 'p'},
132 {"strip", no_argument, NULL, 's'},
133 {"suffix", required_argument, NULL, 'S'},
134 {"target-directory", required_argument, NULL, 't'},
135 {"verbose", no_argument, NULL, 'v'},
136 {GETOPT_HELP_OPTION_DECL},
137 {GETOPT_VERSION_OPTION_DECL},
138 {NULL, 0, NULL, 0}
141 static void
142 cp_option_init (struct cp_options *x)
144 x->copy_as_regular = true;
145 x->dereference = DEREF_ALWAYS;
146 x->unlink_dest_before_opening = true;
147 x->unlink_dest_after_failed_open = false;
148 x->hard_link = false;
149 x->interactive = I_UNSPECIFIED;
150 x->move_mode = false;
151 x->chown_privileges = chown_privileges ();
152 x->one_file_system = false;
153 x->preserve_ownership = false;
154 x->preserve_links = false;
155 x->preserve_mode = false;
156 x->preserve_timestamps = false;
157 x->require_preserve = false;
158 x->recursive = false;
159 x->sparse_mode = SPARSE_AUTO;
160 x->symbolic_link = false;
161 x->backup_type = no_backups;
163 /* Create destination files initially writable so we can run strip on them.
164 Although GNU strip works fine on read-only files, some others
165 would fail. */
166 x->set_mode = true;
167 x->mode = S_IRUSR | S_IWUSR;
168 x->stdin_tty = false;
170 x->update = false;
171 x->verbose = false;
172 x->dest_info = NULL;
173 x->src_info = NULL;
176 /* FILE is the last operand of this command. Return true if FILE is a
177 directory. But report an error there is a problem accessing FILE,
178 or if FILE does not exist but would have to refer to an existing
179 directory if it referred to anything at all. */
181 static bool
182 target_directory_operand (char const *file)
184 char const *b = last_component (file);
185 size_t blen = strlen (b);
186 bool looks_like_a_dir = (blen == 0 || ISSLASH (b[blen - 1]));
187 struct stat st;
188 int err = (stat (file, &st) == 0 ? 0 : errno);
189 bool is_a_dir = !err && S_ISDIR (st.st_mode);
190 if (err && err != ENOENT)
191 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
192 if (is_a_dir < looks_like_a_dir)
193 error (EXIT_FAILURE, err, _("target %s is not a directory"), quote (file));
194 return is_a_dir;
197 /* Process a command-line file name, for the -d option. */
198 static int
199 process_dir (char *dir, struct savewd *wd, void *options)
201 return (make_dir_parents (dir, wd,
202 make_ancestor, options,
203 dir_mode, announce_mkdir,
204 dir_mode_bits, owner_id, group_id, false)
205 ? EXIT_SUCCESS
206 : EXIT_FAILURE);
210 main (int argc, char **argv)
212 int optc;
213 int exit_status = EXIT_SUCCESS;
214 const char *specified_mode = NULL;
215 bool make_backups = false;
216 char *backup_suffix_string;
217 char *version_control_string = NULL;
218 bool mkdir_and_install = false;
219 struct cp_options x;
220 char const *target_directory = NULL;
221 bool no_target_directory = false;
222 int n_files;
223 char **file;
225 initialize_main (&argc, &argv);
226 program_name = argv[0];
227 setlocale (LC_ALL, "");
228 bindtextdomain (PACKAGE, LOCALEDIR);
229 textdomain (PACKAGE);
231 atexit (close_stdout);
233 cp_option_init (&x);
235 owner_name = NULL;
236 group_name = NULL;
237 strip_files = false;
238 dir_arg = false;
239 umask (0);
241 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
242 we'll actually use backup_suffix_string. */
243 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
245 while ((optc = getopt_long (argc, argv, "bcsDdg:m:o:pt:TvS:", long_options,
246 NULL)) != -1)
248 switch (optc)
250 case 'b':
251 make_backups = true;
252 if (optarg)
253 version_control_string = optarg;
254 break;
255 case 'c':
256 break;
257 case 's':
258 strip_files = true;
259 #ifdef SIGCHLD
260 /* System V fork+wait does not work if SIGCHLD is ignored. */
261 signal (SIGCHLD, SIG_DFL);
262 #endif
263 break;
264 case 'd':
265 dir_arg = true;
266 break;
267 case 'D':
268 mkdir_and_install = true;
269 break;
270 case 'v':
271 x.verbose = true;
272 break;
273 case 'g':
274 group_name = optarg;
275 break;
276 case 'm':
277 specified_mode = optarg;
278 break;
279 case 'o':
280 owner_name = optarg;
281 break;
282 case 'p':
283 x.preserve_timestamps = true;
284 break;
285 case 'S':
286 make_backups = true;
287 backup_suffix_string = optarg;
288 break;
289 case 't':
290 if (target_directory)
291 error (EXIT_FAILURE, 0,
292 _("multiple target directories specified"));
293 else
295 struct stat st;
296 if (stat (optarg, &st) != 0)
297 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
298 if (! S_ISDIR (st.st_mode))
299 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
300 quote (optarg));
302 target_directory = optarg;
303 break;
304 case 'T':
305 no_target_directory = true;
306 break;
307 case_GETOPT_HELP_CHAR;
308 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
309 default:
310 usage (EXIT_FAILURE);
314 /* Check for invalid combinations of arguments. */
315 if (dir_arg & strip_files)
316 error (EXIT_FAILURE, 0,
317 _("the strip option may not be used when installing a directory"));
318 if (dir_arg && target_directory)
319 error (EXIT_FAILURE, 0,
320 _("target directory not allowed when installing a directory"));
322 if (backup_suffix_string)
323 simple_backup_suffix = xstrdup (backup_suffix_string);
325 x.backup_type = (make_backups
326 ? xget_version (_("backup type"),
327 version_control_string)
328 : no_backups);
330 n_files = argc - optind;
331 file = argv + optind;
333 if (n_files <= ! (dir_arg || target_directory))
335 if (n_files <= 0)
336 error (0, 0, _("missing file operand"));
337 else
338 error (0, 0, _("missing destination file operand after %s"),
339 quote (file[0]));
340 usage (EXIT_FAILURE);
343 if (no_target_directory)
345 if (target_directory)
346 error (EXIT_FAILURE, 0,
347 _("Cannot combine --target-directory (-t) "
348 "and --no-target-directory (-T)"));
349 if (2 < n_files)
351 error (0, 0, _("extra operand %s"), quote (file[2]));
352 usage (EXIT_FAILURE);
355 else if (! (dir_arg || target_directory))
357 if (2 <= n_files && target_directory_operand (file[n_files - 1]))
358 target_directory = file[--n_files];
359 else if (2 < n_files)
360 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
361 quote (file[n_files - 1]));
364 if (specified_mode)
366 struct mode_change *change = mode_compile (specified_mode);
367 if (!change)
368 error (EXIT_FAILURE, 0, _("invalid mode %s"), quote (specified_mode));
369 mode = mode_adjust (0, false, 0, change, NULL);
370 dir_mode = mode_adjust (0, true, 0, change, &dir_mode_bits);
371 free (change);
374 get_ids ();
376 if (dir_arg)
377 exit_status = savewd_process_files (n_files, file, process_dir, &x);
378 else
380 /* FIXME: it's a little gross that this initialization is
381 required by copy.c::copy. */
382 hash_init ();
384 if (!target_directory)
386 if (! (mkdir_and_install
387 ? install_file_in_file_parents (file[0], file[1], &x)
388 : install_file_in_file (file[0], file[1], &x)))
389 exit_status = EXIT_FAILURE;
391 else
393 int i;
394 dest_info_init (&x);
395 for (i = 0; i < n_files; i++)
396 if (! install_file_in_dir (file[i], target_directory, &x))
397 exit_status = EXIT_FAILURE;
401 exit (exit_status);
404 /* Copy file FROM onto file TO, creating any missing parent directories of TO.
405 Return true if successful. */
407 static bool
408 install_file_in_file_parents (char const *from, char *to,
409 struct cp_options *x)
411 bool save_working_directory =
412 ! (IS_ABSOLUTE_FILE_NAME (from) && IS_ABSOLUTE_FILE_NAME (to));
413 int status = EXIT_SUCCESS;
415 struct savewd wd;
416 savewd_init (&wd);
417 if (! save_working_directory)
418 savewd_finish (&wd);
420 if (mkancesdirs (to, &wd, make_ancestor, x) == -1)
422 error (0, errno, _("cannot create directory %s"), to);
423 status = EXIT_FAILURE;
426 if (save_working_directory)
428 int restore_result = savewd_restore (&wd, status);
429 int restore_errno = errno;
430 savewd_finish (&wd);
431 if (EXIT_SUCCESS < restore_result)
432 return false;
433 if (restore_result < 0 && status == EXIT_SUCCESS)
435 error (0, restore_errno, _("cannot create directory %s"), to);
436 return false;
440 return (status == EXIT_SUCCESS && install_file_in_file (from, to, x));
443 /* Copy file FROM onto file TO and give TO the appropriate
444 attributes.
445 Return true if successful. */
447 static bool
448 install_file_in_file (const char *from, const char *to,
449 const struct cp_options *x)
451 struct stat from_sb;
452 if (x->preserve_timestamps && stat (from, &from_sb) != 0)
454 error (0, errno, _("cannot stat %s"), quote (from));
455 return false;
457 if (! copy_file (from, to, x))
458 return false;
459 if (strip_files)
460 strip (to);
461 if (! change_attributes (to))
462 return false;
463 if (x->preserve_timestamps && (strip_files || ! S_ISREG (from_sb.st_mode)))
464 return change_timestamps (&from_sb, to);
465 return true;
468 /* Copy file FROM into directory TO_DIR, keeping its same name,
469 and give the copy the appropriate attributes.
470 Return true if successful. */
472 static bool
473 install_file_in_dir (const char *from, const char *to_dir,
474 const struct cp_options *x)
476 const char *from_base = last_component (from);
477 char *to = file_name_concat (to_dir, from_base, NULL);
478 bool ret = install_file_in_file (from, to, x);
479 free (to);
480 return ret;
483 /* Copy file FROM onto file TO, creating TO if necessary.
484 Return true if successful. */
486 static bool
487 copy_file (const char *from, const char *to, const struct cp_options *x)
489 bool copy_into_self;
491 /* Allow installing from non-regular files like /dev/null.
492 Charles Karney reported that some Sun version of install allows that
493 and that sendmail's installation process relies on the behavior.
494 However, since !x->recursive, the call to "copy" will fail if FROM
495 is a directory. */
497 return copy (from, to, false, x, &copy_into_self, NULL);
500 /* Set the attributes of file or directory NAME.
501 Return true if successful. */
503 static bool
504 change_attributes (char const *name)
506 /* chown must precede chmod because on some systems,
507 chown clears the set[ug]id bits for non-superusers,
508 resulting in incorrect permissions.
509 On System V, users can give away files with chown and then not
510 be able to chmod them. So don't give files away.
512 We don't normally ignore errors from chown because the idea of
513 the install command is that the file is supposed to end up with
514 precisely the attributes that the user specified (or defaulted).
515 If the file doesn't end up with the group they asked for, they'll
516 want to know. */
518 if (! (owner_id == (uid_t) -1 && group_id == (gid_t) -1)
519 && chown (name, owner_id, group_id) != 0)
520 error (0, errno, _("cannot change ownership of %s"), quote (name));
521 else if (chmod (name, mode) != 0)
522 error (0, errno, _("cannot change permissions of %s"), quote (name));
523 else
524 return true;
526 return false;
529 /* Set the timestamps of file TO to match those of file FROM.
530 Return true if successful. */
532 static bool
533 change_timestamps (struct stat const *from_sb, char const *to)
535 struct timespec timespec[2];
536 timespec[0] = get_stat_atime (from_sb);
537 timespec[1] = get_stat_mtime (from_sb);
539 if (utimens (to, timespec))
541 error (0, errno, _("cannot set time stamps for %s"), quote (to));
542 return false;
544 return true;
547 /* Strip the symbol table from the file NAME.
548 We could dig the magic number out of the file first to
549 determine whether to strip it, but the header files and
550 magic numbers vary so much from system to system that making
551 it portable would be very difficult. Not worth the effort. */
553 static void
554 strip (char const *name)
556 int status;
557 pid_t pid = fork ();
559 switch (pid)
561 case -1:
562 error (EXIT_FAILURE, errno, _("fork system call failed"));
563 break;
564 case 0: /* Child. */
565 execlp ("strip", "strip", name, NULL);
566 error (EXIT_FAILURE, errno, _("cannot run strip"));
567 break;
568 default: /* Parent. */
569 /* Parent process. */
570 while (pid != wait (&status)) /* Wait for kid to finish. */
571 /* Do nothing. */ ;
572 if (status)
573 error (EXIT_FAILURE, 0, _("strip failed"));
574 break;
578 /* Initialize the user and group ownership of the files to install. */
580 static void
581 get_ids (void)
583 struct passwd *pw;
584 struct group *gr;
586 if (owner_name)
588 pw = getpwnam (owner_name);
589 if (pw == NULL)
591 unsigned long int tmp;
592 if (xstrtoul (owner_name, NULL, 0, &tmp, NULL) != LONGINT_OK
593 || UID_T_MAX < tmp)
594 error (EXIT_FAILURE, 0, _("invalid user %s"), quote (owner_name));
595 owner_id = tmp;
597 else
598 owner_id = pw->pw_uid;
599 endpwent ();
601 else
602 owner_id = (uid_t) -1;
604 if (group_name)
606 gr = getgrnam (group_name);
607 if (gr == NULL)
609 unsigned long int tmp;
610 if (xstrtoul (group_name, NULL, 0, &tmp, NULL) != LONGINT_OK
611 || GID_T_MAX < tmp)
612 error (EXIT_FAILURE, 0, _("invalid group %s"), quote (group_name));
613 group_id = tmp;
615 else
616 group_id = gr->gr_gid;
617 endgrent ();
619 else
620 group_id = (gid_t) -1;
623 /* Report that directory DIR was made, if OPTIONS requests this. */
624 static void
625 announce_mkdir (char const *dir, void *options)
627 struct cp_options const *x = options;
628 if (x->verbose)
629 error (0, 0, _("creating directory %s"), quote (dir));
632 /* Make ancestor directory DIR, with options OPTIONS. */
633 static int
634 make_ancestor (char const *dir, void *options)
636 int r = mkdir (dir, DEFAULT_MODE);
637 if (r == 0)
638 announce_mkdir (dir, options);
639 return r;
642 void
643 usage (int status)
645 if (status != EXIT_SUCCESS)
646 fprintf (stderr, _("Try `%s --help' for more information.\n"),
647 program_name);
648 else
650 printf (_("\
651 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
652 or: %s [OPTION]... SOURCE... DIRECTORY\n\
653 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
654 or: %s [OPTION]... -d DIRECTORY...\n\
656 program_name, program_name, program_name, program_name);
657 fputs (_("\
658 In the first three forms, copy SOURCE to DEST or multiple SOURCE(s) to\n\
659 the existing DIRECTORY, while setting permission modes and owner/group.\n\
660 In the 4th form, create all components of the given DIRECTORY(ies).\n\
662 "), stdout);
663 fputs (_("\
664 Mandatory arguments to long options are mandatory for short options too.\n\
665 "), stdout);
666 fputs (_("\
667 --backup[=CONTROL] make a backup of each existing destination file\n\
668 -b like --backup but does not accept an argument\n\
669 -c (ignored)\n\
670 -d, --directory treat all arguments as directory names; create all\n\
671 components of the specified directories\n\
672 "), stdout);
673 fputs (_("\
674 -D create all leading components of DEST except the last,\n\
675 then copy SOURCE to DEST\n\
676 -g, --group=GROUP set group ownership, instead of process' current group\n\
677 -m, --mode=MODE set permission mode (as in chmod), instead of rwxr-xr-x\n\
678 -o, --owner=OWNER set ownership (super-user only)\n\
679 "), stdout);
680 fputs (_("\
681 -p, --preserve-timestamps apply access/modification times of SOURCE files\n\
682 to corresponding destination files\n\
683 -s, --strip strip symbol tables\n\
684 -S, --suffix=SUFFIX override the usual backup suffix\n\
685 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
686 -T, --no-target-directory treat DEST as a normal file\n\
687 -v, --verbose print the name of each directory as it is created\n\
688 "), stdout);
689 fputs (HELP_OPTION_DESCRIPTION, stdout);
690 fputs (VERSION_OPTION_DESCRIPTION, stdout);
691 fputs (_("\
693 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
694 The version control method may be selected via the --backup option or through\n\
695 the VERSION_CONTROL environment variable. Here are the values:\n\
697 "), stdout);
698 fputs (_("\
699 none, off never make backups (even if --backup is given)\n\
700 numbered, t make numbered backups\n\
701 existing, nil numbered if numbered backups exist, simple otherwise\n\
702 simple, never always make simple backups\n\
703 "), stdout);
704 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
706 exit (status);