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