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