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