Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.58
      1 /*	$NetBSD: xinstall.c,v 1.58 2001/11/12 19:08:31 tv Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1987, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #include <sys/cdefs.h>
     37 #ifndef lint
     38 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
     39 	The Regents of the University of California.  All rights reserved.\n");
     40 #endif /* not lint */
     41 
     42 #ifndef lint
     43 #if 0
     44 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
     45 #else
     46 __RCSID("$NetBSD: xinstall.c,v 1.58 2001/11/12 19:08:31 tv Exp $");
     47 #endif
     48 #endif /* not lint */
     49 
     50 #include <sys/param.h>
     51 #include <sys/wait.h>
     52 #include <sys/mman.h>
     53 #include <sys/stat.h>
     54 
     55 #include <ctype.h>
     56 #include <err.h>
     57 #include <errno.h>
     58 #include <fcntl.h>
     59 #include <grp.h>
     60 #include <paths.h>
     61 #include <pwd.h>
     62 #include <stdio.h>
     63 #include <stdlib.h>
     64 #include <string.h>
     65 #include <unistd.h>
     66 #include <vis.h>
     67 
     68 #include "pathnames.h"
     69 #include "stat_flags.h"
     70 
     71 #define STRIP_ARGS_MAX 32
     72 #define BACKUP_SUFFIX ".old"
     73 
     74 int	dobackup, docopy, dodir, dostrip, dolink, dopreserve, dorename,
     75 	    dounpriv;
     76 int	numberedbackup;
     77 int	mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
     78 char	pathbuf[MAXPATHLEN];
     79 uid_t	uid;
     80 gid_t	gid;
     81 char	*group, *owner, *fflags, *tags;
     82 FILE	*metafp;
     83 char	*metafile;
     84 u_long	fileflags;
     85 char	*stripArgs;
     86 char	*suffix = BACKUP_SUFFIX;
     87 
     88 #define LN_ABSOLUTE	0x01
     89 #define LN_RELATIVE	0x02
     90 #define LN_HARD		0x04
     91 #define LN_SYMBOLIC	0x08
     92 #define LN_MIXED	0x10
     93 
     94 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
     95 #define	SETFLAGS	0x02		/* Tell install to set flags. */
     96 #define	HASUID		0x04		/* Tell install the uid was given */
     97 #define	HASGID		0x08		/* Tell install the gid was given */
     98 
     99 void	backup(const char *);
    100 void	copy(int, char *, int, char *, off_t);
    101 const char *inotype(u_int);
    102 void	install(char *, char *, u_int);
    103 void	install_dir(char *, u_int);
    104 int	main(int, char *[]);
    105 void	makelink(char *, char *);
    106 int	parseid(char *, id_t *);
    107 void	strip(char *);
    108 void	metadata_log(const char *, mode_t, struct timeval *, const char *);
    109 void	usage(void);
    110 
    111 int
    112 main(int argc, char *argv[])
    113 {
    114 	struct stat	from_sb, to_sb;
    115 	void		*set;
    116 	u_int		iflags;
    117 	int		ch, no_target;
    118 	char		*p, *to_name;
    119 
    120 	setprogname(argv[0]);
    121 
    122 	iflags = 0;
    123 	while ((ch = getopt(argc, argv, "cbB:df:g:l:m:M:o:prsS:T:U")) != -1)
    124 		switch((char)ch) {
    125 		case 'B':
    126 			suffix = optarg;
    127 			numberedbackup = 0;
    128 			{
    129 				/* Check if given suffix really generates
    130 				   different suffixes - catch e.g. ".%" */
    131 				char suffix_expanded0[FILENAME_MAX],
    132 				     suffix_expanded1[FILENAME_MAX];
    133 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
    134 					       suffix, 0);
    135 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
    136 					       suffix, 1);
    137 				if (strcmp(suffix_expanded0, suffix_expanded1)
    138 				    != 0)
    139 					numberedbackup = 1;
    140 			}
    141 			/* fall through; -B implies -b */
    142 		case 'b':
    143 			dobackup = 1;
    144 			break;
    145 		case 'c':
    146 			docopy = 1;
    147 			break;
    148 		case 'd':
    149 			dodir = 1;
    150 			break;
    151 		case 'f':
    152 			fflags = optarg;
    153 			break;
    154 		case 'g':
    155 			group = optarg;
    156 			break;
    157 		case 'l':
    158 			for (p = optarg; *p; p++)
    159 				switch (*p) {
    160 				case 's':
    161 					dolink &= ~(LN_HARD|LN_MIXED);
    162 					dolink |= LN_SYMBOLIC;
    163 					break;
    164 				case 'h':
    165 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    166 					dolink |= LN_HARD;
    167 					break;
    168 				case 'm':
    169 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    170 					dolink |= LN_MIXED;
    171 					break;
    172 				case 'a':
    173 					dolink &= ~LN_RELATIVE;
    174 					dolink |= LN_ABSOLUTE;
    175 					break;
    176 				case 'r':
    177 					dolink &= ~LN_ABSOLUTE;
    178 					dolink |= LN_RELATIVE;
    179 					break;
    180 				default:
    181 					errx(1, "%c: invalid link type", *p);
    182 					break;
    183 				}
    184 			break;
    185 		case 'm':
    186 			if (!(set = setmode(optarg)))
    187 				errx(1, "%s: invalid file mode", optarg);
    188 			mode = getmode(set, 0);
    189 			free(set);
    190 			break;
    191 		case 'M':
    192 			metafile = optarg;
    193 			break;
    194 		case 'o':
    195 			owner = optarg;
    196 			break;
    197 		case 'p':
    198 			dopreserve = 1;
    199 			break;
    200 		case 'r':
    201 			dorename = 1;
    202 			break;
    203 		case 'S':
    204 			stripArgs = strdup(optarg);
    205 			if (stripArgs == NULL)
    206 				errx(1, "%s", strerror(ENOMEM));
    207 			/* fall through; -S implies -s */
    208 		case 's':
    209 			dostrip = 1;
    210 			break;
    211 		case 'T':
    212 			tags = optarg;
    213 			break;
    214 		case 'U':
    215 			dounpriv = 1;
    216 			break;
    217 		case '?':
    218 		default:
    219 			usage();
    220 		}
    221 	argc -= optind;
    222 	argv += optind;
    223 
    224 	/* strip and link options make no sense when creating directories */
    225 	if ((dostrip || dolink) && dodir)
    226 		usage();
    227 
    228 	/* strip and flags make no sense with links */
    229 	if ((dostrip || fflags) && dolink)
    230 		usage();
    231 
    232 	/* must have at least two arguments, except when creating directories */
    233 	if (argc < 2 && !dodir)
    234 		usage();
    235 
    236 	/* get group and owner id's */
    237 	if (group && !dounpriv) {
    238 		struct group *gp;
    239 
    240 		if ((gp = getgrnam(group)) != NULL)
    241 			gid = gp->gr_gid;
    242 		else if (! parseid(group, &gid))
    243 			errx(1, "unknown group %s", group);
    244 		iflags |= HASGID;
    245 	}
    246 	if (owner && !dounpriv) {
    247 		struct passwd *pp;
    248 
    249 		if ((pp = getpwnam(owner)) != NULL)
    250 			uid = pp->pw_uid;
    251 		else if (! parseid(owner, &uid))
    252 			errx(1, "unknown user %s", owner);
    253 		iflags |= HASUID;
    254 	}
    255 
    256 	if (fflags && !dounpriv) {
    257 		if (string_to_flags(&fflags, &fileflags, NULL))
    258 			errx(1, "%s: invalid flag", fflags);
    259 		iflags |= SETFLAGS;
    260 	}
    261 
    262 	if (metafile) {
    263 		if ((metafp = fopen(metafile, "a")) == NULL)
    264 			warn("open %s", metafile);
    265 	}
    266 
    267 	if (dodir) {
    268 		for (; *argv != NULL; ++argv)
    269 			install_dir(*argv, iflags);
    270 		exit (0);
    271 	}
    272 
    273 	no_target = stat(to_name = argv[argc - 1], &to_sb);
    274 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
    275 		for (; *argv != to_name; ++argv)
    276 			install(*argv, to_name, iflags | DIRECTORY);
    277 		exit(0);
    278 	}
    279 
    280 	/* can't do file1 file2 directory/file */
    281 	if (argc != 2)
    282 		usage();
    283 
    284 	if (!no_target) {
    285 		if (stat(*argv, &from_sb))
    286 			err(1, "%s", *argv);
    287 		if (!S_ISREG(to_sb.st_mode))
    288 			errx(1, "%s: not a regular file", to_name);
    289 		if (!dolink && to_sb.st_dev == from_sb.st_dev &&
    290 		    to_sb.st_ino == from_sb.st_ino)
    291 			errx(1, "%s and %s are the same file", *argv, to_name);
    292 		/*
    293 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    294 		 * off the append/immutable bits -- if we fail, go ahead,
    295 		 * it might work.
    296 		 */
    297 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
    298 		if (to_sb.st_flags & NOCHANGEBITS)
    299 			(void)chflags(to_name,
    300 			    to_sb.st_flags & ~(NOCHANGEBITS));
    301 		if (dobackup)
    302 			backup(to_name);
    303 		else if (!dorename)
    304 			(void)unlink(to_name);
    305 	}
    306 	install(*argv, to_name, iflags);
    307 	exit(0);
    308 }
    309 
    310 /*
    311  * parseid --
    312  *	parse uid or gid from arg into id, returning non-zero if successful
    313  */
    314 int
    315 parseid(char *name, id_t *id)
    316 {
    317 	char	*ep;
    318 
    319 	errno = 0;
    320 	*id = (id_t)strtoul(name, &ep, 10);
    321 	if (errno || *ep != '\0')
    322 		return (0);
    323 	return (1);
    324 }
    325 
    326 /*
    327  * makelink --
    328  *	make a link from source to destination
    329  */
    330 void
    331 makelink(char *from_name, char *to_name)
    332 {
    333 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
    334 
    335 	/* Try hard links first */
    336 	if (dolink & (LN_HARD|LN_MIXED)) {
    337 		if (link(from_name, to_name) == -1) {
    338 			if ((dolink & LN_HARD) || errno != EXDEV)
    339 				err(1, "link %s -> %s", from_name, to_name);
    340 		}
    341 		else {
    342 			/* XXX: need to log hard link metadata ? */
    343 			return;
    344 		}
    345 	}
    346 
    347 	/* Symbolic links */
    348 	if (dolink & LN_ABSOLUTE) {
    349 		/* Convert source path to absolute */
    350 		if (realpath(from_name, src) == NULL)
    351 			err(1, "%s", src);
    352 		if (symlink(src, to_name) == -1)
    353 			err(1, "symlink %s -> %s", src, to_name);
    354 		metadata_log(to_name, S_IFLNK, NULL, src);
    355 		return;
    356 	}
    357 
    358 	if (dolink & LN_RELATIVE) {
    359 		char *s, *d;
    360 
    361 		/* Resolve pathnames */
    362 		if (realpath(from_name, src) == NULL)
    363 			err(1, "%s", src);
    364 		if (realpath(to_name, dst) == NULL)
    365 			err(1, "%s", dst);
    366 
    367 		/* trim common path components */
    368 		for (s = src, d = dst; *s == *d; s++, d++)
    369 			continue;
    370 		while (*s != '/')
    371 			s--, d--;
    372 
    373 		/* count the number of directories we need to backtrack */
    374 		for (++d, lnk[0] = '\0'; *d; d++)
    375 			if (*d == '/')
    376 				(void) strcat(lnk, "../");
    377 
    378 		(void) strcat(lnk, ++s);
    379 
    380 		if (symlink(lnk, dst) == -1)
    381 			err(1, "symlink %s -> %s", lnk, dst);
    382 		metadata_log(dst, S_IFLNK, NULL, lnk);
    383 		return;
    384 	}
    385 
    386 	/*
    387 	 * If absolute or relative was not specified,
    388 	 * try the names the user provided
    389 	 */
    390 	if (symlink(from_name, to_name) == -1)
    391 		err(1, "symlink %s -> %s", from_name, to_name);
    392 	metadata_log(to_name, S_IFLNK, NULL, from_name);
    393 }
    394 
    395 /*
    396  * install --
    397  *	build a path name and install the file
    398  */
    399 void
    400 install(char *from_name, char *to_name, u_int flags)
    401 {
    402 	struct stat	from_sb, to_sb;
    403 	struct timeval	tv[2];
    404 	int		devnull, from_fd, to_fd, serrno;
    405 	char		*p, tmpl[MAXPATHLEN], *oto_name;
    406 
    407 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    408 		if (!dolink) {
    409 			if (stat(from_name, &from_sb))
    410 				err(1, "%s", from_name);
    411 			if (!S_ISREG(from_sb.st_mode))
    412 				errx(1, "%s: not a regular file", from_name);
    413 		}
    414 		/* Build the target path. */
    415 		if (flags & DIRECTORY) {
    416 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    417 			    to_name,
    418 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    419 			to_name = pathbuf;
    420 		}
    421 		devnull = 0;
    422 	} else {
    423 		from_sb.st_flags = 0;	/* XXX */
    424 		devnull = 1;
    425 	}
    426 
    427 	/*
    428 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    429 	 * off the append/immutable bits -- if we fail, go ahead,
    430 	 * it might work.
    431 	 */
    432 	if (stat(to_name, &to_sb) == 0 &&
    433 	    to_sb.st_flags & (NOCHANGEBITS))
    434 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    435 	if (dorename) {
    436 		char *ptr, c, *dir;
    437 
    438 		if ((ptr = strrchr(to_name, '/')) != NULL) {
    439 			c = *++ptr;
    440 			*ptr = '\0';
    441 			dir = to_name;
    442 		} else {
    443 			c = '\0';	/* pacify gcc */
    444 			dir = tmpl;
    445 			*dir = '\0';
    446 		}
    447 		(void)snprintf(tmpl, sizeof(tmpl), "%sinst.XXXXXX", dir);
    448 		if (ptr)
    449 			*ptr = c;
    450 		oto_name = to_name;
    451 		to_name = tmpl;
    452 
    453 	} else {
    454 		oto_name = NULL;	/* pacify gcc */
    455 		if (dobackup)
    456 			backup(to_name);
    457 		else
    458 			(void)unlink(to_name);
    459 	}
    460 
    461 	if (dolink) {
    462 		makelink(from_name, to_name);
    463 		return;
    464 	}
    465 
    466 	/* Create target. */
    467 	if (dorename) {
    468 		if ((to_fd = mkstemp(to_name)) == -1)
    469 			err(1, "%s", to_name);
    470 	} else {
    471 		if ((to_fd = open(to_name,
    472 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    473 			err(1, "%s", to_name);
    474 	}
    475 	if (!devnull) {
    476 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    477 			(void)unlink(to_name);
    478 			err(1, "%s", from_name);
    479 		}
    480 		copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    481 		(void)close(from_fd);
    482 	}
    483 
    484 	if (dostrip) {
    485 		strip(to_name);
    486 
    487 		/*
    488 		 * Re-open our fd on the target, in case we used a strip
    489 		 *  that does not work in-place -- like gnu binutils strip.
    490 		 */
    491 		close(to_fd);
    492 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    493 		  err(1, "stripping %s", to_name);
    494 	}
    495 
    496 	/*
    497 	 * Set owner, group, mode for target; do the chown first,
    498 	 * chown may lose the setuid bits.
    499 	 */
    500 	if (!dounpriv &&
    501 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    502 		serrno = errno;
    503 		(void)unlink(to_name);
    504 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    505 	}
    506 	if (dounpriv)
    507 		mode &= S_IRWXU|S_IRWXG|S_IRWXO;
    508 	if (fchmod(to_fd, mode) == -1) {
    509 		serrno = errno;
    510 		(void)unlink(to_name);
    511 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    512 	}
    513 
    514 	/*
    515 	 * Preserve the date of the source file.
    516 	 */
    517 	if (dopreserve) {
    518 #ifdef BSD4_4
    519 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    520 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    521 #else
    522 		tv[0].tv_sec = from_sb.st_atime;
    523 		tv[0].tv_usec = 0;
    524 		tv[1].tv_sec = from_sb.st_mtime;
    525 		tv[1].tv_usec = 0;
    526 #endif
    527 		if (!dounpriv && futimes(to_fd, tv) == -1)
    528 			warn("%s: futimes", to_name);
    529 	}
    530 
    531 	(void)close(to_fd);
    532 
    533 	if (dorename) {
    534 		if (rename(to_name, oto_name) == -1)
    535 			err(1, "%s: rename", to_name);
    536 		to_name = oto_name;
    537 	}
    538 
    539 	if (!docopy && !devnull && unlink(from_name))
    540 		err(1, "%s", from_name);
    541 
    542 	/*
    543 	 * If provided a set of flags, set them, otherwise, preserve the
    544 	 * flags, except for the dump flag.
    545 	 */
    546 	if (!dounpriv && chflags(to_name,
    547 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    548 	{
    549 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    550 			warn("%s: chflags", to_name);
    551 	}
    552 
    553 	metadata_log(to_name, S_IFREG, tv, NULL);
    554 }
    555 
    556 /*
    557  * copy --
    558  *	copy from one file to another
    559  */
    560 void
    561 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    562 {
    563 	ssize_t	nr, nw;
    564 	int	serrno;
    565 	char	*p;
    566 	char	buf[MAXBSIZE];
    567 
    568 	/*
    569 	 * There's no reason to do anything other than close the file
    570 	 * now if it's empty, so let's not bother.
    571 	 */
    572 	if (size > 0) {
    573 
    574 		/*
    575 		 * Mmap and write if less than 8M (the limit is so we
    576 		 * don't totally trash memory on big files).  This is
    577 		 * really a minor hack, but it wins some CPU back.
    578 		 */
    579 
    580 		if (size <= 8 * 1048576) {
    581 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    582 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    583 			    == MAP_FAILED) {
    584 				goto mmap_failed;
    585 			}
    586 #ifdef MADV_SEQUENTIAL
    587 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    588 			    && errno != EOPNOTSUPP)
    589 				warnx("madvise: %s", strerror(errno));
    590 #endif
    591 
    592 			if (write(to_fd, p, size) != size) {
    593 				serrno = errno;
    594 				(void)unlink(to_name);
    595 				errx(1, "%s: %s",
    596 				    to_name, strerror(serrno));
    597 			}
    598 		} else {
    599 mmap_failed:
    600 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    601 				if ((nw = write(to_fd, buf, nr)) != nr) {
    602 					serrno = errno;
    603 					(void)unlink(to_name);
    604 					errx(1, "%s: %s", to_name,
    605 					    strerror(nw > 0 ? EIO : serrno));
    606 				}
    607 			}
    608 			if (nr != 0) {
    609 				serrno = errno;
    610 				(void)unlink(to_name);
    611 				errx(1, "%s: %s", from_name, strerror(serrno));
    612 			}
    613 		}
    614 	}
    615 }
    616 
    617 /*
    618  * strip --
    619  *	use strip(1) to strip the target file
    620  */
    621 void
    622 strip(char *to_name)
    623 {
    624 	int	serrno, status;
    625 	char	*stripprog;
    626 
    627 	switch (vfork()) {
    628 	case -1:
    629 		serrno = errno;
    630 		(void)unlink(to_name);
    631 		errx(1, "vfork: %s", strerror(serrno));
    632 	case 0:
    633 		stripprog = getenv("STRIP");
    634 		if (stripprog == NULL)
    635 			stripprog = _PATH_STRIP;
    636 
    637 		if (stripArgs) {
    638 			/*
    639 			 * build up a command line and let /bin/sh
    640 			 * parse the arguments
    641 			 */
    642 			char* cmd = (char*)malloc(sizeof(char)*
    643 						  (3+strlen(stripprog)+
    644 						     strlen(stripArgs)+
    645 						     strlen(to_name)));
    646 
    647 			if (cmd == NULL)
    648 				errx(1, "%s", strerror(ENOMEM));
    649 
    650 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    651 
    652 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    653 		} else
    654 			execlp(stripprog, "strip", to_name, NULL);
    655 
    656 		warn("%s", stripprog);
    657 		_exit(1);
    658 	default:
    659 		if (wait(&status) == -1 || status)
    660 			(void)unlink(to_name);
    661 	}
    662 }
    663 
    664 /*
    665  * backup file "to_name" to to_name.suffix
    666  * if suffix contains a "%", it's taken as a printf(3) pattern
    667  * used for a numbered backup.
    668  */
    669 void
    670 backup(const char *to_name)
    671 {
    672 	char	backup[FILENAME_MAX];
    673 
    674 	if (numberedbackup) {
    675 		/* Do numbered backup */
    676 		int cnt;
    677 		char suffix_expanded[FILENAME_MAX];
    678 
    679 		cnt=0;
    680 		do {
    681 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    682 			    cnt);
    683 			(void)snprintf(backup, FILENAME_MAX, "%s%s",
    684 				       to_name, suffix_expanded);
    685 			cnt++;
    686 		} while (access(backup, F_OK)==0);
    687 	} else {
    688 		/* Do simple backup */
    689 		(void)snprintf(backup, FILENAME_MAX, "%s%s", to_name, suffix);
    690 	}
    691 
    692 	(void)rename(to_name, backup);
    693 }
    694 
    695 /*
    696  * install_dir --
    697  *	build directory hierarchy
    698  */
    699 void
    700 install_dir(char *path, u_int flags)
    701 {
    702         char		*p;
    703         struct stat	sb;
    704         int		ch;
    705 
    706         for (p = path;; ++p)
    707                 if (!*p || (p != path && *p  == '/')) {
    708                         ch = *p;
    709                         *p = '\0';
    710                         if (stat(path, &sb)) {
    711                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    712 					err(1, "%s", path);
    713 					/* NOTREACHED */
    714                                 }
    715                         }
    716                         if (!(*p = ch))
    717 				break;
    718                 }
    719 
    720 	if (!dounpriv && (
    721 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
    722 	    || chmod(path, mode) == -1 )) {
    723                 warn("%s", path);
    724 	}
    725 	metadata_log(path, S_IFDIR, NULL, NULL);
    726 }
    727 
    728 const char *
    729 inotype(u_int type)
    730 {
    731 
    732 	switch (type & S_IFMT) {
    733 	case S_IFBLK:
    734 		return ("block");
    735 	case S_IFCHR:
    736 		return ("char");
    737 	case S_IFDIR:
    738 		return ("dir");
    739 	case S_IFIFO:
    740 		return ("fifo");
    741 	case S_IFREG:
    742 		return ("file");
    743 	case S_IFLNK:
    744 		return ("link");
    745 	case S_IFSOCK:
    746 		return ("socket");
    747 	default:
    748 		return ("unknown");
    749 	}
    750 	/* NOTREACHED */
    751 }
    752 
    753 /*
    754  * metadata_log --
    755  *	if metafp is not NULL, output mtree(8) full path name and settings to
    756  *	metafp, to allow permissions to be set correctly by other tools.
    757  */
    758 void
    759 metadata_log(const char *path, mode_t type, struct timeval *tv,
    760 	const char *link)
    761 {
    762 	const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
    763 	char		*buf;
    764 
    765 	if (!metafp)
    766 		return;
    767 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
    768 	if (buf == NULL) {
    769 		warnx("%s", strerror(ENOMEM));
    770 		return;
    771 	}
    772 	if (flock(fileno(metafp), LOCK_EX) == -1) {	/* lock log file */
    773 		warn("can't lock %s", metafile);
    774 		return;
    775 	}
    776 
    777 	strsvis(buf, path, VIS_CSTYLE, extra);		/* encode name */
    778 	fprintf(metafp, ".%s%s type=%s mode=%#o",	/* print details */
    779 	    buf[0] == '/' ? "" : "/", buf, inotype(type), mode);
    780 	if (link)
    781 		fprintf(metafp, " link=%s", link);
    782 	if (owner)
    783 		fprintf(metafp, " uname=%s", owner);
    784 	if (group)
    785 		fprintf(metafp, " gname=%s", group);
    786 	if (fflags)
    787 		fprintf(metafp, " flags=%s", fflags);
    788 	if (tags)
    789 		fprintf(metafp, " tags=%s", tags);
    790 	if (tv != NULL && dopreserve)
    791 		fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
    792 	fputc('\n', metafp);
    793 	fflush(metafp);					/* flush output */
    794 	if (flock(fileno(metafp), LOCK_UN) == -1) {	/* unlock log file */
    795 		warn("can't unlock %s", metafile);
    796 	}
    797 	free(buf);
    798 }
    799 
    800 
    801 
    802 /*
    803  * usage --
    804  *	print a usage message and die
    805  */
    806 void
    807 usage(void)
    808 {
    809 
    810 	(void)fprintf(stderr, "\
    811 usage: install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    812 	    [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 file2\n\
    813        install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    814 	    [-o owner] [-g group] [-l linkflags] [-S stripflags]\n\
    815 	    file1 ... fileN directory\n\
    816        install [-Up] [-M log] [-T tags] -d [-m mode]\n\
    817 	    [-o owner] [-g group] directory ...\n");
    818 	exit(1);
    819 }
    820