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