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