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