Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.84
      1 /*	$NetBSD: xinstall.c,v 1.84 2004/01/29 07:58:33 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.84 2004/01/29 07:58:33 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 
    469 					/* XXX: use underlying perms */
    470 				omode = mode;
    471 				mode = (to_sb.st_mode & 0777);
    472 				oowner = owner;
    473 				owner = NULL;
    474 				ogroup = group;
    475 				group = NULL;
    476 				offlags = fflags;
    477 				fflags = NULL;
    478 				metadata_log(to_name, "file", NULL, NULL, NULL);
    479 				mode = omode;
    480 				owner = oowner;
    481 				group = ogroup;
    482 				fflags = offlags;
    483 			}
    484 			return;
    485 		}
    486 	}
    487 
    488 	/* Symbolic links */
    489 	if (dolink & LN_ABSOLUTE) {
    490 		/* Convert source path to absolute */
    491 		if (realpath(from_name, src) == NULL)
    492 			err(1, "%s: realpath", from_name);
    493 		do_symlink(src, to_name);
    494 		metadata_log(to_name, "link", NULL, src, NULL);
    495 		return;
    496 	}
    497 
    498 	if (dolink & LN_RELATIVE) {
    499 		char *cp, *d, *s;
    500 
    501 		/* Resolve pathnames */
    502 		if (realpath(from_name, src) == NULL)
    503 			err(1, "%s: realpath", from_name);
    504 
    505 		/*
    506 		 * The last component of to_name may be a symlink,
    507 		 * so use realpath to resolve only the directory.
    508 		 */
    509 		cp = xdirname(to_name);
    510 		if (realpath(cp, dst) == NULL)
    511 			err(1, "%s: realpath", cp);
    512 		/* .. and add the last component */
    513 		if (strcmp(dst, "/") != 0) {
    514 			if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
    515 				errx(1, "resolved pathname too long");
    516 		}
    517 		cp = xbasename(to_name);
    518 		if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
    519 			errx(1, "resolved pathname too long");
    520 
    521 		/* trim common path components */
    522 		for (s = src, d = dst; *s == *d; s++, d++)
    523 			continue;
    524 		while (*s != '/')
    525 			s--, d--;
    526 
    527 		/* count the number of directories we need to backtrack */
    528 		for (++d, lnk[0] = '\0'; *d; d++)
    529 			if (*d == '/')
    530 				(void)strlcat(lnk, "../", sizeof(lnk));
    531 
    532 		(void)strlcat(lnk, ++s, sizeof(lnk));
    533 
    534 		do_symlink(lnk, dst);
    535 		metadata_log(dst, "link", NULL, lnk, NULL);
    536 		return;
    537 	}
    538 
    539 	/*
    540 	 * If absolute or relative was not specified,
    541 	 * try the names the user provided
    542 	 */
    543 	do_symlink(from_name, to_name);
    544 	metadata_log(to_name, "link", NULL, from_name, NULL);
    545 }
    546 
    547 /*
    548  * install --
    549  *	build a path name and install the file
    550  */
    551 void
    552 install(char *from_name, char *to_name, u_int flags)
    553 {
    554 	struct stat	from_sb;
    555 #if ! HAVE_NBTOOL_CONFIG_H
    556 	struct stat	to_sb;
    557 #endif
    558 	struct timeval	tv[2];
    559 	int		devnull, from_fd, to_fd, serrno, tmpmode;
    560 	char		*p, tmpl[MAXPATHLEN], *oto_name, *digestresult;
    561 
    562 	if (!dolink) {
    563 			/* ensure that from_sb & tv are sane if !dolink */
    564 		if (stat(from_name, &from_sb))
    565 			err(1, "%s: stat", from_name);
    566 #ifdef BSD4_4
    567 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    568 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    569 #else
    570 		tv[0].tv_sec = from_sb.st_atime;
    571 		tv[0].tv_usec = 0;
    572 		tv[1].tv_sec = from_sb.st_mtime;
    573 		tv[1].tv_usec = 0;
    574 #endif
    575 	}
    576 
    577 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    578 		if (!dolink) {
    579 			if (!S_ISREG(from_sb.st_mode))
    580 				errx(1, "%s: not a regular file", from_name);
    581 		}
    582 		/* Build the target path. */
    583 		if (flags & DIRECTORY) {
    584 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    585 			    to_name,
    586 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    587 			to_name = pathbuf;
    588 		}
    589 		devnull = 0;
    590 	} else {
    591 #if HAVE_STRUCT_STAT_ST_FLAGS
    592 		from_sb.st_flags = 0;	/* XXX */
    593 #endif
    594 		devnull = 1;
    595 	}
    596 
    597 	/*
    598 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    599 	 * off the append/immutable bits -- if we fail, go ahead,
    600 	 * it might work.
    601 	 */
    602 #if ! HAVE_NBTOOL_CONFIG_H
    603 	if (stat(to_name, &to_sb) == 0 &&
    604 	    to_sb.st_flags & (NOCHANGEBITS))
    605 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    606 #endif
    607 	if (dorename) {
    608 		(void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
    609 		    xdirname(to_name));
    610 		oto_name = to_name;
    611 		to_name = tmpl;
    612 	} else {
    613 		oto_name = NULL;	/* pacify gcc */
    614 		if (dobackup)
    615 			backup(to_name);
    616 		else
    617 			(void)unlink(to_name);
    618 	}
    619 
    620 	if (dolink) {
    621 		makelink(from_name, dorename ? oto_name : to_name);
    622 		return;
    623 	}
    624 
    625 	/* Create target. */
    626 	if (dorename) {
    627 		if ((to_fd = mkstemp(to_name)) == -1)
    628 			err(1, "%s: mkstemp", to_name);
    629 	} else {
    630 		if ((to_fd = open(to_name,
    631 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    632 			err(1, "%s: open", to_name);
    633 	}
    634 	if (!devnull) {
    635 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    636 			(void)unlink(to_name);
    637 			err(1, "%s: open", from_name);
    638 		}
    639 		digestresult =
    640 		    copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    641 		(void)close(from_fd);
    642 	}
    643 
    644 	if (dostrip) {
    645 		strip(to_name);
    646 
    647 		/*
    648 		 * Re-open our fd on the target, in case we used a strip
    649 		 *  that does not work in-place -- like gnu binutils strip.
    650 		 */
    651 		close(to_fd);
    652 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    653 			err(1, "stripping %s", to_name);
    654 	}
    655 
    656 	if (afterinstallcmd != NULL) {
    657 		afterinstall(afterinstallcmd, to_name, 1);
    658 
    659 		/*
    660 		 * Re-open our fd on the target, in case we used an
    661 		 * after-install command that does not work in-place
    662 		 */
    663 		close(to_fd);
    664 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    665 			err(1, "running after install command on %s", to_name);
    666 	}
    667 
    668 	/*
    669 	 * Set owner, group, mode for target; do the chown first,
    670 	 * chown may lose the setuid bits.
    671 	 */
    672 	if (!dounpriv &&
    673 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    674 		serrno = errno;
    675 		(void)unlink(to_name);
    676 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    677 	}
    678 	tmpmode = mode;
    679 	if (dounpriv)
    680 		tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
    681 	if (fchmod(to_fd, tmpmode) == -1) {
    682 		serrno = errno;
    683 		(void)unlink(to_name);
    684 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    685 	}
    686 
    687 	/*
    688 	 * Preserve the date of the source file.
    689 	 */
    690 	if (dopreserve) {
    691 #if HAVE_FUTIMES
    692 		if (futimes(to_fd, tv) == -1)
    693 			warn("%s: futimes", to_name);
    694 #else
    695 		if (utimes(to_name, tv) == -1)
    696 			warn("%s: utimes", to_name);
    697 #endif
    698 	}
    699 
    700 	(void)close(to_fd);
    701 
    702 	if (dorename) {
    703 		if (rename(to_name, oto_name) == -1)
    704 			err(1, "%s: rename", to_name);
    705 		to_name = oto_name;
    706 	}
    707 
    708 	/*
    709 	 * If provided a set of flags, set them, otherwise, preserve the
    710 	 * flags, except for the dump flag.
    711 	 */
    712 #if ! HAVE_NBTOOL_CONFIG_H
    713 	if (!dounpriv && chflags(to_name,
    714 	    flags & SETFLAGS ? fileflags : from_sb.st_flags & ~UF_NODUMP) == -1)
    715 	{
    716 		if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
    717 			warn("%s: chflags", to_name);
    718 	}
    719 #endif
    720 
    721 	metadata_log(to_name, "file", tv, NULL, digestresult);
    722 	free(digestresult);
    723 }
    724 
    725 /*
    726  * copy --
    727  *	copy from one file to another
    728  */
    729 char *
    730 copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size)
    731 {
    732 	ssize_t	nr, nw;
    733 	int	serrno;
    734 	char	*p;
    735 	char	buf[MAXBSIZE];
    736 	MD5_CTX		ctxMD5;
    737 	RMD160_CTX	ctxRMD160;
    738 	SHA1_CTX	ctxSHA1;
    739 
    740 	switch (digesttype) {
    741 	case DIGEST_MD5:
    742 		MD5Init(&ctxMD5);
    743 		break;
    744 	case DIGEST_RMD160:
    745 		RMD160Init(&ctxRMD160);
    746 		break;
    747 	case DIGEST_SHA1:
    748 		SHA1Init(&ctxSHA1);
    749 		break;
    750 	case DIGEST_NONE:
    751 	default:
    752 		break;
    753 	}
    754 	/*
    755 	 * There's no reason to do anything other than close the file
    756 	 * now if it's empty, so let's not bother.
    757 	 */
    758 	if (size > 0) {
    759 
    760 		/*
    761 		 * Mmap and write if less than 8M (the limit is so we
    762 		 * don't totally trash memory on big files).  This is
    763 		 * really a minor hack, but it wins some CPU back.
    764 		 */
    765 
    766 		if (size <= 8 * 1048576) {
    767 			if ((p = mmap(NULL, (size_t)size, PROT_READ,
    768 			    MAP_FILE|MAP_SHARED, from_fd, (off_t)0))
    769 			    == MAP_FAILED) {
    770 				goto mmap_failed;
    771 			}
    772 #if defined(MADV_SEQUENTIAL) && !defined(__APPLE__)
    773 			if (madvise(p, (size_t)size, MADV_SEQUENTIAL) == -1
    774 			    && errno != EOPNOTSUPP)
    775 				warnx("madvise: %s", strerror(errno));
    776 #endif
    777 
    778 			if (write(to_fd, p, size) != size) {
    779 				serrno = errno;
    780 				(void)unlink(to_name);
    781 				errx(1, "%s: write: %s",
    782 				    to_name, strerror(serrno));
    783 			}
    784 			switch (digesttype) {
    785 			case DIGEST_MD5:
    786 				MD5Update(&ctxMD5, p, size);
    787 				break;
    788 			case DIGEST_RMD160:
    789 				RMD160Update(&ctxRMD160, p, size);
    790 				break;
    791 			case DIGEST_SHA1:
    792 				SHA1Update(&ctxSHA1, p, size);
    793 				break;
    794 			default:
    795 				break;
    796 			}
    797 			(void)munmap(p, size);
    798 		} else {
    799  mmap_failed:
    800 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    801 				if ((nw = write(to_fd, buf, nr)) != nr) {
    802 					serrno = errno;
    803 					(void)unlink(to_name);
    804 					errx(1, "%s: write: %s", to_name,
    805 					    strerror(nw > 0 ? EIO : serrno));
    806 				}
    807 				switch (digesttype) {
    808 				case DIGEST_MD5:
    809 					MD5Update(&ctxMD5, buf, nr);
    810 					break;
    811 				case DIGEST_RMD160:
    812 					RMD160Update(&ctxRMD160, buf, nr);
    813 					break;
    814 				case DIGEST_SHA1:
    815 					SHA1Update(&ctxSHA1, buf, nr);
    816 					break;
    817 				default:
    818 					break;
    819 				}
    820 			}
    821 			if (nr != 0) {
    822 				serrno = errno;
    823 				(void)unlink(to_name);
    824 				errx(1, "%s: read: %s", from_name, strerror(serrno));
    825 			}
    826 		}
    827 	}
    828 	switch (digesttype) {
    829 	case DIGEST_MD5:
    830 		return MD5End(&ctxMD5, NULL);
    831 	case DIGEST_RMD160:
    832 		return RMD160End(&ctxRMD160, NULL);
    833 	case DIGEST_SHA1:
    834 		return SHA1End(&ctxSHA1, NULL);
    835 	default:
    836 		return NULL;
    837 	}
    838 }
    839 
    840 /*
    841  * strip --
    842  *	use strip(1) to strip the target file
    843  */
    844 void
    845 strip(char *to_name)
    846 {
    847 	int	serrno, status;
    848 	char	*stripprog;
    849 
    850 	switch (vfork()) {
    851 	case -1:
    852 		serrno = errno;
    853 		(void)unlink(to_name);
    854 		errx(1, "vfork: %s", strerror(serrno));
    855 		/*NOTREACHED*/
    856 	case 0:
    857 		stripprog = getenv("STRIP");
    858 		if (stripprog == NULL)
    859 			stripprog = _PATH_STRIP;
    860 
    861 		if (stripArgs) {
    862 			/*
    863 			 * build up a command line and let /bin/sh
    864 			 * parse the arguments
    865 			 */
    866 			char* cmd = (char*)malloc(sizeof(char)*
    867 						  (3+strlen(stripprog)+
    868 						     strlen(stripArgs)+
    869 						     strlen(to_name)));
    870 
    871 			if (cmd == NULL)
    872 				errx(1, "%s", strerror(ENOMEM));
    873 
    874 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    875 
    876 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    877 		} else
    878 			execlp(stripprog, "strip", to_name, NULL);
    879 
    880 		warn("%s: exec of strip", stripprog);
    881 		_exit(1);
    882 		/*NOTREACHED*/
    883 	default:
    884 		if (wait(&status) == -1 || status)
    885 			(void)unlink(to_name);
    886 	}
    887 }
    888 
    889 /*
    890  * afterinstall --
    891  *	run provided command on the target file or directory after it's been
    892  *	installed and stripped, but before permissions are set or it's renamed
    893  */
    894 void
    895 afterinstall(const char *command, const char *to_name, int errunlink)
    896 {
    897 	int	serrno, status;
    898 	char	*cmd;
    899 
    900 	switch (vfork()) {
    901 	case -1:
    902 		serrno = errno;
    903 		if (errunlink)
    904 			(void)unlink(to_name);
    905 		errx(1, "vfork: %s", strerror(serrno));
    906 		/*NOTREACHED*/
    907 	case 0:
    908 		/*
    909 		 * build up a command line and let /bin/sh
    910 		 * parse the arguments
    911 		 */
    912 		cmd = (char*)malloc(sizeof(char)*
    913 					  (2+strlen(command)+
    914 					     strlen(to_name)));
    915 
    916 		if (cmd == NULL)
    917 			errx(1, "%s", strerror(ENOMEM));
    918 
    919 		sprintf(cmd, "%s %s", command, to_name);
    920 
    921 		execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    922 
    923 		warn("%s: exec of after install command", command);
    924 		_exit(1);
    925 		/*NOTREACHED*/
    926 	default:
    927 		if ((wait(&status) == -1 || status) && errunlink)
    928 			(void)unlink(to_name);
    929 	}
    930 }
    931 
    932 /*
    933  * backup --
    934  *	backup file "to_name" to to_name.suffix
    935  *	if suffix contains a "%", it's taken as a printf(3) pattern
    936  *	used for a numbered backup.
    937  */
    938 void
    939 backup(const char *to_name)
    940 {
    941 	char	bname[FILENAME_MAX];
    942 
    943 	if (numberedbackup) {
    944 		/* Do numbered backup */
    945 		int cnt;
    946 		char suffix_expanded[FILENAME_MAX];
    947 
    948 		cnt=0;
    949 		do {
    950 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    951 			    cnt);
    952 			(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
    953 			    suffix_expanded);
    954 			cnt++;
    955 		} while (access(bname, F_OK) == 0);
    956 	} else {
    957 		/* Do simple backup */
    958 		(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
    959 	}
    960 
    961 	(void)rename(to_name, bname);
    962 }
    963 
    964 /*
    965  * install_dir --
    966  *	build directory hierarchy
    967  */
    968 void
    969 install_dir(char *path, u_int flags)
    970 {
    971         char		*p;
    972         struct stat	sb;
    973         int		ch;
    974 
    975         for (p = path;; ++p)
    976                 if (!*p || (p != path && *p  == '/')) {
    977                         ch = *p;
    978                         *p = '\0';
    979                         if (stat(path, &sb)) {
    980                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    981 					err(1, "%s: mkdir", path);
    982                                 }
    983                         }
    984                         if (!(*p = ch))
    985 				break;
    986                 }
    987 
    988 	if (afterinstallcmd != NULL)
    989 		afterinstall(afterinstallcmd, path, 0);
    990 
    991 	if (!dounpriv && (
    992 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
    993 	    || chmod(path, mode) == -1 )) {
    994                 warn("%s: chown/chmod", path);
    995 	}
    996 	metadata_log(path, "dir", NULL, NULL, NULL);
    997 }
    998 
    999 /*
   1000  * metadata_log --
   1001  *	if metafp is not NULL, output mtree(8) full path name and settings to
   1002  *	metafp, to allow permissions to be set correctly by other tools.
   1003  */
   1004 void
   1005 metadata_log(const char *path, const char *type, struct timeval *tv,
   1006 	const char *link, const char *digestresult)
   1007 {
   1008 	static const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
   1009 	char		*buf, *p;
   1010 	size_t		destlen;
   1011 	struct flock	metalog_lock;
   1012 
   1013 	if (!metafp)
   1014 		return;
   1015 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
   1016 	if (buf == NULL) {
   1017 		warnx("%s", strerror(ENOMEM));
   1018 		return;
   1019 	}
   1020 							/* lock log file */
   1021 	metalog_lock.l_start = 0;
   1022 	metalog_lock.l_len = 0;
   1023 	metalog_lock.l_whence = SEEK_SET;
   1024 	metalog_lock.l_type = F_WRLCK;
   1025 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1026 		warn("can't lock %s", metafile);
   1027 		return;
   1028 	}
   1029 
   1030 	strsvis(buf, path, VIS_CSTYLE, extra);		/* encode name */
   1031 	p = buf;					/* remove destdir */
   1032 	if (destdir) {
   1033 		destlen = strlen(destdir);
   1034 		if (strncmp(p, destdir, destlen) == 0 &&
   1035 		    (p[destlen] == '/' || p[destlen] == '\0'))
   1036 			p += destlen;
   1037 	}
   1038 	while (*p && *p == '/')				/* remove leading /s */
   1039 		p++;
   1040 							/* print details */
   1041 	fprintf(metafp, ".%s%s type=%s mode=%#o", *p ? "/" : "", p, type, mode);
   1042 	if (link)
   1043 		fprintf(metafp, " link=%s", link);
   1044 	if (owner)
   1045 		fprintf(metafp, " uname=%s", owner);
   1046 	if (group)
   1047 		fprintf(metafp, " gname=%s", group);
   1048 	if (fflags)
   1049 		fprintf(metafp, " flags=%s", fflags);
   1050 	if (tags)
   1051 		fprintf(metafp, " tags=%s", tags);
   1052 	if (tv != NULL && dopreserve)
   1053 		fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
   1054 	if (digestresult && digest)
   1055 		fprintf(metafp, " %s=%s", digest, digestresult);
   1056 	fputc('\n', metafp);
   1057 	fflush(metafp);					/* flush output */
   1058 							/* unlock log file */
   1059 	metalog_lock.l_type = F_UNLCK;
   1060 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
   1061 		warn("can't unlock %s", metafile);
   1062 	}
   1063 	free(buf);
   1064 }
   1065 
   1066 /*
   1067  * xbasename --
   1068  *	libc basename(3) that returns a pointer to a static buffer
   1069  *	instead of overwriting that passed-in string.
   1070  */
   1071 char *
   1072 xbasename(char *path)
   1073 {
   1074 	static char tmp[MAXPATHLEN];
   1075 
   1076 	(void)strlcpy(tmp, path, sizeof(tmp));
   1077 	return (basename(tmp));
   1078 }
   1079 
   1080 /*
   1081  * xdirname --
   1082  *	libc dirname(3) that returns a pointer to a static buffer
   1083  *	instead of overwriting that passed-in string.
   1084  */
   1085 char *
   1086 xdirname(char *path)
   1087 {
   1088 	static char tmp[MAXPATHLEN];
   1089 
   1090 	(void)strlcpy(tmp, path, sizeof(tmp));
   1091 	return (dirname(tmp));
   1092 }
   1093 
   1094 /*
   1095  * usage --
   1096  *	print a usage message and die
   1097  */
   1098 void
   1099 usage(void)
   1100 {
   1101 	const char *prog;
   1102 
   1103 	prog = getprogname();
   1104 
   1105 	(void)fprintf(stderr,
   1106 "usage: %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1107 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group] \n"
   1108 "           [-l linkflags] [-h hash] [-S stripflags] file1 file2\n"
   1109 "       %s [-Ubcprs] [-M log] [-D dest] [-T tags] [-B suffix]\n"
   1110 "           [-a aftercmd] [-f flags] [-m mode] [-N dbdir] [-o owner] [-g group]\n"
   1111 "           [-l linkflags] [-h hash] [-S stripflags] file1 ... fileN directory\n"
   1112 "       %s -d [-Up] [-M log] [-D dest] [-T tags] [-a aftercmd] [-m mode]\n"
   1113 "           [-N dbdir] [-o owner] [-g group] directory ...\n",
   1114 	    prog, prog, prog);
   1115 	exit(1);
   1116 }
   1117