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