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