Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.105
      1 /*	$NetBSD: xinstall.c,v 1.105 2008/12/28 18:38:27 christos 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. Neither the name of the University nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #if HAVE_NBTOOL_CONFIG_H
     33 #include "nbtool_config.h"
     34 #else
     35 #define HAVE_FUTIMES 1
     36 #define HAVE_STRUCT_STAT_ST_FLAGS 1
     37 #endif
     38 
     39 #include <sys/cdefs.h>
     40 #if defined(__COPYRIGHT) && !defined(lint)
     41 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\
     42  The Regents of the University of California.  All rights reserved.");
     43 #endif /* not lint */
     44 
     45 #if defined(__RCSID) && !defined(lint)
     46 #if 0
     47 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
     48 #else
     49 __RCSID("$NetBSD: xinstall.c,v 1.105 2008/12/28 18:38:27 christos Exp $");
     50 #endif
     51 #endif /* not lint */
     52 
     53 #define __MKTEMP_OK__	/* All uses of mktemp have been checked */
     54 #include <sys/param.h>
     55 #include <sys/mman.h>
     56 #include <sys/stat.h>
     57 #include <sys/wait.h>
     58 #include <sys/time.h>
     59 
     60 #include <ctype.h>
     61 #include <err.h>
     62 #include <errno.h>
     63 #include <fcntl.h>
     64 #include <grp.h>
     65 #include <libgen.h>
     66 #include <paths.h>
     67 #include <pwd.h>
     68 #include <stdio.h>
     69 #include <stdlib.h>
     70 #include <string.h>
     71 #include <unistd.h>
     72 #include <util.h>
     73 #include <vis.h>
     74 
     75 #include <md5.h>
     76 #include <rmd160.h>
     77 #include <sha1.h>
     78 
     79 #include "pathnames.h"
     80 #include "mtree.h"
     81 
     82 #define STRIP_ARGS_MAX 32
     83 #define BACKUP_SUFFIX ".old"
     84 
     85 int	dobackup, dodir, dostrip, dolink, dopreserve, dorename, dounpriv;
     86 int	numberedbackup;
     87 int	mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
     88 char	pathbuf[MAXPATHLEN];
     89 id_t	uid = -1, gid = -1;
     90 char	*group, *owner, *fflags, *tags;
     91 FILE	*metafp;
     92 char	*metafile;
     93 u_long	fileflags;
     94 char	*stripArgs;
     95 char	*afterinstallcmd;
     96 char	*suffix = BACKUP_SUFFIX;
     97 char	*destdir;
     98 
     99 enum {
    100 	DIGEST_NONE = 0,
    101 	DIGEST_MD5,
    102 	DIGEST_RMD160,
    103 	DIGEST_SHA1,
    104 } digesttype = DIGEST_NONE;
    105 char	*digest;
    106 
    107 #define LN_ABSOLUTE	0x01
    108 #define LN_RELATIVE	0x02
    109 #define LN_HARD		0x04
    110 #define LN_SYMBOLIC	0x08
    111 #define LN_MIXED	0x10
    112 
    113 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
    114 #define	SETFLAGS	0x02		/* Tell install to set flags. */
    115 #define	HASUID		0x04		/* Tell install the uid was given */
    116 #define	HASGID		0x08		/* Tell install the gid was given */
    117 
    118 void	afterinstall(const char *, const char *, int);
    119 void	backup(const char *);
    120 char   *copy(int, char *, int, char *, off_t);
    121 int	do_link(char *, char *);
    122 void	do_symlink(char *, char *);
    123 void	install(char *, char *, u_int);
    124 void	install_dir(char *, u_int);
    125 int	main(int, char *[]);
    126 void	makelink(char *, char *);
    127 void	metadata_log(const char *, const char *, struct timeval *,
    128 	    const char *, const char *);
    129 int	parseid(char *, id_t *);
    130 void	strip(char *);
    131 void	usage(void);
    132 char   *xbasename(char *);
    133 char   *xdirname(char *);
    134 
    135 int
    136 main(int argc, char *argv[])
    137 {
    138 	struct stat	from_sb, to_sb;
    139 	void		*set;
    140 	u_int		iflags;
    141 	int		ch, no_target;
    142 	char		*p, *to_name;
    143 
    144 	setprogname(argv[0]);
    145 
    146 	iflags = 0;
    147 	while ((ch = getopt(argc, argv, "a:cbB:dD:f:g:h:l:m:M:N:o:prsS:T:U"))
    148 	    != -1)
    149 		switch((char)ch) {
    150 		case 'a':
    151 			afterinstallcmd = strdup(optarg);
    152 			if (afterinstallcmd == NULL)
    153 				errx(1, "%s", strerror(ENOMEM));
    154 			break;
    155 		case 'B':
    156 			suffix = optarg;
    157 			numberedbackup = 0;
    158 			{
    159 				/* Check if given suffix really generates
    160 				   different suffixes - catch e.g. ".%" */
    161 				char suffix_expanded0[FILENAME_MAX],
    162 				     suffix_expanded1[FILENAME_MAX];
    163 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
    164 					       suffix, 0);
    165 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
    166 					       suffix, 1);
    167 				if (strcmp(suffix_expanded0, suffix_expanded1)
    168 				    != 0)
    169 					numberedbackup = 1;
    170 			}
    171 			/* fall through; -B implies -b */
    172 			/*FALLTHROUGH*/
    173 		case 'b':
    174 			dobackup = 1;
    175 			break;
    176 		case 'c':
    177 			/* ignored; was "docopy" which is now the default. */
    178 			break;
    179 		case 'd':
    180 			dodir = 1;
    181 			break;
    182 		case 'D':
    183 			destdir = optarg;
    184 			break;
    185 #if ! HAVE_NBTOOL_CONFIG_H
    186 		case 'f':
    187 			fflags = optarg;
    188 			break;
    189 #endif
    190 		case 'g':
    191 			group = optarg;
    192 			break;
    193 		case 'h':
    194 			digest = optarg;
    195 			break;
    196 		case 'l':
    197 			for (p = optarg; *p; p++)
    198 				switch (*p) {
    199 				case 's':
    200 					dolink &= ~(LN_HARD|LN_MIXED);
    201 					dolink |= LN_SYMBOLIC;
    202 					break;
    203 				case 'h':
    204 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    205 					dolink |= LN_HARD;
    206 					break;
    207 				case 'm':
    208 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    209 					dolink |= LN_MIXED;
    210 					break;
    211 				case 'a':
    212 					dolink &= ~LN_RELATIVE;
    213 					dolink |= LN_ABSOLUTE;
    214 					break;
    215 				case 'r':
    216 					dolink &= ~LN_ABSOLUTE;
    217 					dolink |= LN_RELATIVE;
    218 					break;
    219 				default:
    220 					errx(1, "%c: invalid link type", *p);
    221 					/* NOTREACHED */
    222 				}
    223 			break;
    224 		case 'm':
    225 			if (!(set = setmode(optarg)))
    226 				err(1, "Cannot set file mode `%s'", optarg);
    227 			mode = getmode(set, 0);
    228 			free(set);
    229 			break;
    230 		case 'M':
    231 			metafile = optarg;
    232 			break;
    233 		case 'N':
    234 			if (! setup_getid(optarg))
    235 				errx(1,
    236 			    "Unable to use user and group databases in `%s'",
    237 				    optarg);
    238 			break;
    239 		case 'o':
    240 			owner = optarg;
    241 			break;
    242 		case 'p':
    243 			dopreserve = 1;
    244 			break;
    245 		case 'r':
    246 			dorename = 1;
    247 			break;
    248 		case 'S':
    249 			stripArgs = strdup(optarg);
    250 			if (stripArgs == NULL)
    251 				errx(1, "%s", strerror(ENOMEM));
    252 			/* fall through; -S implies -s */
    253 			/*FALLTHROUGH*/
    254 		case 's':
    255 			dostrip = 1;
    256 			break;
    257 		case 'T':
    258 			tags = optarg;
    259 			break;
    260 		case 'U':
    261 			dounpriv = 1;
    262 			break;
    263 		case '?':
    264 		default:
    265 			usage();
    266 		}
    267 	argc -= optind;
    268 	argv += optind;
    269 
    270 	/* strip and link options make no sense when creating directories */
    271 	if ((dostrip || dolink) && dodir)
    272 		usage();
    273 
    274 	/* strip and flags make no sense with links */
    275 	if ((dostrip || fflags) && dolink)
    276 		usage();
    277 
    278 	/* must have at least two arguments, except when creating directories */
    279 	if (argc < 2 && !dodir)
    280 		usage();
    281 
    282 	if (digest) {
    283 		if (0) {
    284 		} else if (strcmp(digest, "none") == 0) {
    285 			digesttype = DIGEST_NONE;
    286 		} else if (strcmp(digest, "md5") == 0) {
    287 			digesttype = DIGEST_MD5;
    288 		} else if (strcmp(digest, "rmd160") == 0) {
    289 			digesttype = DIGEST_RMD160;
    290 		} else if (strcmp(digest, "sha1") == 0) {
    291 			digesttype = DIGEST_SHA1;
    292 		} else {
    293 			warnx("unknown digest `%s'", digest);
    294 			usage();
    295 		}
    296 	}
    297 
    298 	/* get group and owner id's */
    299 	if (group && !dounpriv) {
    300 		if (gid_from_group(group, &gid) == -1 && ! parseid(group, &gid))
    301 			errx(1, "unknown group %s", group);
    302 		iflags |= HASGID;
    303 	}
    304 	if (owner && !dounpriv) {
    305 		if (uid_from_user(owner, &uid) == -1 && ! parseid(owner, &uid))
    306 			errx(1, "unknown user %s", owner);
    307 		iflags |= HASUID;
    308 	}
    309 
    310 #if ! HAVE_NBTOOL_CONFIG_H
    311 	if (fflags && !dounpriv) {
    312 		if (string_to_flags(&fflags, &fileflags, NULL))
    313 			errx(1, "%s: invalid flag", fflags);
    314 		/* restore fflags since string_to_flags() changed it */
    315 		fflags = flags_to_string(fileflags, "-");
    316 		iflags |= SETFLAGS;
    317 	}
    318 #endif
    319 
    320 	if (metafile) {
    321 		if ((metafp = fopen(metafile, "a")) == NULL)
    322 			warn("open %s", metafile);
    323 	} else
    324 		digesttype = DIGEST_NONE;
    325 
    326 	if (dodir) {
    327 		for (; *argv != NULL; ++argv)
    328 			install_dir(*argv, iflags);
    329 		exit (0);
    330 	}
    331 
    332 	no_target = stat(to_name = argv[argc - 1], &to_sb);
    333 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
    334 		for (; *argv != to_name; ++argv)
    335 			install(*argv, to_name, iflags | DIRECTORY);
    336 		exit(0);
    337 	}
    338 
    339 	/* can't do file1 file2 directory/file */
    340 	if (argc != 2) {
    341 		errx(EXIT_FAILURE, "the last argument (%s) "
    342 		    "must name an existing directory", argv[argc - 1]);
    343 		/* NOTREACHED */
    344 	}
    345 
    346 	if (!no_target) {
    347 		/* makelink() handles checks for links */
    348 		if (!dolink) {
    349 			if (stat(*argv, &from_sb))
    350 				err(1, "%s: stat", *argv);
    351 			if (!S_ISREG(to_sb.st_mode))
    352 				errx(1, "%s: not a regular file", to_name);
    353 			if (to_sb.st_dev == from_sb.st_dev &&
    354 			    to_sb.st_ino == from_sb.st_ino)
    355 				errx(1, "%s and %s are the same file", *argv,
    356 				    to_name);
    357 		}
    358 		/*
    359 		 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    360 		 * off the append/immutable bits -- if we fail, go ahead,
    361 		 * it might work.
    362 		 */
    363 #if ! HAVE_NBTOOL_CONFIG_H
    364 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
    365 		if (to_sb.st_flags & NOCHANGEBITS)
    366 			(void)chflags(to_name,
    367 			    to_sb.st_flags & ~(NOCHANGEBITS));
    368 #endif
    369 		if (dobackup)
    370 			backup(to_name);
    371 		else if (!dorename)
    372 			(void)unlink(to_name);
    373 	}
    374 	install(*argv, to_name, iflags);
    375 	exit(0);
    376 }
    377 
    378 /*
    379  * parseid --
    380  *	parse uid or gid from arg into id, returning non-zero if successful
    381  */
    382 int
    383 parseid(char *name, id_t *id)
    384 {
    385 	char	*ep;
    386 
    387 	errno = 0;
    388 	*id = (id_t)strtoul(name, &ep, 10);
    389 	if (errno || *ep != '\0')
    390 		return (0);
    391 	return (1);
    392 }
    393 
    394 /*
    395  * do_link --
    396  *	make a hard link, obeying dorename if set
    397  *	return -1 on failure
    398  */
    399 int
    400 do_link(char *from_name, char *to_name)
    401 {
    402 	char tmpl[MAXPATHLEN];
    403 	int ret;
    404 
    405 	if (dorename) {
    406 		(void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
    407 		    xdirname(to_name));
    408 		/* This usage is safe. */
    409 		if (mktemp(tmpl) == NULL)
    410 			err(1, "%s: mktemp", tmpl);
    411 		ret = link(from_name, tmpl);
    412 		if (ret == 0) {
    413 			ret = rename(tmpl, to_name);
    414 			/* If rename has posix semantics, then the temporary
    415 			 * file may still exist when from_name and to_name point
    416 			 * to the same file, so unlink it unconditionally.
    417 			 */
    418 			(void)unlink(tmpl);
    419 		}
    420 		return (ret);
    421 	} else
    422 		return (link(from_name, to_name));
    423 }
    424 
    425 /*
    426  * do_symlink --
    427  *	make a symbolic link, obeying dorename if set
    428  *	exit on failure
    429  */
    430 void
    431 do_symlink(char *from_name, char *to_name)
    432 {
    433 	char tmpl[MAXPATHLEN];
    434 
    435 	if (dorename) {
    436 		(void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
    437 		    xdirname(to_name));
    438 		/* This usage is safe. */
    439 		if (mktemp(tmpl) == NULL)
    440 			err(1, "%s: mktemp", tmpl);
    441 
    442 		if (symlink(from_name, tmpl) == -1)
    443 			err(1, "symlink %s -> %s", from_name, tmpl);
    444 		if (rename(tmpl, to_name) == -1) {
    445 			/* remove temporary link before exiting */
    446 			(void)unlink(tmpl);
    447 			err(1, "%s: rename", to_name);
    448 		}
    449 	} else {
    450 		if (symlink(from_name, to_name) == -1)
    451 			err(1, "symlink %s -> %s", from_name, to_name);
    452 	}
    453 }
    454 
    455 /*
    456  * makelink --
    457  *	make a link from source to destination
    458  */
    459 void
    460 makelink(char *from_name, char *to_name)
    461 {
    462 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
    463 	struct stat	to_sb;
    464 
    465 	/* Try hard links first */
    466 	if (dolink & (LN_HARD|LN_MIXED)) {
    467 		if (do_link(from_name, to_name) == -1) {
    468 			if ((dolink & LN_HARD) || errno != EXDEV)
    469 				err(1, "link %s -> %s", from_name, to_name);
    470 		} else {
    471 			if (stat(to_name, &to_sb))
    472 				err(1, "%s: stat", to_name);
    473 			if (S_ISREG(to_sb.st_mode)) {
    474 					/* XXX: only metalog hardlinked files */
    475 				int omode;
    476 				char *oowner, *ogroup, *offlags;
    477 				char *dres;
    478 
    479 					/* XXX: use underlying perms */
    480 				omode = mode;
    481 				mode = (to_sb.st_mode & 0777);
    482 				oowner = owner;
    483 				owner = NULL;
    484 				ogroup = group;
    485 				group = NULL;
    486 				offlags = fflags;
    487 				fflags = NULL;
    488 				switch (digesttype) {
    489 				case DIGEST_MD5:
    490 					dres = MD5File(from_name, NULL);
    491 					break;
    492 				case DIGEST_RMD160:
    493 					dres = RMD160File(from_name, NULL);
    494 					break;
    495 				case DIGEST_SHA1:
    496 					dres = SHA1File(from_name, NULL);
    497 					break;
    498 				default:
    499 					dres = NULL;
    500 				}
    501 				metadata_log(to_name, "file", NULL, NULL, dres);
    502 				free(dres);
    503 				mode = omode;
    504 				owner = oowner;
    505 				group = ogroup;
    506 				fflags = offlags;
    507 			}
    508 			return;
    509 		}
    510 	}
    511 
    512 	/* Symbolic links */
    513 	if (dolink & LN_ABSOLUTE) {
    514 		/* Convert source path to absolute */
    515 		if (realpath(from_name, src) == NULL)
    516 			err(1, "%s: realpath", from_name);
    517 		do_symlink(src, to_name);
    518 			/* XXX: src may point outside of destdir */
    519 		metadata_log(to_name, "link", NULL, src, NULL);
    520 		return;
    521 	}
    522 
    523 	if (dolink & LN_RELATIVE) {
    524 		char *cp, *d, *s;
    525 
    526 		/* Resolve pathnames */
    527 		if (realpath(from_name, src) == NULL)
    528 			err(1, "%s: realpath", from_name);
    529 
    530 		/*
    531 		 * The last component of to_name may be a symlink,
    532 		 * so use realpath to resolve only the directory.
    533 		 */
    534 		cp = xdirname(to_name);
    535 		if (realpath(cp, dst) == NULL)
    536 			err(1, "%s: realpath", cp);
    537 		/* .. and add the last component */
    538 		if (strcmp(dst, "/") != 0) {
    539 			if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
    540 				errx(1, "resolved pathname too long");
    541 		}
    542 		cp = xbasename(to_name);
    543 		if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
    544 			errx(1, "resolved pathname too long");
    545 
    546 		/* trim common path components */
    547 		for (s = src, d = dst; *s == *d; s++, d++)
    548 			continue;
    549 		while (*s != '/')
    550 			s--, d--;
    551 
    552 		/* count the number of directories we need to backtrack */
    553 		for (++d, lnk[0] = '\0'; *d; d++)
    554 			if (*d == '/')
    555 				(void)strlcat(lnk, "../", sizeof(lnk));
    556 
    557 		(void)strlcat(lnk, ++s, sizeof(lnk));
    558 
    559 		do_symlink(lnk, to_name);
    560 			/* XXX: lnk may point outside of destdir */
    561 		metadata_log(to_name, "link", NULL, lnk, NULL);
    562 		return;
    563 	}
    564 
    565 	/*
    566 	 * If absolute or relative was not specified,
    567 	 * try the names the user provided
    568 	 */
    569 	do_symlink(from_name, to_name);
    570 		/* XXX: from_name may point outside of destdir */
    571 	metadata_log(to_name, "link", NULL, from_name, NULL);
    572 }
    573 
    574 /*
    575  * install --
    576  *	build a path name and install the file
    577  */
    578 void
    579 install(char *from_name, char *to_name, u_int flags)
    580 {
    581 	struct stat	from_sb;
    582 #if ! HAVE_NBTOOL_CONFIG_H
    583 	struct stat	to_sb;
    584 #endif
    585 	struct timeval	tv[2];
    586 	int		devnull, from_fd, to_fd, serrno, tmpmode;
    587 	char		*p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
    588 
    589 	if (!dolink) {
    590 			/* ensure that from_sb & tv are sane if !dolink */
    591 		if (stat(from_name, &from_sb))
    592 			err(1, "%s: stat", from_name);
    593 #if BSD4_4 && !HAVE_NBTOOL_CONFIG_H
    594 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    595 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    596 #else
    597 		tv[0].tv_sec = from_sb.st_atime;
    598 		tv[0].tv_usec = 0;
    599 		tv[1].tv_sec = from_sb.st_mtime;
    600 		tv[1].tv_usec = 0;
    601 #endif
    602 	}
    603 
    604 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    605 		if (!dolink) {
    606 			if (!S_ISREG(from_sb.st_mode))
    607 				errx(1, "%s: not a regular file", from_name);
    608 		}
    609 		/* Build the target path. */
    610 		if (flags & DIRECTORY) {
    611 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    612 			    to_name,
    613 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    614 			to_name = pathbuf;
    615 		}
    616 		devnull = 0;
    617 	} else {
    618 #if HAVE_STRUCT_STAT_ST_FLAGS
    619 		from_sb.st_flags = 0;	/* XXX */
    620 #endif
    621 		devnull = 1;
    622 	}
    623 
    624 	/*
    625 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    626 	 * off the append/immutable bits -- if we fail, go ahead,
    627 	 * it might work.
    628 	 */
    629 #if ! HAVE_NBTOOL_CONFIG_H
    630 	if (stat(to_name, &to_sb) == 0 &&
    631 	    to_sb.st_flags & (NOCHANGEBITS))
    632 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    633 #endif
    634 	if (dorename) {
    635 		(void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
    636 		    xdirname(to_name));
    637 		oto_name = to_name;
    638 		to_name = tmpl;
    639 	} else {
    640 		oto_name = NULL;	/* pacify gcc */
    641 		if (dobackup)
    642 			backup(to_name);
    643 		else
    644 			(void)unlink(to_name);
    645 	}
    646 
    647 	if (dolink) {
    648 		makelink(from_name, dorename ? oto_name : to_name);
    649 		return;
    650 	}
    651 
    652 	/* Create target. */
    653 	if (dorename) {
    654 		if ((to_fd = mkstemp(to_name)) == -1)
    655 			err(1, "%s: mkstemp", to_name);
    656 	} else {
    657 		if ((to_fd = open(to_name,
    658 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    659 			err(1, "%s: open", to_name);
    660 	}
    661 	digestresult = NULL;
    662 	if (!devnull) {
    663 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    664 			(void)unlink(to_name);
    665 			err(1, "%s: open", from_name);
    666 		}
    667 		digestresult =
    668 		    copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    669 		(void)close(from_fd);
    670 	}
    671 
    672 	if (dostrip) {
    673 		strip(to_name);
    674 
    675 		/*
    676 		 * Re-open our fd on the target, in case we used a strip
    677 		 *  that does not work in-place -- like gnu binutils strip.
    678 		 */
    679 		close(to_fd);
    680 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    681 			err(1, "stripping %s", to_name);
    682 	}
    683 
    684 	if (afterinstallcmd != NULL) {
    685 		afterinstall(afterinstallcmd, to_name, 1);
    686 
    687 		/*
    688 		 * Re-open our fd on the target, in case we used an
    689 		 * after-install command that does not work in-place
    690 		 */
    691 		close(to_fd);
    692 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    693 			err(1, "running after install command on %s", to_name);
    694 	}
    695 
    696 	/*
    697 	 * Set owner, group, mode for target; do the chown first,
    698 	 * chown may lose the setuid bits.
    699 	 */
    700 	if (!dounpriv &&
    701 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    702 		serrno = errno;
    703 		(void)unlink(to_name);
    704 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    705 	}
    706 	tmpmode = mode;
    707 	if (dounpriv)
    708 		tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
    709 	if (fchmod(to_fd, tmpmode) == -1) {
    710 		serrno = errno;
    711 		(void)unlink(to_name);
    712 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    713 	}
    714 
    715 	/*
    716 	 * Preserve the date of the source file.
    717 	 */
    718 	if (dopreserve) {
    719 #if HAVE_FUTIMES
    720 		if (futimes(to_fd, tv) == -1)
    721 			warn("%s: futimes", to_name);
    722 #else
    723 		if (utimes(to_name, tv) == -1)
    724 			warn("%s: utimes", to_name);
    725 #endif
    726 	}
    727 
    728 	(void)close(to_fd);
    729 
    730 	if (dorename) {
    731 		if (rename(to_name, oto_name) == -1)
    732 			err(1, "%s: rename", to_name);
    733 		to_name = oto_name;
    734 	}
    735 
    736 	/*
    737 	 * If provided a set of flags, set them, otherwise, preserve the
    738 	 * flags, except for the dump flag.
    739 	 */
    740 #if ! HAVE_NBTOOL_CONFIG_H
    741 	if (!dounpriv && chflags(to_name,
    742 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    743 	{
    744 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    745 			warn("%s: chflags", to_name);
    746 	}
    747 #endif
    748 
    749 	metadata_log(to_name, "file", tv, NULL, digestresult);
    750 	free(digestresult);
    751 }
    752 
    753 /*
    754  * copy --
    755  *	copy from one file to another
    756  */
    757 char *
    758 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    759 {
    760 	ssize_t	nr, nw;
    761 	int	serrno;
    762 	u_char	*p;
    763 	u_char	buf[MAXBSIZE];
    764 	MD5_CTX		ctxMD5;
    765 	RMD160_CTX	ctxRMD160;
    766 	SHA1_CTX	ctxSHA1;
    767 
    768 	switch (digesttype) {
    769 	case DIGEST_MD5:
    770 		MD5Init(&ctxMD5);
    771 		break;
    772 	case DIGEST_RMD160:
    773 		RMD160Init(&ctxRMD160);
    774 		break;
    775 	case DIGEST_SHA1:
    776 		SHA1Init(&ctxSHA1);
    777 		break;
    778 	case DIGEST_NONE:
    779 	default:
    780 		break;
    781 	}
    782 	/*
    783 	 * There's no reason to do anything other than close the file
    784 	 * now if it's empty, so let's not bother.
    785 	 */
    786 	if (size > 0) {
    787 
    788 		/*
    789 		 * Mmap and write if less than 8M (the limit is so we
    790 		 * don't totally trash memory on big files).  This is
    791 		 * really a minor hack, but it wins some CPU back.
    792 		 */
    793 
    794 		if (size <= 8 * 1048576) {
    795 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    796 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    797 			    == MAP_FAILED) {
    798 				goto mmap_failed;
    799 			}
    800 #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
    801 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    802 			    && errno != EOPNOTSUPP)
    803 				warnx("madvise: %s", strerror(errno));
    804 #endif
    805 
    806 			if (write(to_fd, p, size) != size) {
    807 				serrno = errno;
    808 				(void)unlink(to_name);
    809 				errx(1, "%s: write: %s",
    810 				    to_name, strerror(serrno));
    811 			}
    812 			switch (digesttype) {
    813 			case DIGEST_MD5:
    814 				MD5Update(&ctxMD5, p, size);
    815 				break;
    816 			case DIGEST_RMD160:
    817 				RMD160Update(&ctxRMD160, p, size);
    818 				break;
    819 			case DIGEST_SHA1:
    820 				SHA1Update(&ctxSHA1, p, size);
    821 				break;
    822 			default:
    823 				break;
    824 			}
    825 			(void)munmap(p, size);
    826 		} else {
    827  mmap_failed:
    828 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    829 				if ((nw = write(to_fd, buf, nr)) != nr) {
    830 					serrno = errno;
    831 					(void)unlink(to_name);
    832 					errx(1, "%s: write: %s", to_name,
    833 					    strerror(nw > 0 ? EIO : serrno));
    834 				}
    835 				switch (digesttype) {
    836 				case DIGEST_MD5:
    837 					MD5Update(&ctxMD5, buf, nr);
    838 					break;
    839 				case DIGEST_RMD160:
    840 					RMD160Update(&ctxRMD160, buf, nr);
    841 					break;
    842 				case DIGEST_SHA1:
    843 					SHA1Update(&ctxSHA1, buf, nr);
    844 					break;
    845 				default:
    846 					break;
    847 				}
    848 			}
    849 			if (nr != 0) {
    850 				serrno = errno;
    851 				(void)unlink(to_name);
    852 				errx(1, "%s: read: %s", from_name, strerror(serrno));
    853 			}
    854 		}
    855 	}
    856 	switch (digesttype) {
    857 	case DIGEST_MD5:
    858 		return MD5End(&ctxMD5, NULL);
    859 	case DIGEST_RMD160:
    860 		return RMD160End(&ctxRMD160, NULL);
    861 	case DIGEST_SHA1:
    862 		return SHA1End(&ctxSHA1, NULL);
    863 	default:
    864 		return NULL;
    865 	}
    866 }
    867 
    868 /*
    869  * strip --
    870  *	use strip(1) to strip the target file
    871  */
    872 void
    873 strip(char *to_name)
    874 {
    875 	static const char exec_failure[] = ": exec of strip failed: ";
    876 	int	serrno, status;
    877 	const char *stripprog, *progname;
    878 	char *cmd;
    879 
    880 	if ((stripprog = getenv("STRIP")) == NULL) {
    881 #ifdef TARGET_STRIP
    882 		stripprog = TARGET_STRIP;
    883 #else
    884 		stripprog = _PATH_STRIP;
    885 #endif
    886 	}
    887 
    888 	cmd = NULL;
    889 
    890 	if (stripArgs) {
    891 		/*
    892 		 * Build up a command line and let /bin/sh
    893 		 * parse the arguments.
    894 		 */
    895 		int ret = asprintf(&cmd, "%s %s %s", stripprog, stripArgs,
    896 		    to_name);
    897 
    898 		if (ret == -1 || cmd == NULL)
    899 			err(1, "asprintf failed");
    900 	}
    901 
    902 	switch (vfork()) {
    903 	case -1:
    904 		serrno = errno;
    905 		(void)unlink(to_name);
    906 		errx(1, "vfork: %s", strerror(serrno));
    907 		/*NOTREACHED*/
    908 	case 0:
    909 
    910 		if (stripArgs)
    911 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    912 		else
    913 			execlp(stripprog, "strip", to_name, NULL);
    914 
    915 		progname = getprogname();
    916 		write(STDERR_FILENO, progname, strlen(progname));
    917 		write(STDERR_FILENO, exec_failure, strlen(exec_failure));
    918 		write(STDERR_FILENO, stripprog, strlen(stripprog));
    919 		write(STDERR_FILENO, "\n", 1);
    920 		_exit(1);
    921 		/*NOTREACHED*/
    922 	default:
    923 		if (wait(&status) == -1 || status)
    924 			(void)unlink(to_name);
    925 	}
    926 
    927 	free(cmd);
    928 }
    929 
    930 /*
    931  * afterinstall --
    932  *	run provided command on the target file or directory after it's been
    933  *	installed and stripped, but before permissions are set or it's renamed
    934  */
    935 void
    936 afterinstall(const char *command, const char *to_name, int errunlink)
    937 {
    938 	int	serrno, status;
    939 	char	*cmd;
    940 
    941 	switch (vfork()) {
    942 	case -1:
    943 		serrno = errno;
    944 		if (errunlink)
    945 			(void)unlink(to_name);
    946 		errx(1, "vfork: %s", strerror(serrno));
    947 		/*NOTREACHED*/
    948 	case 0:
    949 		/*
    950 		 * build up a command line and let /bin/sh
    951 		 * parse the arguments
    952 		 */
    953 		cmd = (char*)malloc(sizeof(char)*
    954 					  (2+strlen(command)+
    955 					     strlen(to_name)));
    956 
    957 		if (cmd == NULL)
    958 			errx(1, "%s", strerror(ENOMEM));
    959 
    960 		sprintf(cmd, "%s %s", command, to_name);
    961 
    962 		execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    963 
    964 		warn("%s: exec of after install command", command);
    965 		_exit(1);
    966 		/*NOTREACHED*/
    967 	default:
    968 		if ((wait(&status) == -1 || status) && errunlink)
    969 			(void)unlink(to_name);
    970 	}
    971 }
    972 
    973 /*
    974  * backup --
    975  *	backup file "to_name" to to_name.suffix
    976  *	if suffix contains a "%", it's taken as a printf(3) pattern
    977  *	used for a numbered backup.
    978  */
    979 void
    980 backup(const char *to_name)
    981 {
    982 	char	bname[FILENAME_MAX];
    983 
    984 	if (numberedbackup) {
    985 		/* Do numbered backup */
    986 		int cnt;
    987 		char suffix_expanded[FILENAME_MAX];
    988 
    989 		cnt=0;
    990 		do {
    991 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    992 			    cnt);
    993 			(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
    994 			    suffix_expanded);
    995 			cnt++;
    996 		} while (access(bname, F_OK) == 0);
    997 	} else {
    998 		/* Do simple backup */
    999 		(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
   1000 	}
   1001 
   1002 	(void)rename(to_name, bname);
   1003 }
   1004 
   1005 /*
   1006  * install_dir --
   1007  *	build directory hierarchy
   1008  */
   1009 void
   1010 install_dir(char *path, u_int flags)
   1011 {
   1012         char		*p;
   1013         struct stat	sb;
   1014         int		ch;
   1015 
   1016         for (p = path;; ++p)
   1017                 if (!*p || (p != path && *p  == '/')) {
   1018                         ch = *p;
   1019                         *p = '\0';
   1020                         if (stat(path, &sb)) {
   1021                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
   1022 					err(1, "%s: mkdir", path);
   1023                                 }
   1024                         }
   1025 			else if (!S_ISDIR(sb.st_mode)) {
   1026 				errx(1, "%s exists but is not a directory", path);
   1027 			}
   1028                         if (!(*p = ch))
   1029 				break;
   1030                 }
   1031 
   1032 	if (afterinstallcmd != NULL)
   1033 		afterinstall(afterinstallcmd, path, 0);
   1034 
   1035 	if (!dounpriv && (
   1036 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
   1037 	    || chmod(path, mode) == -1 )) {
   1038                 warn("%s: chown/chmod", path);
   1039 	}
   1040 	metadata_log(path, "dir", NULL, NULL, NULL);
   1041 }
   1042 
   1043 /*
   1044  * metadata_log --
   1045  *	if metafp is not NULL, output mtree(8) full path name and settings to
   1046  *	metafp, to allow permissions to be set correctly by other tools.
   1047  */
   1048 void
   1049 metadata_log(const char *path, const char *type, struct timeval *tv,
   1050 	const char *link, const char *digestresult)
   1051 {
   1052 	static const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
   1053 	const char	*p;
   1054 	char		*buf;
   1055 	size_t		destlen;
   1056 	struct flock	metalog_lock;
   1057 
   1058 	if (!metafp)
   1059 		return;
   1060 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
   1061 	if (buf == NULL) {
   1062 		warnx("%s", strerror(ENOMEM));
   1063 		return;
   1064 	}
   1065 							/* lock log file */
   1066 	metalog_lock.l_start = 0;
   1067 	metalog_lock.l_len = 0;
   1068 	metalog_lock.l_whence = SEEK_SET;
   1069 	metalog_lock.l_type = F_WRLCK;
   1070 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1071 		warn("can't lock %s", metafile);
   1072 		free(buf);
   1073 		return;
   1074 	}
   1075 
   1076 	p = path;					/* remove destdir */
   1077 	if (destdir) {
   1078 		destlen = strlen(destdir);
   1079 		if (strncmp(p, destdir, destlen) == 0 &&
   1080 		    (p[destlen] == '/' || p[destlen] == '\0'))
   1081 			p += destlen;
   1082 	}
   1083 	while (*p && *p == '/')				/* remove leading /s */
   1084 		p++;
   1085 	strsvis(buf, p, VIS_CSTYLE, extra);		/* encode name */
   1086 	p = buf;
   1087 							/* print details */
   1088 	fprintf(metafp, ".%s%s type=%s mode=%#o", *p ? "/" : "", p, type, mode);
   1089 	if (link) {
   1090 		strsvis(buf, link, VIS_CSTYLE, extra);	/* encode link */
   1091 		fprintf(metafp, " link=%s", buf);
   1092 	}
   1093 	if (owner)
   1094 		fprintf(metafp, " uname=%s", owner);
   1095 	if (group)
   1096 		fprintf(metafp, " gname=%s", group);
   1097 	if (fflags)
   1098 		fprintf(metafp, " flags=%s", fflags);
   1099 	if (tags)
   1100 		fprintf(metafp, " tags=%s", tags);
   1101 	if (tv != NULL && dopreserve)
   1102 		fprintf(metafp, " time=%lld.%ld",
   1103 			(long long)tv[1].tv_sec, (long)tv[1].tv_usec);
   1104 	if (digestresult && digest)
   1105 		fprintf(metafp, " %s=%s", digest, digestresult);
   1106 	fputc('\n', metafp);
   1107 	fflush(metafp);					/* flush output */
   1108 							/* unlock log file */
   1109 	metalog_lock.l_type = F_UNLCK;
   1110 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1111 		warn("can't unlock %s", metafile);
   1112 	}
   1113 	free(buf);
   1114 }
   1115 
   1116 /*
   1117  * xbasename --
   1118  *	libc basename(3) that returns a pointer to a static buffer
   1119  *	instead of overwriting that passed-in string.
   1120  */
   1121 char *
   1122 xbasename(char *path)
   1123 {
   1124 	static char tmp[MAXPATHLEN];
   1125 
   1126 	(void)strlcpy(tmp, path, sizeof(tmp));
   1127 	return (basename(tmp));
   1128 }
   1129 
   1130 /*
   1131  * xdirname --
   1132  *	libc dirname(3) that returns a pointer to a static buffer
   1133  *	instead of overwriting that passed-in string.
   1134  */
   1135 char *
   1136 xdirname(char *path)
   1137 {
   1138 	static char tmp[MAXPATHLEN];
   1139 
   1140 	(void)strlcpy(tmp, path, sizeof(tmp));
   1141 	return (dirname(tmp));
   1142 }
   1143 
   1144 /*
   1145  * usage --
   1146  *	print a usage message and die
   1147  */
   1148 void
   1149 usage(void)
   1150 {
   1151 	const char *prog;
   1152 
   1153 	prog = getprogname();
   1154 
   1155 	(void)fprintf(stderr,
   1156 "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1157 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
   1158 "           [-l linkflags] [-h hash] [-S stripflags] file1 file2\n"
   1159 "       %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1160 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
   1161 "           [-l linkflags] [-h hash] [-S stripflags] file1 ... fileN directory\n"
   1162 "       %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
   1163 "           [-N dbdir] [-o owner] [-g group] directory ...\n",
   1164 	    prog, prog, prog);
   1165 	exit(1);
   1166 }
   1167