Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.57
      1 /*	$NetBSD: xinstall.c,v 1.57 2001/10/29 02:57:21 lukem 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.57 2001/10/29 02:57:21 lukem 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 && fchmod(to_fd, mode) == -1) {
    507 		serrno = errno;
    508 		(void)unlink(to_name);
    509 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    510 	}
    511 
    512 	/*
    513 	 * Preserve the date of the source file.
    514 	 */
    515 	if (dopreserve) {
    516 #ifdef BSD4_4
    517 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    518 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    519 #else
    520 		tv[0].tv_sec = from_sb.st_atime;
    521 		tv[0].tv_usec = 0;
    522 		tv[1].tv_sec = from_sb.st_mtime;
    523 		tv[1].tv_usec = 0;
    524 #endif
    525 		if (!dounpriv && futimes(to_fd, tv) == -1)
    526 			warn("%s: futimes", to_name);
    527 	}
    528 
    529 	(void)close(to_fd);
    530 
    531 	if (dorename) {
    532 		if (rename(to_name, oto_name) == -1)
    533 			err(1, "%s: rename", to_name);
    534 		to_name = oto_name;
    535 	}
    536 
    537 	if (!docopy && !devnull && unlink(from_name))
    538 		err(1, "%s", from_name);
    539 
    540 	/*
    541 	 * If provided a set of flags, set them, otherwise, preserve the
    542 	 * flags, except for the dump flag.
    543 	 */
    544 	if (!dounpriv && chflags(to_name,
    545 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    546 	{
    547 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    548 			warn("%s: chflags", to_name);
    549 	}
    550 
    551 	metadata_log(to_name, S_IFREG, tv, NULL);
    552 }
    553 
    554 /*
    555  * copy --
    556  *	copy from one file to another
    557  */
    558 void
    559 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    560 {
    561 	ssize_t	nr, nw;
    562 	int	serrno;
    563 	char	*p;
    564 	char	buf[MAXBSIZE];
    565 
    566 	/*
    567 	 * There's no reason to do anything other than close the file
    568 	 * now if it's empty, so let's not bother.
    569 	 */
    570 	if (size > 0) {
    571 
    572 		/*
    573 		 * Mmap and write if less than 8M (the limit is so we
    574 		 * don't totally trash memory on big files).  This is
    575 		 * really a minor hack, but it wins some CPU back.
    576 		 */
    577 
    578 		if (size <= 8 * 1048576) {
    579 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    580 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    581 			    == MAP_FAILED) {
    582 				goto mmap_failed;
    583 			}
    584 #ifdef MADV_SEQUENTIAL
    585 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    586 			    && errno != EOPNOTSUPP)
    587 				warnx("madvise: %s", strerror(errno));
    588 #endif
    589 
    590 			if (write(to_fd, p, size) != size) {
    591 				serrno = errno;
    592 				(void)unlink(to_name);
    593 				errx(1, "%s: %s",
    594 				    to_name, strerror(serrno));
    595 			}
    596 		} else {
    597 mmap_failed:
    598 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    599 				if ((nw = write(to_fd, buf, nr)) != nr) {
    600 					serrno = errno;
    601 					(void)unlink(to_name);
    602 					errx(1, "%s: %s", to_name,
    603 					    strerror(nw > 0 ? EIO : serrno));
    604 				}
    605 			}
    606 			if (nr != 0) {
    607 				serrno = errno;
    608 				(void)unlink(to_name);
    609 				errx(1, "%s: %s", from_name, strerror(serrno));
    610 			}
    611 		}
    612 	}
    613 }
    614 
    615 /*
    616  * strip --
    617  *	use strip(1) to strip the target file
    618  */
    619 void
    620 strip(char *to_name)
    621 {
    622 	int	serrno, status;
    623 	char	*stripprog;
    624 
    625 	switch (vfork()) {
    626 	case -1:
    627 		serrno = errno;
    628 		(void)unlink(to_name);
    629 		errx(1, "vfork: %s", strerror(serrno));
    630 	case 0:
    631 		stripprog = getenv("STRIP");
    632 		if (stripprog == NULL)
    633 			stripprog = _PATH_STRIP;
    634 
    635 		if (stripArgs) {
    636 			/*
    637 			 * build up a command line and let /bin/sh
    638 			 * parse the arguments
    639 			 */
    640 			char* cmd = (char*)malloc(sizeof(char)*
    641 						  (3+strlen(stripprog)+
    642 						     strlen(stripArgs)+
    643 						     strlen(to_name)));
    644 
    645 			if (cmd == NULL)
    646 				errx(1, "%s", strerror(ENOMEM));
    647 
    648 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    649 
    650 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    651 		} else
    652 			execlp(stripprog, "strip", to_name, NULL);
    653 
    654 		warn("%s", stripprog);
    655 		_exit(1);
    656 	default:
    657 		if (wait(&status) == -1 || status)
    658 			(void)unlink(to_name);
    659 	}
    660 }
    661 
    662 /*
    663  * backup file "to_name" to to_name.suffix
    664  * if suffix contains a "%", it's taken as a printf(3) pattern
    665  * used for a numbered backup.
    666  */
    667 void
    668 backup(const char *to_name)
    669 {
    670 	char	backup[FILENAME_MAX];
    671 
    672 	if (numberedbackup) {
    673 		/* Do numbered backup */
    674 		int cnt;
    675 		char suffix_expanded[FILENAME_MAX];
    676 
    677 		cnt=0;
    678 		do {
    679 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    680 			    cnt);
    681 			(void)snprintf(backup, FILENAME_MAX, "%s%s",
    682 				       to_name, suffix_expanded);
    683 			cnt++;
    684 		} while (access(backup, F_OK)==0);
    685 	} else {
    686 		/* Do simple backup */
    687 		(void)snprintf(backup, FILENAME_MAX, "%s%s", to_name, suffix);
    688 	}
    689 
    690 	(void)rename(to_name, backup);
    691 }
    692 
    693 /*
    694  * install_dir --
    695  *	build directory hierarchy
    696  */
    697 void
    698 install_dir(char *path, u_int flags)
    699 {
    700         char		*p;
    701         struct stat	sb;
    702         int		ch;
    703 
    704         for (p = path;; ++p)
    705                 if (!*p || (p != path && *p  == '/')) {
    706                         ch = *p;
    707                         *p = '\0';
    708                         if (stat(path, &sb)) {
    709                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    710 					err(1, "%s", path);
    711 					/* NOTREACHED */
    712                                 }
    713                         }
    714                         if (!(*p = ch))
    715 				break;
    716                 }
    717 
    718 	if (!dounpriv && (
    719 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
    720 	    || chmod(path, mode) == -1 )) {
    721                 warn("%s", path);
    722 	}
    723 	metadata_log(path, S_IFDIR, NULL, NULL);
    724 }
    725 
    726 const char *
    727 inotype(u_int type)
    728 {
    729 
    730 	switch (type & S_IFMT) {
    731 	case S_IFBLK:
    732 		return ("block");
    733 	case S_IFCHR:
    734 		return ("char");
    735 	case S_IFDIR:
    736 		return ("dir");
    737 	case S_IFIFO:
    738 		return ("fifo");
    739 	case S_IFREG:
    740 		return ("file");
    741 	case S_IFLNK:
    742 		return ("link");
    743 	case S_IFSOCK:
    744 		return ("socket");
    745 	default:
    746 		return ("unknown");
    747 	}
    748 	/* NOTREACHED */
    749 }
    750 
    751 /*
    752  * metadata_log --
    753  *	if metafp is not NULL, output mtree(8) full path name and settings to
    754  *	metafp, to allow permissions to be set correctly by other tools.
    755  */
    756 void
    757 metadata_log(const char *path, mode_t type, struct timeval *tv,
    758 	const char *link)
    759 {
    760 	const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
    761 	char		*buf;
    762 
    763 	if (!metafp)
    764 		return;
    765 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
    766 	if (buf == NULL) {
    767 		warnx("%s", strerror(ENOMEM));
    768 		return;
    769 	}
    770 	if (flock(fileno(metafp), LOCK_EX) == -1) {	/* lock log file */
    771 		warn("can't lock %s", metafile);
    772 		return;
    773 	}
    774 
    775 	strsvis(buf, path, VIS_CSTYLE, extra);		/* encode name */
    776 	fprintf(metafp, ".%s%s type=%s mode=%#o",	/* print details */
    777 	    buf[0] == '/' ? "" : "/", buf, inotype(type), mode);
    778 	if (link)
    779 		fprintf(metafp, " link=%s", link);
    780 	if (owner)
    781 		fprintf(metafp, " uname=%s", owner);
    782 	if (group)
    783 		fprintf(metafp, " gname=%s", group);
    784 	if (fflags)
    785 		fprintf(metafp, " flags=%s", fflags);
    786 	if (tags)
    787 		fprintf(metafp, " tags=%s", tags);
    788 	if (tv != NULL && dopreserve)
    789 		fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
    790 	fputc('\n', metafp);
    791 	fflush(metafp);					/* flush output */
    792 	if (flock(fileno(metafp), LOCK_UN) == -1) {	/* unlock log file */
    793 		warn("can't unlock %s", metafile);
    794 	}
    795 	free(buf);
    796 }
    797 
    798 
    799 
    800 /*
    801  * usage --
    802  *	print a usage message and die
    803  */
    804 void
    805 usage(void)
    806 {
    807 
    808 	(void)fprintf(stderr, "\
    809 usage: install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    810 	    [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 file2\n\
    811        install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    812 	    [-o owner] [-g group] [-l linkflags] [-S stripflags]\n\
    813 	    file1 ... fileN directory\n\
    814        install [-Up] [-M log] [-T tags] -d [-m mode]\n\
    815 	    [-o owner] [-g group] directory ...\n");
    816 	exit(1);
    817 }
    818