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