Home | History | Annotate | Line # | Download | only in xinstall
xinstall.c revision 1.69
      1 /*	$NetBSD: xinstall.c,v 1.69 2002/03/19 14:17:04 lukem 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. All advertising materials mentioning features or use of this software
     16  *    must display the following acknowledgement:
     17  *	This product includes software developed by the University of
     18  *	California, Berkeley and its contributors.
     19  * 4. Neither the name of the University nor the names of its contributors
     20  *    may be used to endorse or promote products derived from this software
     21  *    without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  */
     35 
     36 #if HAVE_CONFIG_H
     37 #include "config.h"
     38 #else
     39 #define HAVE_FUTIMES 1
     40 #define HAVE_STRUCT_STAT_ST_FLAGS 1
     41 #endif
     42 
     43 #include <sys/cdefs.h>
     44 #if defined(__COPYRIGHT) && !defined(lint)
     45 __COPYRIGHT("@(#) Copyright (c) 1987, 1993\n\
     46 	The Regents of the University of California.  All rights reserved.\n");
     47 #endif /* not lint */
     48 
     49 #if defined(__RCSID) && !defined(lint)
     50 #if 0
     51 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
     52 #else
     53 __RCSID("$NetBSD: xinstall.c,v 1.69 2002/03/19 14:17:04 lukem Exp $");
     54 #endif
     55 #endif /* not lint */
     56 
     57 #include <sys/param.h>
     58 #include <sys/mman.h>
     59 #include <sys/stat.h>
     60 #include <sys/wait.h>
     61 
     62 #include <ctype.h>
     63 #include <err.h>
     64 #include <errno.h>
     65 #include <fcntl.h>
     66 #include <grp.h>
     67 #include <libgen.h>
     68 #include <paths.h>
     69 #include <pwd.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.h>
     73 #include <unistd.h>
     74 #include <vis.h>
     75 
     76 #include "pathnames.h"
     77 #include "stat_flags.h"
     78 
     79 #define STRIP_ARGS_MAX 32
     80 #define BACKUP_SUFFIX ".old"
     81 
     82 int	dobackup, docopy, dodir, dostrip, dolink, dopreserve, dorename,
     83 	    dounpriv;
     84 int	numberedbackup;
     85 int	mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
     86 char	pathbuf[MAXPATHLEN];
     87 id_t	uid, gid;
     88 char	*group, *owner, *fflags, *tags;
     89 FILE	*metafp;
     90 char	*metafile;
     91 u_long	fileflags;
     92 char	*stripArgs;
     93 char	*afterinstallcmd;
     94 char	*suffix = BACKUP_SUFFIX;
     95 
     96 #define LN_ABSOLUTE	0x01
     97 #define LN_RELATIVE	0x02
     98 #define LN_HARD		0x04
     99 #define LN_SYMBOLIC	0x08
    100 #define LN_MIXED	0x10
    101 
    102 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
    103 #define	SETFLAGS	0x02		/* Tell install to set flags. */
    104 #define	HASUID		0x04		/* Tell install the uid was given */
    105 #define	HASGID		0x08		/* Tell install the gid was given */
    106 
    107 void	afterinstall(const char *, const char *, int);
    108 void	backup(const char *);
    109 void	copy(int, char *, int, char *, off_t);
    110 int	do_link(char *, char *);
    111 void	do_symlink(char *, char *);
    112 void	install(char *, char *, u_int);
    113 void	install_dir(char *, u_int);
    114 int	main(int, char *[]);
    115 void	makelink(char *, char *);
    116 void	metadata_log(const char *, const char *, struct timeval *, const char *);
    117 int	parseid(char *, id_t *);
    118 void	strip(char *);
    119 void	usage(void);
    120 char   *xbasename(char *);
    121 char   *xdirname(char *);
    122 
    123 int
    124 main(int argc, char *argv[])
    125 {
    126 	struct stat	from_sb, to_sb;
    127 	void		*set;
    128 	u_int		iflags;
    129 	int		ch, no_target;
    130 	char		*p, *to_name;
    131 
    132 	setprogname(argv[0]);
    133 
    134 	iflags = 0;
    135 	while ((ch = getopt(argc, argv, "a:cbB:df:g:l:m:M:o:prsS:T:U")) != -1)
    136 		switch((char)ch) {
    137 		case 'a':
    138 			afterinstallcmd = strdup(optarg);
    139 			if (afterinstallcmd == NULL)
    140 				errx(1, "%s", strerror(ENOMEM));
    141 			break;
    142 		case 'B':
    143 			suffix = optarg;
    144 			numberedbackup = 0;
    145 			{
    146 				/* Check if given suffix really generates
    147 				   different suffixes - catch e.g. ".%" */
    148 				char suffix_expanded0[FILENAME_MAX],
    149 				     suffix_expanded1[FILENAME_MAX];
    150 				(void)snprintf(suffix_expanded0, FILENAME_MAX,
    151 					       suffix, 0);
    152 				(void)snprintf(suffix_expanded1, FILENAME_MAX,
    153 					       suffix, 1);
    154 				if (strcmp(suffix_expanded0, suffix_expanded1)
    155 				    != 0)
    156 					numberedbackup = 1;
    157 			}
    158 			/* fall through; -B implies -b */
    159 			/*FALLTHROUGH*/
    160 		case 'b':
    161 			dobackup = 1;
    162 			break;
    163 		case 'c':
    164 			docopy = 1;
    165 			break;
    166 		case 'd':
    167 			dodir = 1;
    168 			break;
    169 #if !HAVE_CONFIG_H
    170 		case 'f':
    171 			fflags = optarg;
    172 			break;
    173 #endif
    174 		case 'g':
    175 			group = optarg;
    176 			break;
    177 		case 'l':
    178 			for (p = optarg; *p; p++)
    179 				switch (*p) {
    180 				case 's':
    181 					dolink &= ~(LN_HARD|LN_MIXED);
    182 					dolink |= LN_SYMBOLIC;
    183 					break;
    184 				case 'h':
    185 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
    186 					dolink |= LN_HARD;
    187 					break;
    188 				case 'm':
    189 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
    190 					dolink |= LN_MIXED;
    191 					break;
    192 				case 'a':
    193 					dolink &= ~LN_RELATIVE;
    194 					dolink |= LN_ABSOLUTE;
    195 					break;
    196 				case 'r':
    197 					dolink &= ~LN_ABSOLUTE;
    198 					dolink |= LN_RELATIVE;
    199 					break;
    200 				default:
    201 					errx(1, "%c: invalid link type", *p);
    202 					/* NOTREACHED */
    203 				}
    204 			break;
    205 		case 'm':
    206 			if (!(set = setmode(optarg)))
    207 				errx(1, "%s: invalid file mode", optarg);
    208 			mode = getmode(set, 0);
    209 			free(set);
    210 			break;
    211 		case 'M':
    212 			metafile = optarg;
    213 			break;
    214 		case 'o':
    215 			owner = optarg;
    216 			break;
    217 		case 'p':
    218 			dopreserve = 1;
    219 			break;
    220 		case 'r':
    221 			dorename = 1;
    222 			break;
    223 		case 'S':
    224 			stripArgs = strdup(optarg);
    225 			if (stripArgs == NULL)
    226 				errx(1, "%s", strerror(ENOMEM));
    227 			/* fall through; -S implies -s */
    228 			/*FALLTHROUGH*/
    229 		case 's':
    230 			dostrip = 1;
    231 			break;
    232 		case 'T':
    233 			tags = optarg;
    234 			break;
    235 		case 'U':
    236 			dounpriv = 1;
    237 			break;
    238 		case '?':
    239 		default:
    240 			usage();
    241 		}
    242 	argc -= optind;
    243 	argv += optind;
    244 
    245 	/* strip and link options make no sense when creating directories */
    246 	if ((dostrip || dolink) && dodir)
    247 		usage();
    248 
    249 	/* strip and flags make no sense with links */
    250 	if ((dostrip || fflags) && dolink)
    251 		usage();
    252 
    253 	/* must have at least two arguments, except when creating directories */
    254 	if (argc < 2 && !dodir)
    255 		usage();
    256 
    257 	/* get group and owner id's */
    258 	if (group && !dounpriv) {
    259 		struct group *gp;
    260 
    261 		if ((gp = getgrnam(group)) != NULL)
    262 			gid = gp->gr_gid;
    263 		else if (! parseid(group, &gid))
    264 			errx(1, "unknown group %s", group);
    265 		iflags |= HASGID;
    266 	}
    267 	if (owner && !dounpriv) {
    268 		struct passwd *pp;
    269 
    270 		if ((pp = getpwnam(owner)) != NULL)
    271 			uid = pp->pw_uid;
    272 		else if (! parseid(owner, &uid))
    273 			errx(1, "unknown user %s", owner);
    274 		iflags |= HASUID;
    275 	}
    276 
    277 #if !HAVE_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_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)strcat(lnk, "../");
    499 
    500 		(void)strcat(lnk, ++s);
    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_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 (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
    531 		if (!dolink) {
    532 			if (stat(from_name, &from_sb))
    533 				err(1, "%s: stat", from_name);
    534 			if (!S_ISREG(from_sb.st_mode))
    535 				errx(1, "%s: not a regular file", from_name);
    536 		}
    537 		/* Build the target path. */
    538 		if (flags & DIRECTORY) {
    539 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
    540 			    to_name,
    541 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
    542 			to_name = pathbuf;
    543 		}
    544 		devnull = 0;
    545 	} else {
    546 #if HAVE_STRUCT_STAT_ST_FLAGS
    547 		from_sb.st_flags = 0;	/* XXX */
    548 #endif
    549 		devnull = 1;
    550 	}
    551 
    552 	/*
    553 	 * Unlink now... avoid ETXTBSY errors later.  Try and turn
    554 	 * off the append/immutable bits -- if we fail, go ahead,
    555 	 * it might work.
    556 	 */
    557 #if !HAVE_CONFIG_H
    558 	if (stat(to_name, &to_sb) == 0 &&
    559 	    to_sb.st_flags & (NOCHANGEBITS))
    560 		(void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
    561 #endif
    562 	if (dorename) {
    563 		(void)snprintf(tmpl, sizeof(tmpl), "%s/inst.XXXXXX",
    564 		    xdirname(to_name));
    565 		oto_name = to_name;
    566 		to_name = tmpl;
    567 	} else {
    568 		oto_name = NULL;	/* pacify gcc */
    569 		if (dobackup)
    570 			backup(to_name);
    571 		else
    572 			(void)unlink(to_name);
    573 	}
    574 
    575 	if (dolink) {
    576 		makelink(from_name, dorename ? oto_name : to_name);
    577 		return;
    578 	}
    579 
    580 	/* Create target. */
    581 	if (dorename) {
    582 		if ((to_fd = mkstemp(to_name)) == -1)
    583 			err(1, "%s: mkstemp", to_name);
    584 	} else {
    585 		if ((to_fd = open(to_name,
    586 		    O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)) < 0)
    587 			err(1, "%s: open", to_name);
    588 	}
    589 	if (!devnull) {
    590 		if ((from_fd = open(from_name, O_RDONLY, 0)) < 0) {
    591 			(void)unlink(to_name);
    592 			err(1, "%s: open", from_name);
    593 		}
    594 		copy(from_fd, from_name, to_fd, to_name, from_sb.st_size);
    595 		(void)close(from_fd);
    596 	}
    597 
    598 	if (dostrip) {
    599 		strip(to_name);
    600 
    601 		/*
    602 		 * Re-open our fd on the target, in case we used a strip
    603 		 *  that does not work in-place -- like gnu binutils strip.
    604 		 */
    605 		close(to_fd);
    606 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    607 			err(1, "stripping %s", to_name);
    608 	}
    609 
    610 	if (afterinstallcmd != NULL) {
    611 		afterinstall(afterinstallcmd, to_name, 1);
    612 
    613 		/*
    614 		 * Re-open our fd on the target, in case we used an
    615 		 * after-install command that does not work in-place
    616 		 */
    617 		close(to_fd);
    618 		if ((to_fd = open(to_name, O_RDONLY, S_IRUSR | S_IWUSR)) < 0)
    619 			err(1, "running after install command on %s", to_name);
    620 	}
    621 
    622 	/*
    623 	 * Set owner, group, mode for target; do the chown first,
    624 	 * chown may lose the setuid bits.
    625 	 */
    626 	if (!dounpriv &&
    627 	    (flags & (HASUID | HASGID)) && fchown(to_fd, uid, gid) == -1) {
    628 		serrno = errno;
    629 		(void)unlink(to_name);
    630 		errx(1, "%s: chown/chgrp: %s", to_name, strerror(serrno));
    631 	}
    632 	tmpmode = mode;
    633 	if (dounpriv)
    634 		tmpmode &= S_IRWXU|S_IRWXG|S_IRWXO;
    635 	if (fchmod(to_fd, tmpmode) == -1) {
    636 		serrno = errno;
    637 		(void)unlink(to_name);
    638 		errx(1, "%s: chmod: %s", to_name, strerror(serrno));
    639 	}
    640 
    641 	/*
    642 	 * Preserve the date of the source file.
    643 	 */
    644 	if (dopreserve) {
    645 #ifdef BSD4_4
    646 		TIMESPEC_TO_TIMEVAL(&tv[0], &from_sb.st_atimespec);
    647 		TIMESPEC_TO_TIMEVAL(&tv[1], &from_sb.st_mtimespec);
    648 #else
    649 		tv[0].tv_sec = from_sb.st_atime;
    650 		tv[0].tv_usec = 0;
    651 		tv[1].tv_sec = from_sb.st_mtime;
    652 		tv[1].tv_usec = 0;
    653 #endif
    654 #if HAVE_FUTIMES
    655 		if (futimes(to_fd, tv) == -1)
    656 			warn("%s: futimes", to_name);
    657 #else
    658 		if (utimes(to_name, tv) == -1)
    659 			warn("%s: utimes", to_name);
    660 #endif
    661 	}
    662 
    663 	(void)close(to_fd);
    664 
    665 	if (dorename) {
    666 		if (rename(to_name, oto_name) == -1)
    667 			err(1, "%s: rename", to_name);
    668 		to_name = oto_name;
    669 	}
    670 
    671 	if (!docopy && !devnull && unlink(from_name))
    672 		err(1, "%s: unlink", from_name);
    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_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 #ifdef MADV_SEQUENTIAL
    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 		} else {
    733 mmap_failed:
    734 			while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
    735 				if ((nw = write(to_fd, buf, nr)) != nr) {
    736 					serrno = errno;
    737 					(void)unlink(to_name);
    738 					errx(1, "%s: write: %s", to_name,
    739 					    strerror(nw > 0 ? EIO : serrno));
    740 				}
    741 			}
    742 			if (nr != 0) {
    743 				serrno = errno;
    744 				(void)unlink(to_name);
    745 				errx(1, "%s: read: %s", from_name, strerror(serrno));
    746 			}
    747 		}
    748 	}
    749 }
    750 
    751 /*
    752  * strip --
    753  *	use strip(1) to strip the target file
    754  */
    755 void
    756 strip(char *to_name)
    757 {
    758 	int	serrno, status;
    759 	char	*stripprog;
    760 
    761 	switch (vfork()) {
    762 	case -1:
    763 		serrno = errno;
    764 		(void)unlink(to_name);
    765 		errx(1, "vfork: %s", strerror(serrno));
    766 		/*NOTREACHED*/
    767 	case 0:
    768 		stripprog = getenv("STRIP");
    769 		if (stripprog == NULL)
    770 			stripprog = _PATH_STRIP;
    771 
    772 		if (stripArgs) {
    773 			/*
    774 			 * build up a command line and let /bin/sh
    775 			 * parse the arguments
    776 			 */
    777 			char* cmd = (char*)malloc(sizeof(char)*
    778 						  (3+strlen(stripprog)+
    779 						     strlen(stripArgs)+
    780 						     strlen(to_name)));
    781 
    782 			if (cmd == NULL)
    783 				errx(1, "%s", strerror(ENOMEM));
    784 
    785 			sprintf(cmd, "%s %s %s", stripprog, stripArgs, to_name);
    786 
    787 			execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    788 		} else
    789 			execlp(stripprog, "strip", to_name, NULL);
    790 
    791 		warn("%s: exec of strip", stripprog);
    792 		_exit(1);
    793 		/*NOTREACHED*/
    794 	default:
    795 		if (wait(&status) == -1 || status)
    796 			(void)unlink(to_name);
    797 	}
    798 }
    799 
    800 /*
    801  * afterinstall --
    802  *	run provided command on the target file or directory after it's been
    803  *	installed and stripped, but before permissions are set or it's renamed
    804  */
    805 void
    806 afterinstall(const char *command, const char *to_name, int errunlink)
    807 {
    808 	int	serrno, status;
    809 	char	*cmd;
    810 
    811 	switch (vfork()) {
    812 	case -1:
    813 		serrno = errno;
    814 		if (errunlink)
    815 			(void)unlink(to_name);
    816 		errx(1, "vfork: %s", strerror(serrno));
    817 		/*NOTREACHED*/
    818 	case 0:
    819 		/*
    820 		 * build up a command line and let /bin/sh
    821 		 * parse the arguments
    822 		 */
    823 		cmd = (char*)malloc(sizeof(char)*
    824 					  (2+strlen(command)+
    825 					     strlen(to_name)));
    826 
    827 		if (cmd == NULL)
    828 			errx(1, "%s", strerror(ENOMEM));
    829 
    830 		sprintf(cmd, "%s %s", command, to_name);
    831 
    832 		execl(_PATH_BSHELL, "sh", "-c", cmd, NULL);
    833 
    834 		warn("%s: exec of after install command", command);
    835 		_exit(1);
    836 		/*NOTREACHED*/
    837 	default:
    838 		if ((wait(&status) == -1 || status) && errunlink)
    839 			(void)unlink(to_name);
    840 	}
    841 }
    842 
    843 /*
    844  * backup --
    845  *	backup file "to_name" to to_name.suffix
    846  *	if suffix contains a "%", it's taken as a printf(3) pattern
    847  *	used for a numbered backup.
    848  */
    849 void
    850 backup(const char *to_name)
    851 {
    852 	char	bname[FILENAME_MAX];
    853 
    854 	if (numberedbackup) {
    855 		/* Do numbered backup */
    856 		int cnt;
    857 		char suffix_expanded[FILENAME_MAX];
    858 
    859 		cnt=0;
    860 		do {
    861 			(void)snprintf(suffix_expanded, FILENAME_MAX, suffix,
    862 			    cnt);
    863 			(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name,
    864 			    suffix_expanded);
    865 			cnt++;
    866 		} while (access(bname, F_OK) == 0);
    867 	} else {
    868 		/* Do simple backup */
    869 		(void)snprintf(bname, FILENAME_MAX, "%s%s", to_name, suffix);
    870 	}
    871 
    872 	(void)rename(to_name, bname);
    873 }
    874 
    875 /*
    876  * install_dir --
    877  *	build directory hierarchy
    878  */
    879 void
    880 install_dir(char *path, u_int flags)
    881 {
    882         char		*p;
    883         struct stat	sb;
    884         int		ch;
    885 
    886         for (p = path;; ++p)
    887                 if (!*p || (p != path && *p  == '/')) {
    888                         ch = *p;
    889                         *p = '\0';
    890                         if (stat(path, &sb)) {
    891                                 if (errno != ENOENT || mkdir(path, 0777) < 0) {
    892 					err(1, "%s: mkdir", path);
    893                                 }
    894                         }
    895                         if (!(*p = ch))
    896 				break;
    897                 }
    898 
    899 	if (afterinstallcmd != NULL)
    900 		afterinstall(afterinstallcmd, path, 0);
    901 
    902 	if (!dounpriv && (
    903 	    ((flags & (HASUID | HASGID)) && chown(path, uid, gid) == -1)
    904 	    || chmod(path, mode) == -1 )) {
    905                 warn("%s: chown/chmod", path);
    906 	}
    907 	metadata_log(path, "dir", NULL, NULL);
    908 }
    909 
    910 /*
    911  * metadata_log --
    912  *	if metafp is not NULL, output mtree(8) full path name and settings to
    913  *	metafp, to allow permissions to be set correctly by other tools.
    914  */
    915 void
    916 metadata_log(const char *path, const char *type, struct timeval *tv,
    917 	const char *link)
    918 {
    919 	const char	extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
    920 	char		*buf;
    921 
    922 	if (!metafp)
    923 		return;
    924 	buf = (char *)malloc(4 * strlen(path) + 1);	/* buf for strsvis(3) */
    925 	if (buf == NULL) {
    926 		warnx("%s", strerror(ENOMEM));
    927 		return;
    928 	}
    929 	if (flock(fileno(metafp), LOCK_EX) == -1) {	/* lock log file */
    930 		warn("can't lock %s", metafile);
    931 		return;
    932 	}
    933 
    934 	strsvis(buf, path, VIS_CSTYLE, extra);		/* encode name */
    935 	fprintf(metafp, ".%s%s type=%s mode=%#o",	/* print details */
    936 	    buf[0] == '/' ? "" : "/", buf, type, mode);
    937 	if (link)
    938 		fprintf(metafp, " link=%s", link);
    939 	if (owner)
    940 		fprintf(metafp, " uname=%s", owner);
    941 	if (group)
    942 		fprintf(metafp, " gname=%s", group);
    943 	if (fflags)
    944 		fprintf(metafp, " flags=%s", fflags);
    945 	if (tags)
    946 		fprintf(metafp, " tags=%s", tags);
    947 	if (tv != NULL && dopreserve)
    948 		fprintf(metafp, " time=%ld.%ld", tv[1].tv_sec, tv[1].tv_usec);
    949 	fputc('\n', metafp);
    950 	fflush(metafp);					/* flush output */
    951 	if (flock(fileno(metafp), LOCK_UN) == -1) {	/* unlock log file */
    952 		warn("can't unlock %s", metafile);
    953 	}
    954 	free(buf);
    955 }
    956 
    957 /*
    958  * xbasename --
    959  *	libc basename(3) that returns a pointer to a static buffer
    960  *	instead of overwriting that passed-in string.
    961  */
    962 char *
    963 xbasename(char *path)
    964 {
    965 	static char tmp[MAXPATHLEN];
    966 
    967 	(void)strlcpy(tmp, path, sizeof(tmp));
    968 	return (basename(tmp));
    969 }
    970 
    971 /*
    972  * xdirname --
    973  *	libc dirname(3) that returns a pointer to a static buffer
    974  *	instead of overwriting that passed-in string.
    975  */
    976 char *
    977 xdirname(char *path)
    978 {
    979 	static char tmp[MAXPATHLEN];
    980 
    981 	(void)strlcpy(tmp, path, sizeof(tmp));
    982 	return (dirname(tmp));
    983 }
    984 
    985 /*
    986  * usage --
    987  *	print a usage message and die
    988  */
    989 void
    990 usage(void)
    991 {
    992 	const char *prog;
    993 
    994 	prog = getprogname();
    995 
    996 	(void)fprintf(stderr,
    997 "usage: %s [-Ubcprs] [-M log] [-T tags] [-B suffix] [-a afterinstallcmd]\n"
    998 "           [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags]\n"
    999 "           [-S stripflags] file1 file2\n"
   1000 "       %s [-Ubcprs] [-M log] [-T tags] [-B suffix] [-a afterinstallcmd]\n"
   1001 "           [-f flags] [-m mode] [-o owner] [-g group] [-l linkflags]\n"
   1002 "           [-S stripflags] file1 ... fileN directory\n"
   1003 "       %s -d [-Up] [-M log] [-T tags] [-a afterinstallcmd] [-m mode]\n"
   1004 "           [-o owner] [-g group] directory ...\n",
   1005 	    prog, prog, prog);
   1006 	exit(1);
   1007 }
   1008