Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.56
      1 /*	$NetBSD: xinstall.c,v 1.56 2001/10/29 00:25:44 perry 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.56 2001/10/29 00:25:44 perry 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 void	install(char *, char *, u_int);
    102 void	install_dir(char *, u_int);
    103 int	main(int, char *[]);
    104 void	makelink(char *, char *);
    105 int	parseid(char *, id_t *);
    106 void	strip(char *);
    107 void	metadata_log(const char *, mode_t, u_int, struct timeval *);
    108 void	usage(void);
    109 
    110 int
    111 main(int argc, char *argv[])
    112 {
    113 	struct stat	from_sb, to_sb;
    114 	void		*set;
    115 	u_int		iflags;
    116 	int		ch, no_target;
    117 	char		*p, *to_name;
    118 
    119 	setprogname(argv[0]);
    120 
    121 	iflags = 0;
    122 	while ((ch = getopt(argc, argv, "cbB:df:g:l:m:M:o:prsS:T:U")) != -1)
    123 		switch((char)ch) {
    124 		case 'B':
    125 			suffix = optarg;
    126 			numberedbackup = 0;
    127 			{
    128 				/* Check if given suffix really generates
    129 				   different suffixes - catch e.g. ".%" */
    130 				char suffix_expanded0[FILENAME_MAX],
    131 				     suffix_expanded1[FILENAME_MAX];
    132 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
    133 					       suffix, 0);
    134 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
    135 					       suffix, 1);
    136 				if (strcmp(suffix_expanded0, suffix_expanded1)
    137 				    != 0)
    138 					numberedbackup = 1;
    139 			}
    140 			/* fall through; -B implies -b */
    141 		case 'b':
    142 			dobackup = 1;
    143 			break;
    144 		case 'c':
    145 			docopy = 1;
    146 			break;
    147 		case 'd':
    148 			dodir = 1;
    149 			break;
    150 		case 'f':
    151 			fflags = optarg;
    152 			break;
    153 		case 'g':
    154 			group = optarg;
    155 			break;
    156 		case 'l':
    157 			for (p = optarg; *p; p++)
    158 				switch (*p) {
    159 				case 's':
    160 					dolink &= ~(LN_HARD|LN_MIXED);
    161 					dolink |= LN_SYMBOLIC;
    162 					break;
    163 				case 'h':
    164 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    165 					dolink |= LN_HARD;
    166 					break;
    167 				case 'm':
    168 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    169 					dolink |= LN_MIXED;
    170 					break;
    171 				case 'a':
    172 					dolink &= ~LN_RELATIVE;
    173 					dolink |= LN_ABSOLUTE;
    174 					break;
    175 				case 'r':
    176 					dolink &= ~LN_ABSOLUTE;
    177 					dolink |= LN_RELATIVE;
    178 					break;
    179 				default:
    180 					errx(1, "%c: invalid link type", *p);
    181 					break;
    182 				}
    183 			break;
    184 		case 'm':
    185 			if (!(set = setmode(optarg)))
    186 				errx(1, "%s: invalid file mode", optarg);
    187 			mode = getmode(set, 0);
    188 			free(set);
    189 			break;
    190 		case 'M':
    191 			metafile = optarg;
    192 			break;
    193 		case 'o':
    194 			owner = optarg;
    195 			break;
    196 		case 'p':
    197 			dopreserve = 1;
    198 			break;
    199 		case 'r':
    200 			dorename = 1;
    201 			break;
    202 		case 'S':
    203 			stripArgs = strdup(optarg);
    204 			if (stripArgs == NULL)
    205 				errx(1, "%s", strerror(ENOMEM));
    206 			/* fall through; -S implies -s */
    207 		case 's':
    208 			dostrip = 1;
    209 			break;
    210 		case 'T':
    211 			tags = optarg;
    212 			break;
    213 		case 'U':
    214 			dounpriv = 1;
    215 			break;
    216 		case '?':
    217 		default:
    218 			usage();
    219 		}
    220 	argc -= optind;
    221 	argv += optind;
    222 
    223 	/* strip and link options make no sense when creating directories */
    224 	if ((dostrip || dolink) && dodir)
    225 		usage();
    226 
    227 	/* strip and flags make no sense with links */
    228 	if ((dostrip || fflags) && dolink)
    229 		usage();
    230 
    231 	/* must have at least two arguments, except when creating directories */
    232 	if (argc < 2 && !dodir)
    233 		usage();
    234 
    235 	/* get group and owner id's */
    236 	if (group && !dounpriv) {
    237 		struct group *gp;
    238 
    239 		if ((gp = getgrnam(group)) != NULL)
    240 			gid = gp->gr_gid;
    241 		else if (! parseid(group, &gid))
    242 			errx(1, "unknown group %s", group);
    243 		iflags |= HASGID;
    244 	}
    245 	if (owner && !dounpriv) {
    246 		struct passwd *pp;
    247 
    248 		if ((pp = getpwnam(owner)) != NULL)
    249 			uid = pp->pw_uid;
    250 		else if (! parseid(owner, &uid))
    251 			errx(1, "unknown user %s", owner);
    252 		iflags |= HASUID;
    253 	}
    254 
    255 	if (fflags && !dounpriv) {
    256 		if (string_to_flags(&fflags, &fileflags, NULL))
    257 			errx(1, "%s: invalid flag", fflags);
    258 		iflags |= SETFLAGS;
    259 	}
    260 
    261 	if (metafile) {
    262 		if ((metafp = fopen(metafile, "a")) == NULL)
    263 			warn("open %s", metafile);
    264 	}
    265 
    266 	if (dodir) {
    267 		for (; *argv != NULL; ++argv)
    268 			install_dir(*argv, iflags);
    269 		exit (0);
    270 	}
    271 
    272 	no_target = stat(to_name = argv[argc - 1], &to_sb);
    273 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
    274 		for (; *argv != to_name; ++argv)
    275 			install(*argv, to_name, iflags | DIRECTORY);
    276 		exit(0);
    277 	}
    278 
    279 	/* can't do file1 file2 directory/file */
    280 	if (argc != 2)
    281 		usage();
    282 
    283 	if (!no_target) {
    284 		if (stat(*argv, &from_sb))
    285 			err(1, "%s", *argv);
    286 		if (!S_ISREG(to_sb.st_mode))
    287 			errx(1, "%s: not a regular file", to_name);
    288 		if (!dolink && to_sb.st_dev == from_sb.st_dev &&
    289 		    to_sb.st_ino == from_sb.st_ino)
    290 			errx(1, "%s and %s are the same file", *argv, to_name);
    291 		/*
    292 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    293 		 * off the append/immutable bits -- if we fail, go ahead,
    294 		 * it might work.
    295 		 */
    296 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
    297 		if (to_sb.st_flags & NOCHANGEBITS)
    298 			(void)chflags(to_name,
    299 			    to_sb.st_flags & ~(NOCHANGEBITS));
    300 		if (dobackup)
    301 			backup(to_name);
    302 		else if (!dorename)
    303 			(void)unlink(to_name);
    304 	}
    305 	install(*argv, to_name, iflags);
    306 	exit(0);
    307 }
    308 
    309 /*
    310  * parseid --
    311  *	parse uid or gid from arg into id, returning non-zero if successful
    312  */
    313 int
    314 parseid(char *name, id_t *id)
    315 {
    316 	char	*ep;
    317 
    318 	errno = 0;
    319 	*id = (id_t)strtoul(name, &ep, 10);
    320 	if (errno || *ep != '\0')
    321 		return (0);
    322 	return (1);
    323 }
    324 
    325 /*
    326  * makelink --
    327  *	make a link from source to destination
    328  */
    329 void
    330 makelink(char *from_name, char *to_name)
    331 {
    332 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
    333 
    334 	/* Try hard links first */
    335 	if (dolink & (LN_HARD|LN_MIXED)) {
    336 		if (link(from_name, to_name) == -1) {
    337 			if ((dolink & LN_HARD) || errno != EXDEV)
    338 				err(1, "link %s -> %s", from_name, to_name);
    339 		}
    340 		else
    341 			return;
    342 	}
    343 
    344 	/* Symbolic links */
    345 	if (dolink & LN_ABSOLUTE) {
    346 		/* Convert source path to absolute */
    347 		if (realpath(from_name, src) == NULL)
    348 			err(1, "%s", src);
    349 		if (symlink(src, to_name) == -1)
    350 			err(1, "symlink %s -> %s", src, to_name);
    351 		return;
    352 	}
    353 
    354 	if (dolink & LN_RELATIVE) {
    355 		char *s, *d;
    356 
    357 		/* Resolve pathnames */
    358 		if (realpath(from_name, src) == NULL)
    359 			err(1, "%s", src);
    360 		if (realpath(to_name, dst) == NULL)
    361 			err(1, "%s", dst);
    362 
    363 		/* trim common path components */
    364 		for (s = src, d = dst; *s == *d; s++, d++)
    365 			continue;
    366 		while (*s != '/')
    367 			s--, d--;
    368 
    369 		/* count the number of directories we need to backtrack */
    370 		for (++d, lnk[0] = '\0'; *d; d++)
    371 			if (*d == '/')
    372 				(void) strcat(lnk, "../");
    373 
    374 		(void) strcat(lnk, ++s);
    375 
    376 		if (symlink(lnk, dst) == -1)
    377 			err(1, "symlink %s -> %s", lnk, dst);
    378 		return;
    379 	}
    380 
    381 	/*
    382 	 * If absolute or relative was not specified,
    383 	 * try the names the user provided
    384 	 */
    385 	if (symlink(from_name, to_name) == -1)
    386 		err(1, "symlink %s -> %s", from_name, to_name);
    387 
    388 }
    389 
    390 /*
    391  * install --
    392  *	build a path name and install the file
    393  */
    394 void
    395 install(char *from_name, char *to_name, u_int flags)
    396 {
    397 	struct stat	from_sb, to_sb;
    398 	struct timeval	tv[2];
    399 	int		devnull, from_fd, to_fd, serrno;
    400 	char		*p, tmpl[MAXPATHLEN], *oto_name;
    401 
    402 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    403 		if (!dolink) {
    404 			if (stat(from_name, &from_sb))
    405 				err(1, "%s", from_name);
    406 			if (!S_ISREG(from_sb.st_mode))
    407 				errx(1, "%s: not a regular file", from_name);
    408 		}
    409 		/* Build the target path. */
    410 		if (flags & DIRECTORY) {
    411 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    412 			    to_name,
    413 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    414 			to_name = pathbuf;
    415 		}
    416 		devnull = 0;
    417 	} else {
    418 		from_sb.st_flags = 0;	/* XXX */
    419 		devnull = 1;
    420 	}
    421 
    422 	/*
    423 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    424 	 * off the append/immutable bits -- if we fail, go ahead,
    425 	 * it might work.
    426 	 */
    427 	if (stat(to_name, &to_sb) == 0 &&
    428 	    to_sb.st_flags & (NOCHANGEBITS))
    429 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    430 	if (dorename) {
    431 		char *ptr, c, *dir;
    432 
    433 		if ((ptr = strrchr(to_name, '/')) != NULL) {
    434 			c = *++ptr;
    435 			*ptr = '\0';
    436 			dir = to_name;
    437 		} else {
    438 			c = '\0';	/* pacify gcc */
    439 			dir = tmpl;
    440 			*dir = '\0';
    441 		}
    442 		(void)snprintf(tmpl, sizeof(tmpl), "%sinst.XXXXXX", dir);
    443 		if (ptr)
    444 			*ptr = c;
    445 		oto_name = to_name;
    446 		to_name = tmpl;
    447 
    448 	} else {
    449 		oto_name = NULL;	/* pacify gcc */
    450 		if (dobackup)
    451 			backup(to_name);
    452 		else
    453 			(void)unlink(to_name);
    454 	}
    455 
    456 	if (dolink) {
    457 		makelink(from_name, to_name);
    458 		return;
    459 	}
    460 
    461 	/* Create target. */
    462 	if (dorename) {
    463 		if ((to_fd = mkstemp(to_name)) == -1)
    464 			err(1, "%s", to_name);
    465 	} else {
    466 		if ((to_fd = open(to_name,
    467 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    468 			err(1, "%s", to_name);
    469 	}
    470 	if (!devnull) {
    471 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    472 			(void)unlink(to_name);
    473 			err(1, "%s", from_name);
    474 		}
    475 		copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    476 		(void)close(from_fd);
    477 	}
    478 
    479 	if (dostrip) {
    480 		strip(to_name);
    481 
    482 		/*
    483 		 * Re-open our fd on the target, in case we used a strip
    484 		 *  that does not work in-place -- like gnu binutils strip.
    485 		 */
    486 		close(to_fd);
    487 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    488 		  err(1, "stripping %s", to_name);
    489 	}
    490 
    491 	/*
    492 	 * Set owner, group, mode for target; do the chown first,
    493 	 * chown may lose the setuid bits.
    494 	 */
    495 	if (!dounpriv &&
    496 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    497 		serrno = errno;
    498 		(void)unlink(to_name);
    499 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    500 	}
    501 	if (!dounpriv && fchmod(to_fd, mode) == -1) {
    502 		serrno = errno;
    503 		(void)unlink(to_name);
    504 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    505 	}
    506 
    507 	/*
    508 	 * Preserve the date of the source file.
    509 	 */
    510 	if (dopreserve) {
    511 #ifdef BSD4_4
    512 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    513 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    514 #else
    515 		tv[0].tv_sec = from_sb.st_atime;
    516 		tv[0].tv_usec = 0;
    517 		tv[1].tv_sec = from_sb.st_mtime;
    518 		tv[1].tv_usec = 0;
    519 #endif
    520 		if (!dounpriv && futimes(to_fd, tv) == -1)
    521 			warn("%s: futimes", to_name);
    522 	}
    523 
    524 	(void)close(to_fd);
    525 
    526 	if (dorename) {
    527 		if (rename(to_name, oto_name) == -1)
    528 			err(1, "%s: rename", to_name);
    529 		to_name = oto_name;
    530 	}
    531 
    532 	if (!docopy && !devnull && unlink(from_name))
    533 		err(1, "%s", from_name);
    534 
    535 	/*
    536 	 * If provided a set of flags, set them, otherwise, preserve the
    537 	 * flags, except for the dump flag.
    538 	 */
    539 	if (!dounpriv && chflags(to_name,
    540 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    541 	{
    542 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    543 			warn("%s: chflags", to_name);
    544 	}
    545 
    546 	metadata_log(to_name, S_IFREG, flags, dopreserve ? tv : NULL);
    547 }
    548 
    549 /*
    550  * copy --
    551  *	copy from one file to another
    552  */
    553 void
    554 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    555 {
    556 	ssize_t	nr, nw;
    557 	int	serrno;
    558 	char	*p;
    559 	char	buf[MAXBSIZE];
    560 
    561 	/*
    562 	 * There's no reason to do anything other than close the file
    563 	 * now if it's empty, so let's not bother.
    564 	 */
    565 	if (size > 0) {
    566 
    567 		/*
    568 		 * Mmap and write if less than 8M (the limit is so we
    569 		 * don't totally trash memory on big files).  This is
    570 		 * really a minor hack, but it wins some CPU back.
    571 		 */
    572 
    573 		if (size <= 8 * 1048576) {
    574 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    575 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    576 			    == MAP_FAILED) {
    577 				goto mmap_failed;
    578 			}
    579 #ifdef MADV_SEQUENTIAL
    580 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    581 			    && errno != EOPNOTSUPP)
    582 				warnx("madvise: %s", strerror(errno));
    583 #endif
    584 
    585 			if (write(to_fd, p, size) != size) {
    586 				serrno = errno;
    587 				(void)unlink(to_name);
    588 				errx(1, "%s: %s",
    589 				    to_name, strerror(serrno));
    590 			}
    591 		} else {
    592 mmap_failed:
    593 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    594 				if ((nw = write(to_fd, buf, nr)) != nr) {
    595 					serrno = errno;
    596 					(void)unlink(to_name);
    597 					errx(1, "%s: %s", to_name,
    598 					    strerror(nw > 0 ? EIO : serrno));
    599 				}
    600 			}
    601 			if (nr != 0) {
    602 				serrno = errno;
    603 				(void)unlink(to_name);
    604 				errx(1, "%s: %s", from_name, strerror(serrno));
    605 			}
    606 		}
    607 	}
    608 }
    609 
    610 /*
    611  * strip --
    612  *	use strip(1) to strip the target file
    613  */
    614 void
    615 strip(char *to_name)
    616 {
    617 	int	serrno, status;
    618 	char	*stripprog;
    619 
    620 	switch (vfork()) {
    621 	case -1:
    622 		serrno = errno;
    623 		(void)unlink(to_name);
    624 		errx(1, "vfork: %s", strerror(serrno));
    625 	case 0:
    626 		stripprog = getenv("STRIP");
    627 		if (stripprog == NULL)
    628 			stripprog = _PATH_STRIP;
    629 
    630 		if (stripArgs) {
    631 			/*
    632 			 * build up a command line and let /bin/sh
    633 			 * parse the arguments
    634 			 */
    635 			char* cmd = (char*)malloc(sizeof(char)*
    636 						  (3+strlen(stripprog)+
    637 						     strlen(stripArgs)+
    638 						     strlen(to_name)));
    639 
    640 			if (cmd == NULL)
    641 				errx(1, "%s", strerror(ENOMEM));
    642 
    643 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    644 
    645 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    646 		} else
    647 			execlp(stripprog, "strip", to_name, NULL);
    648 
    649 		warn("%s", stripprog);
    650 		_exit(1);
    651 	default:
    652 		if (wait(&status) == -1 || status)
    653 			(void)unlink(to_name);
    654 	}
    655 }
    656 
    657 /*
    658  * backup file "to_name" to to_name.suffix
    659  * if suffix contains a "%", it's taken as a printf(3) pattern
    660  * used for a numbered backup.
    661  */
    662 void
    663 backup(const char *to_name)
    664 {
    665 	char	backup[FILENAME_MAX];
    666 
    667 	if (numberedbackup) {
    668 		/* Do numbered backup */
    669 		int cnt;
    670 		char suffix_expanded[FILENAME_MAX];
    671 
    672 		cnt=0;
    673 		do {
    674 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    675 			    cnt);
    676 			(void)snprintf(backup, FILENAME_MAX, "%s%s",
    677 				       to_name, suffix_expanded);
    678 			cnt++;
    679 		} while (access(backup, F_OK)==0);
    680 	} else {
    681 		/* Do simple backup */
    682 		(void)snprintf(backup, FILENAME_MAX, "%s%s", to_name, suffix);
    683 	}
    684 
    685 	(void)rename(to_name, backup);
    686 }
    687 
    688 /*
    689  * install_dir --
    690  *	build directory hierarchy
    691  */
    692 void
    693 install_dir(char *path, u_int flags)
    694 {
    695         char		*p;
    696         struct stat	sb;
    697         int		ch;
    698 
    699         for (p = path;; ++p)
    700                 if (!*p || (p != path && *p  == '/')) {
    701                         ch = *p;
    702                         *p = '\0';
    703                         if (stat(path, &sb)) {
    704                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    705 					err(1, "%s", path);
    706 					/* NOTREACHED */
    707                                 }
    708                         }
    709                         if (!(*p = ch))
    710 				break;
    711                 }
    712 
    713 	if (!dounpriv && (
    714 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
    715 	    || chmod(path, mode) == -1 )) {
    716                 warn("%s", path);
    717 	}
    718 	metadata_log(path, S_IFDIR, flags & ~SETFLAGS, NULL);
    719 }
    720 
    721 /*
    722  * metadata_log --
    723  *	if metafp is not NULL, output mtree(8) full path name and settings to
    724  *	metafp, to allow permissions to be set correctly by other tools.
    725  */
    726 void
    727 metadata_log(const char *path, mode_t type, u_int flags, struct timeval *tv)
    728 {
    729 	const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
    730 	char		*buf;
    731 
    732 	if (!metafp)
    733 		return;
    734 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
    735 	if (buf == NULL) {
    736 		warnx("%s", strerror(ENOMEM));
    737 		return;
    738 	}
    739 	if (flock(fileno(metafp), LOCK_EX) == -1) {	/* lock log file */
    740 		warn("can't lock %s", metafile);
    741 		return;
    742 	}
    743 
    744 	strsvis(buf, path, VIS_CSTYLE, extra);		/* encode name */
    745 	fprintf(metafp, ".%s%s type=%s mode=%#o",	/* print details */
    746 	    buf[0] == '/' ? "" : "/", buf,
    747 	    S_ISDIR(type) ? "dir" : "file", mode);
    748 	if (owner)
    749 		fprintf(metafp, " uname=%s", owner);
    750 	if (group)
    751 		fprintf(metafp, " gname=%s", group);
    752 	if (fflags)
    753 		fprintf(metafp, " flags=%s", fflags);
    754 	if (tags)
    755 		fprintf(metafp, " tags=%s", tags);
    756 	if (tv != NULL)
    757 		fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
    758 	fputc('\n', metafp);
    759 	fflush(metafp);					/* flush output */
    760 	if (flock(fileno(metafp), LOCK_UN) == -1) {	/* unlock log file */
    761 		warn("can't unlock %s", metafile);
    762 	}
    763 	free(buf);
    764 }
    765 
    766 
    767 
    768 /*
    769  * usage --
    770  *	print a usage message and die
    771  */
    772 void
    773 usage(void)
    774 {
    775 
    776 	(void)fprintf(stderr, "\
    777 usage: install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    778 	    [-o owner] [-g group] [-l linkflags] [-S stripflags] file1 file2\n\
    779        install [-Ubcprs] [-M log] [-T tags] [-B suffix] [-f flags] [-m mode]\n\
    780 	    [-o owner] [-g group] [-l linkflags] [-S stripflags]\n\
    781 	    file1 ... fileN directory\n\
    782        install [-Up] [-M log] [-T tags] -d [-m mode]\n\
    783 	    [-o owner] [-g group] directory ...\n");
    784 	exit(1);
    785 }
    786