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