Don't include version.h.
[coreutils.git] / src / install.c
blob39584840b12d79fde7d7bf2d6a98a20f5563bb73
1 /* install - copy files and set attributes
2 Copyright (C) 1989, 1990, 1991, 1995 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
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Copy files and set their permission modes and, if possible,
19 their owner and group. Used similarly to `cp'; typically
20 used in Makefiles to copy programs into their destination
21 directories. It can also be used to create the destination
22 directories and any leading directories, and to set the final
23 directory's modes. It refuses to copy files onto themselves.
25 Options:
26 -g, --group=GROUP
27 Set the group ownership of the installed file or directory
28 to the group ID of GROUP (default is process's current
29 group). GROUP may also be a numeric group ID.
31 -m, --mode=MODE
32 Set the permission mode for the installed file or directory
33 to MODE, which is an octal number (default is 0755).
35 -o, --owner=OWNER
36 If run as root, set the ownership of the installed file to
37 the user ID of OWNER (default is root). OWNER may also be
38 a numeric user ID.
40 -c No effect. For compatibility with old Unix versions of install.
42 -s, --strip
43 Strip the symbol tables from installed files.
45 -d, --directory
46 Create a directory and its leading directories, if they
47 do not already exist. Set the owner, group and mode
48 as given on the command line. Any leading directories
49 that are created are also given those attributes.
50 This is different from the SunOS 4.0 install, which gives
51 directories that it creates the default attributes.
53 David MacKenzie <djm@gnu.ai.mit.edu> */
55 #include <config.h>
56 #include <stdio.h>
57 #include <getopt.h>
58 #include <sys/types.h>
59 #include <pwd.h>
60 #include <grp.h>
62 #include "system.h"
63 #include "backupfile.h"
64 #include "modechange.h"
65 #include "makepath.h"
66 #include "error.h"
68 #if HAVE_SYS_WAIT_H
69 #include <sys/wait.h>
70 #endif
72 struct passwd *getpwnam ();
73 struct group *getgrnam ();
75 #ifndef _POSIX_VERSION
76 uid_t getuid ();
77 gid_t getgid ();
78 int wait ();
79 #endif
81 #ifndef HAVE_ENDGRENT
82 # define endgrent() ((void) 0)
83 #endif
85 #ifndef HAVE_ENDPWENT
86 # define endpwent() ((void) 0)
87 #endif
89 /* True if C is an ASCII octal digit. */
90 #define isodigit(c) ((c) >= '0' && c <= '7')
92 /* Number of bytes of a file to copy at a time. */
93 #define READ_SIZE (32 * 1024)
95 char *basename ();
96 char *stpcpy ();
97 char *xmalloc ();
98 int safe_read ();
99 int full_write ();
100 int isdir ();
101 enum backup_type get_version ();
103 static int change_attributes __P ((char *path, int no_need_to_chown));
104 static int copy_file __P ((char *from, char *to, int *to_created));
105 static int install_file_in_dir __P ((char *from, char *to_dir));
106 static int install_file_in_file __P ((char *from, char *to));
107 static void get_ids __P ((void));
108 static void strip __P ((char *path));
109 static void usage __P ((int status));
111 /* The name this program was run with, for error messages. */
112 char *program_name;
114 /* The user name that will own the files, or NULL to make the owner
115 the current user ID. */
116 static char *owner_name;
118 /* The user ID corresponding to `owner_name'. */
119 static uid_t owner_id;
121 /* The group name that will own the files, or NULL to make the group
122 the current group ID. */
123 static char *group_name;
125 /* The group ID corresponding to `group_name'. */
126 static gid_t group_id;
128 /* The permissions to which the files will be set. The umask has
129 no effect. */
130 static int mode;
132 /* If nonzero, strip executable files after copying them. */
133 static int strip_files;
135 /* If nonzero, install a directory instead of a regular file. */
136 static int dir_arg;
138 /* If nonzero, display usage information and exit. */
139 static int show_help;
141 /* If nonzero, print the version on standard output and exit. */
142 static int show_version;
144 static struct option const long_options[] =
146 {"strip", no_argument, NULL, 's'},
147 {"directory", no_argument, NULL, 'd'},
148 {"group", required_argument, NULL, 'g'},
149 {"mode", required_argument, NULL, 'm'},
150 {"owner", required_argument, NULL, 'o'},
151 {"backup", no_argument, NULL, 'b'},
152 {"version-control", required_argument, NULL, 'V'},
153 {"help", no_argument, &show_help, 1},
154 {"version", no_argument, &show_version, 1},
155 {NULL, 0, NULL, 0}
158 void
159 main (int argc, char **argv)
161 int optc;
162 int errors = 0;
163 char *symbolic_mode = NULL;
164 int make_backups = 0;
165 char *version;
167 program_name = argv[0];
168 setlocale (LC_ALL, "");
169 bindtextdomain (PACKAGE, LOCALEDIR);
170 textdomain (PACKAGE);
172 owner_name = NULL;
173 group_name = NULL;
174 mode = 0755;
175 strip_files = 0;
176 dir_arg = 0;
177 umask (0);
179 version = getenv ("SIMPLE_BACKUP_SUFFIX");
180 if (version)
181 simple_backup_suffix = version;
182 version = getenv ("VERSION_CONTROL");
184 while ((optc = getopt_long (argc, argv, "bcsdg:m:o:V:S:", long_options,
185 (int *) 0)) != EOF)
187 switch (optc)
189 case 0:
190 break;
191 case 'b':
192 make_backups = 1;
193 break;
194 case 'c':
195 break;
196 case 's':
197 strip_files = 1;
198 break;
199 case 'd':
200 dir_arg = 1;
201 break;
202 case 'g':
203 group_name = optarg;
204 break;
205 case 'm':
206 symbolic_mode = optarg;
207 break;
208 case 'o':
209 owner_name = optarg;
210 break;
211 case 'S':
212 simple_backup_suffix = optarg;
213 break;
214 case 'V':
215 version = optarg;
216 break;
217 default:
218 usage (1);
222 if (show_version)
224 printf ("install - %s\n", PACKAGE_VERSION);
225 exit (0);
228 if (show_help)
229 usage (0);
231 /* Check for invalid combinations of arguments. */
232 if (dir_arg && strip_files)
233 error (1, 0,
234 _("the strip option may not be used when installing a directory"));
236 if (make_backups)
237 backup_type = get_version (version);
239 if (optind == argc || (optind == argc - 1 && !dir_arg))
241 error (0, 0, _("too few arguments"));
242 usage (1);
245 if (symbolic_mode)
247 struct mode_change *change = mode_compile (symbolic_mode, 0);
248 if (change == MODE_INVALID)
249 error (1, 0, _("invalid mode `%s'"), symbolic_mode);
250 else if (change == MODE_MEMORY_EXHAUSTED)
251 error (1, 0, _("virtual memory exhausted"));
252 mode = mode_adjust (0, change);
255 get_ids ();
257 if (dir_arg)
259 for (; optind < argc; ++optind)
261 errors |=
262 make_path (argv[optind], mode, mode, owner_id, group_id, 0, NULL);
265 else
267 if (optind == argc - 2)
269 if (!isdir (argv[argc - 1]))
270 errors = install_file_in_file (argv[argc - 2], argv[argc - 1]);
271 else
272 errors = install_file_in_dir (argv[argc - 2], argv[argc - 1]);
274 else
276 if (!isdir (argv[argc - 1]))
277 usage (1);
278 for (; optind < argc - 1; ++optind)
280 errors |= install_file_in_dir (argv[optind], argv[argc - 1]);
285 exit (errors);
288 /* Copy file FROM onto file TO and give TO the appropriate
289 attributes.
290 Return 0 if successful, 1 if an error occurs. */
292 static int
293 install_file_in_file (char *from, char *to)
295 int to_created;
296 int no_need_to_chown;
298 if (copy_file (from, to, &to_created))
299 return 1;
300 if (strip_files)
301 strip (to);
302 no_need_to_chown = (to_created
303 && owner_name == NULL
304 && group_name == NULL);
305 return change_attributes (to, no_need_to_chown);
308 /* Copy file FROM into directory TO_DIR, keeping its same name,
309 and give the copy the appropriate attributes.
310 Return 0 if successful, 1 if not. */
312 static int
313 install_file_in_dir (char *from, char *to_dir)
315 char *from_base;
316 char *to;
317 int ret;
319 from_base = basename (from);
320 to = xmalloc ((unsigned) (strlen (to_dir) + strlen (from_base) + 2));
321 stpcpy (stpcpy (stpcpy (to, to_dir), "/"), from_base);
322 ret = install_file_in_file (from, to);
323 free (to);
324 return ret;
327 /* A chunk of a file being copied. */
328 static char buffer[READ_SIZE];
330 /* Copy file FROM onto file TO, creating TO if necessary.
331 Return 0 if the copy is successful, 1 if not. If the copy is
332 successful, set *TO_CREATED to nonzero if TO was created (if it did
333 not exist or did, but was unlinked) and to zero otherwise. If the
334 copy fails, don't modify *TO_CREATED. */
336 static int
337 copy_file (char *from, char *to, int *to_created)
339 int fromfd, tofd;
340 int bytes;
341 int ret = 0;
342 struct stat from_stats, to_stats;
343 int target_created = 1;
345 if (stat (from, &from_stats))
347 error (0, errno, "%s", from);
348 return 1;
350 if (!S_ISREG (from_stats.st_mode))
352 error (0, 0, _("`%s' is not a regular file"), from);
353 return 1;
355 if (stat (to, &to_stats) == 0)
357 if (!S_ISREG (to_stats.st_mode))
359 error (0, 0, _("`%s' is not a regular file"), to);
360 return 1;
362 if (from_stats.st_dev == to_stats.st_dev
363 && from_stats.st_ino == to_stats.st_ino)
365 error (0, 0, _("`%s' and `%s' are the same file"), from, to);
366 return 1;
369 /* The destination file exists. Try to back it up if required. */
370 if (backup_type != none)
372 char *tmp_backup = find_backup_file_name (to);
373 char *dst_backup;
375 if (tmp_backup == NULL)
376 error (1, 0, "virtual memory exhausted");
377 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
378 strcpy (dst_backup, tmp_backup);
379 free (tmp_backup);
380 if (rename (to, dst_backup))
382 if (errno != ENOENT)
384 error (0, errno, "cannot backup `%s'", to);
385 return 1;
390 /* If unlink fails, try to proceed anyway. */
391 if (unlink (to))
392 target_created = 0;
395 fromfd = open (from, O_RDONLY, 0);
396 if (fromfd == -1)
398 error (0, errno, "%s", from);
399 return 1;
402 /* Make sure to open the file in a mode that allows writing. */
403 tofd = open (to, O_WRONLY | O_CREAT | O_TRUNC, 0600);
404 if (tofd == -1)
406 error (0, errno, "%s", to);
407 close (fromfd);
408 return 1;
411 while ((bytes = safe_read (fromfd, buffer, READ_SIZE)) > 0)
412 if (full_write (tofd, buffer, bytes) < 0)
414 error (0, errno, "%s", to);
415 goto copy_error;
418 if (bytes == -1)
420 error (0, errno, "%s", from);
421 goto copy_error;
424 if (close (fromfd) < 0)
426 error (0, errno, "%s", from);
427 ret = 1;
429 if (close (tofd) < 0)
431 error (0, errno, "%s", to);
432 ret = 1;
434 if (ret == 0)
435 *to_created = target_created;
436 return ret;
438 copy_error:
439 close (fromfd);
440 close (tofd);
441 return 1;
444 /* Set the attributes of file or directory PATH.
445 If NO_NEED_TO_CHOWN is nonzero, don't call chown.
446 Return 0 if successful, 1 if not. */
448 static int
449 change_attributes (char *path, int no_need_to_chown)
451 int err = 0;
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.
459 We don't pass -1 to chown to mean "don't change the value"
460 because SVR3 and earlier non-BSD systems don't support that.
462 We don't normally ignore errors from chown because the idea of
463 the install command is that the file is supposed to end up with
464 precisely the attributes that the user specified (or defaulted).
465 If the file doesn't end up with the group they asked for, they'll
466 want to know. But AFS returns EPERM when you try to change a
467 file's group; thus the kludge. */
469 if (!no_need_to_chown && chown (path, owner_id, group_id)
470 #ifdef AFS
471 && errno != EPERM
472 #endif
474 err = errno;
475 if (chmod (path, mode))
476 err = errno;
477 if (err)
479 error (0, err, "%s", path);
480 return 1;
482 return 0;
485 /* Strip the symbol table from the file PATH.
486 We could dig the magic number out of the file first to
487 determine whether to strip it, but the header files and
488 magic numbers vary so much from system to system that making
489 it portable would be very difficult. Not worth the effort. */
491 static void
492 strip (char *path)
494 int pid, status;
496 pid = fork ();
497 switch (pid)
499 case -1:
500 error (1, errno, _("cannot fork"));
501 break;
502 case 0: /* Child. */
503 execlp ("strip", "strip", path, (char *) NULL);
504 error (1, errno, _("cannot run strip"));
505 break;
506 default: /* Parent. */
507 /* Parent process. */
508 while (pid != wait (&status)) /* Wait for kid to finish. */
509 /* Do nothing. */ ;
510 break;
514 /* Return nonzero if STR is an ASCII representation of a nonzero
515 decimal integer, zero if not. */
517 static int
518 is_number (char *str)
520 if (*str == 0)
521 return 0;
522 for (; *str; str++)
523 if (!ISDIGIT (*str))
524 return 0;
525 return 1;
528 /* Initialize the user and group ownership of the files to install. */
530 static void
531 get_ids (void)
533 struct passwd *pw;
534 struct group *gr;
536 if (owner_name)
538 pw = getpwnam (owner_name);
539 if (pw == NULL)
541 if (!is_number (owner_name))
542 error (1, 0, _("invalid user `%s'"), owner_name);
543 /* FIXME: atoi won't warn about overflow. Use xstrtoul. */
544 /* FIXME: eliminate is_number altogether! */
545 owner_id = atoi (owner_name);
547 else
548 owner_id = pw->pw_uid;
549 endpwent ();
551 else
552 owner_id = getuid ();
554 if (group_name)
556 gr = getgrnam (group_name);
557 if (gr == NULL)
559 if (!is_number (group_name))
560 error (1, 0, _("invalid group `%s'"), group_name);
561 /* FIXME: atoi won't warn about overflow. Use xstrtoul. */
562 group_id = atoi (group_name);
564 else
565 group_id = gr->gr_gid;
566 endgrent ();
568 else
569 group_id = getgid ();
572 static void
573 usage (int status)
575 if (status != 0)
576 fprintf (stderr, _("Try `%s --help' for more information.\n"),
577 program_name);
578 else
580 printf (_("\
581 Usage: %s [OPTION]... SOURCE DEST (1st format)\n\
582 or: %s [OPTION]... SOURCE... DIRECTORY (2nd format)\n\
583 or: %s -d [OPTION]... DIRECTORY... (3nd format)\n\
585 program_name, program_name, program_name);
586 printf (_("\
587 In first two formats, copy SOURCE to DEST or multiple SOURCE(s) to\n\
588 DIRECTORY, while setting permission modes and owner/group. In third\n\
589 format, make all components of the given DIRECTORY(ies).\n\
591 -c (ignored)\n\
592 -d, --directory create [leading] directories, mandatory for 3rd format\n\
593 -g, --group=GROUP set group ownership, instead of process' current group\n\
594 -m, --mode=MODE set permission mode (as in chmod), instead of rw-r--r--\n\
595 -o, --owner=OWNER set ownership (super-user only)\n\
596 -s, --strip strip symbol tables, only for 1st and 2nd formats\n\
597 -b, --backup make backup before removal\n\
598 -S, --suffix=SUFFIX override the usual backup suffix\n\
599 -V, --version-control=WORD override the usual version control\n\
600 --help display this help and exit\n\
601 --version output version information and exit\n\
603 The backup suffix is ~, unless set with SIMPLE_BACKUP_SUFFIX. The\n\
604 version control may be set with VERSION_CONTROL, values are:\n\
606 t, numbered make numbered backups\n\
607 nil, existing numbered if numbered backups exist, simple otherwise\n\
608 never, simple always make simple backups\n"));
610 exit (status);