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