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