xref: /freebsd/usr.bin/xinstall/xinstall.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2012, 2013 SRI International
5  * Copyright (c) 1987, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1987, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #if 0
40 #ifndef lint
41 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
42 #endif /* not lint */
43 #endif
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include <sys/param.h>
49 #include <sys/mman.h>
50 #include <sys/mount.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 #include <sys/wait.h>
54 
55 #include <err.h>
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <grp.h>
59 #include <libgen.h>
60 #include <md5.h>
61 #include <paths.h>
62 #include <pwd.h>
63 #include <ripemd.h>
64 #include <sha.h>
65 #include <sha256.h>
66 #include <sha512.h>
67 #include <spawn.h>
68 #include <stdint.h>
69 #include <stdio.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <sysexits.h>
73 #include <unistd.h>
74 #include <vis.h>
75 
76 #include "mtree.h"
77 
78 #define MAX_CMP_SIZE	(16 * 1024 * 1024)
79 
80 #define	LN_ABSOLUTE	0x01
81 #define	LN_RELATIVE	0x02
82 #define	LN_HARD		0x04
83 #define	LN_SYMBOLIC	0x08
84 #define	LN_MIXED	0x10
85 
86 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
87 #define	SETFLAGS	0x02		/* Tell install to set flags. */
88 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
89 #define	BACKUP_SUFFIX	".old"
90 
91 typedef union {
92 	MD5_CTX		MD5;
93 	RIPEMD160_CTX	RIPEMD160;
94 	SHA1_CTX	SHA1;
95 	SHA256_CTX	SHA256;
96 	SHA512_CTX	SHA512;
97 }	DIGEST_CTX;
98 
99 static enum {
100 	DIGEST_NONE = 0,
101 	DIGEST_MD5,
102 	DIGEST_RIPEMD160,
103 	DIGEST_SHA1,
104 	DIGEST_SHA256,
105 	DIGEST_SHA512,
106 } digesttype = DIGEST_NONE;
107 
108 extern char **environ;
109 
110 static gid_t gid;
111 static uid_t uid;
112 static int dobackup, docompare, dodir, dolink, dopreserve, dostrip, dounpriv,
113     safecopy, verbose;
114 static int haveopt_f, haveopt_g, haveopt_m, haveopt_o;
115 static mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
116 static FILE *metafp;
117 static const char *group, *owner;
118 static const char *suffix = BACKUP_SUFFIX;
119 static char *destdir, *digest, *fflags, *metafile, *tags;
120 
121 static int	compare(int, const char *, size_t, int, const char *, size_t,
122 		    char **);
123 static char	*copy(int, const char *, int, const char *, off_t);
124 static int	create_newfile(const char *, int, struct stat *);
125 static int	create_tempfile(const char *, char *, size_t);
126 static char	*quiet_mktemp(char *template);
127 static char	*digest_file(const char *);
128 static void	digest_init(DIGEST_CTX *);
129 static void	digest_update(DIGEST_CTX *, const char *, size_t);
130 static char	*digest_end(DIGEST_CTX *, char *);
131 static int	do_link(const char *, const char *, const struct stat *);
132 static void	do_symlink(const char *, const char *, const struct stat *);
133 static void	makelink(const char *, const char *, const struct stat *);
134 static void	install(const char *, const char *, u_long, u_int);
135 static void	install_dir(char *);
136 static void	metadata_log(const char *, const char *, struct timespec *,
137 		    const char *, const char *, off_t);
138 static int	parseid(const char *, id_t *);
139 static void	strip(const char *);
140 static int	trymmap(int);
141 static void	usage(void);
142 
143 int
144 main(int argc, char *argv[])
145 {
146 	struct stat from_sb, to_sb;
147 	mode_t *set;
148 	u_long fset;
149 	int ch, no_target;
150 	u_int iflags;
151 	char *p;
152 	const char *to_name;
153 
154 	fset = 0;
155 	iflags = 0;
156 	group = owner = NULL;
157 	while ((ch = getopt(argc, argv, "B:bCcD:df:g:h:l:M:m:N:o:pSsT:Uv")) !=
158 	     -1)
159 		switch((char)ch) {
160 		case 'B':
161 			suffix = optarg;
162 			/* FALLTHROUGH */
163 		case 'b':
164 			dobackup = 1;
165 			break;
166 		case 'C':
167 			docompare = 1;
168 			break;
169 		case 'c':
170 			/* For backwards compatibility. */
171 			break;
172 		case 'D':
173 			destdir = optarg;
174 			break;
175 		case 'd':
176 			dodir = 1;
177 			break;
178 		case 'f':
179 			haveopt_f = 1;
180 			fflags = optarg;
181 			break;
182 		case 'g':
183 			haveopt_g = 1;
184 			group = optarg;
185 			break;
186 		case 'h':
187 			digest = optarg;
188 			break;
189 		case 'l':
190 			for (p = optarg; *p != '\0'; p++)
191 				switch (*p) {
192 				case 's':
193 					dolink &= ~(LN_HARD|LN_MIXED);
194 					dolink |= LN_SYMBOLIC;
195 					break;
196 				case 'h':
197 					dolink &= ~(LN_SYMBOLIC|LN_MIXED);
198 					dolink |= LN_HARD;
199 					break;
200 				case 'm':
201 					dolink &= ~(LN_SYMBOLIC|LN_HARD);
202 					dolink |= LN_MIXED;
203 					break;
204 				case 'a':
205 					dolink &= ~LN_RELATIVE;
206 					dolink |= LN_ABSOLUTE;
207 					break;
208 				case 'r':
209 					dolink &= ~LN_ABSOLUTE;
210 					dolink |= LN_RELATIVE;
211 					break;
212 				default:
213 					errx(1, "%c: invalid link type", *p);
214 					/* NOTREACHED */
215 				}
216 			break;
217 		case 'M':
218 			metafile = optarg;
219 			break;
220 		case 'm':
221 			haveopt_m = 1;
222 			if (!(set = setmode(optarg)))
223 				errx(EX_USAGE, "invalid file mode: %s",
224 				     optarg);
225 			mode = getmode(set, 0);
226 			free(set);
227 			break;
228 		case 'N':
229 			if (!setup_getid(optarg))
230 				err(EX_OSERR, "Unable to use user and group "
231 				    "databases in `%s'", optarg);
232 			break;
233 		case 'o':
234 			haveopt_o = 1;
235 			owner = optarg;
236 			break;
237 		case 'p':
238 			docompare = dopreserve = 1;
239 			break;
240 		case 'S':
241 			safecopy = 1;
242 			break;
243 		case 's':
244 			dostrip = 1;
245 			break;
246 		case 'T':
247 			tags = optarg;
248 			break;
249 		case 'U':
250 			dounpriv = 1;
251 			break;
252 		case 'v':
253 			verbose = 1;
254 			break;
255 		case '?':
256 		default:
257 			usage();
258 		}
259 	argc -= optind;
260 	argv += optind;
261 
262 	/* some options make no sense when creating directories */
263 	if (dostrip && dodir) {
264 		warnx("-d and -s may not be specified together");
265 		usage();
266 	}
267 
268 	if (getenv("DONTSTRIP") != NULL) {
269 		warnx("DONTSTRIP set - will not strip installed binaries");
270 		dostrip = 0;
271 	}
272 
273 	/* must have at least two arguments, except when creating directories */
274 	if (argc == 0 || (argc == 1 && !dodir))
275 		usage();
276 
277 	if (digest != NULL) {
278 		if (strcmp(digest, "none") == 0) {
279 			digesttype = DIGEST_NONE;
280 		} else if (strcmp(digest, "md5") == 0) {
281 		       digesttype = DIGEST_MD5;
282 		} else if (strcmp(digest, "rmd160") == 0) {
283 			digesttype = DIGEST_RIPEMD160;
284 		} else if (strcmp(digest, "sha1") == 0) {
285 			digesttype = DIGEST_SHA1;
286 		} else if (strcmp(digest, "sha256") == 0) {
287 			digesttype = DIGEST_SHA256;
288 		} else if (strcmp(digest, "sha512") == 0) {
289 			digesttype = DIGEST_SHA512;
290 		} else {
291 			warnx("unknown digest `%s'", digest);
292 			usage();
293 		}
294 	}
295 
296 	/* need to make a temp copy so we can compare stripped version */
297 	if (docompare && dostrip)
298 		safecopy = 1;
299 
300 	/* get group and owner id's */
301 	if (group != NULL && !dounpriv) {
302 		if (gid_from_group(group, &gid) == -1) {
303 			id_t id;
304 			if (!parseid(group, &id))
305 				errx(1, "unknown group %s", group);
306 			gid = id;
307 		}
308 	} else
309 		gid = (gid_t)-1;
310 
311 	if (owner != NULL && !dounpriv) {
312 		if (uid_from_user(owner, &uid) == -1) {
313 			id_t id;
314 			if (!parseid(owner, &id))
315 				errx(1, "unknown user %s", owner);
316 			uid = id;
317 		}
318 	} else
319 		uid = (uid_t)-1;
320 
321 	if (fflags != NULL && !dounpriv) {
322 		if (strtofflags(&fflags, &fset, NULL))
323 			errx(EX_USAGE, "%s: invalid flag", fflags);
324 		iflags |= SETFLAGS;
325 	}
326 
327 	if (metafile != NULL) {
328 		if ((metafp = fopen(metafile, "a")) == NULL)
329 			warn("open %s", metafile);
330 	} else
331 		digesttype = DIGEST_NONE;
332 
333 	if (dodir) {
334 		for (; *argv != NULL; ++argv)
335 			install_dir(*argv);
336 		exit(EX_OK);
337 		/* NOTREACHED */
338 	}
339 
340 	to_name = argv[argc - 1];
341 	no_target = stat(to_name, &to_sb);
342 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
343 		if (dolink & LN_SYMBOLIC) {
344 			if (lstat(to_name, &to_sb) != 0)
345 				err(EX_OSERR, "%s vanished", to_name);
346 			if (S_ISLNK(to_sb.st_mode)) {
347 				if (argc != 2) {
348 					errno = ENOTDIR;
349 					err(EX_USAGE, "%s", to_name);
350 				}
351 				install(*argv, to_name, fset, iflags);
352 				exit(EX_OK);
353 			}
354 		}
355 		for (; *argv != to_name; ++argv)
356 			install(*argv, to_name, fset, iflags | DIRECTORY);
357 		exit(EX_OK);
358 		/* NOTREACHED */
359 	}
360 
361 	/* can't do file1 file2 directory/file */
362 	if (argc != 2) {
363 		if (no_target)
364 			warnx("target directory `%s' does not exist",
365 			    argv[argc - 1]);
366 		else
367 			warnx("target `%s' is not a directory",
368 			    argv[argc - 1]);
369 		usage();
370 	}
371 
372 	if (!no_target && !dolink) {
373 		if (stat(*argv, &from_sb))
374 			err(EX_OSERR, "%s", *argv);
375 		if (!S_ISREG(to_sb.st_mode)) {
376 			errno = EFTYPE;
377 			err(EX_OSERR, "%s", to_name);
378 		}
379 		if (to_sb.st_dev == from_sb.st_dev &&
380 		    to_sb.st_ino == from_sb.st_ino)
381 			errx(EX_USAGE,
382 			    "%s and %s are the same file", *argv, to_name);
383 	}
384 	install(*argv, to_name, fset, iflags);
385 	exit(EX_OK);
386 	/* NOTREACHED */
387 }
388 
389 static char *
390 digest_file(const char *name)
391 {
392 
393 	switch (digesttype) {
394 	case DIGEST_MD5:
395 		return (MD5File(name, NULL));
396 	case DIGEST_RIPEMD160:
397 		return (RIPEMD160_File(name, NULL));
398 	case DIGEST_SHA1:
399 		return (SHA1_File(name, NULL));
400 	case DIGEST_SHA256:
401 		return (SHA256_File(name, NULL));
402 	case DIGEST_SHA512:
403 		return (SHA512_File(name, NULL));
404 	default:
405 		return (NULL);
406 	}
407 }
408 
409 static void
410 digest_init(DIGEST_CTX *c)
411 {
412 
413 	switch (digesttype) {
414 	case DIGEST_NONE:
415 		break;
416 	case DIGEST_MD5:
417 		MD5Init(&(c->MD5));
418 		break;
419 	case DIGEST_RIPEMD160:
420 		RIPEMD160_Init(&(c->RIPEMD160));
421 		break;
422 	case DIGEST_SHA1:
423 		SHA1_Init(&(c->SHA1));
424 		break;
425 	case DIGEST_SHA256:
426 		SHA256_Init(&(c->SHA256));
427 		break;
428 	case DIGEST_SHA512:
429 		SHA512_Init(&(c->SHA512));
430 		break;
431 	}
432 }
433 
434 static void
435 digest_update(DIGEST_CTX *c, const char *data, size_t len)
436 {
437 
438 	switch (digesttype) {
439 	case DIGEST_NONE:
440 		break;
441 	case DIGEST_MD5:
442 		MD5Update(&(c->MD5), data, len);
443 		break;
444 	case DIGEST_RIPEMD160:
445 		RIPEMD160_Update(&(c->RIPEMD160), data, len);
446 		break;
447 	case DIGEST_SHA1:
448 		SHA1_Update(&(c->SHA1), data, len);
449 		break;
450 	case DIGEST_SHA256:
451 		SHA256_Update(&(c->SHA256), data, len);
452 		break;
453 	case DIGEST_SHA512:
454 		SHA512_Update(&(c->SHA512), data, len);
455 		break;
456 	}
457 }
458 
459 static char *
460 digest_end(DIGEST_CTX *c, char *buf)
461 {
462 
463 	switch (digesttype) {
464 	case DIGEST_MD5:
465 		return (MD5End(&(c->MD5), buf));
466 	case DIGEST_RIPEMD160:
467 		return (RIPEMD160_End(&(c->RIPEMD160), buf));
468 	case DIGEST_SHA1:
469 		return (SHA1_End(&(c->SHA1), buf));
470 	case DIGEST_SHA256:
471 		return (SHA256_End(&(c->SHA256), buf));
472 	case DIGEST_SHA512:
473 		return (SHA512_End(&(c->SHA512), buf));
474 	default:
475 		return (NULL);
476 	}
477 }
478 
479 /*
480  * parseid --
481  *	parse uid or gid from arg into id, returning non-zero if successful
482  */
483 static int
484 parseid(const char *name, id_t *id)
485 {
486 	char	*ep;
487 	errno = 0;
488 	*id = (id_t)strtoul(name, &ep, 10);
489 	if (errno || *ep != '\0')
490 		return (0);
491 	return (1);
492 }
493 
494 /*
495  * quiet_mktemp --
496  *	mktemp implementation used mkstemp to avoid mktemp warnings.  We
497  *	really do need mktemp semantics here as we will be creating a link.
498  */
499 static char *
500 quiet_mktemp(char *template)
501 {
502 	int fd;
503 
504 	if ((fd = mkstemp(template)) == -1)
505 		return (NULL);
506 	close (fd);
507 	if (unlink(template) == -1)
508 		err(EX_OSERR, "unlink %s", template);
509 	return (template);
510 }
511 
512 /*
513  * do_link --
514  *	make a hard link, obeying dorename if set
515  *	return -1 on failure
516  */
517 static int
518 do_link(const char *from_name, const char *to_name,
519     const struct stat *target_sb)
520 {
521 	char tmpl[MAXPATHLEN];
522 	int ret;
523 
524 	if (safecopy && target_sb != NULL) {
525 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
526 		/* This usage is safe. */
527 		if (quiet_mktemp(tmpl) == NULL)
528 			err(EX_OSERR, "%s: mktemp", tmpl);
529 		ret = link(from_name, tmpl);
530 		if (ret == 0) {
531 			if (target_sb->st_mode & S_IFDIR && rmdir(to_name) ==
532 			    -1) {
533 				unlink(tmpl);
534 				err(EX_OSERR, "%s", to_name);
535 			}
536 #if HAVE_STRUCT_STAT_ST_FLAGS
537 			if (target_sb->st_flags & NOCHANGEBITS)
538 				(void)chflags(to_name, target_sb->st_flags &
539 				     ~NOCHANGEBITS);
540 #endif
541 			if (verbose)
542 				printf("install: link %s -> %s\n",
543 				    from_name, to_name);
544 			ret = rename(tmpl, to_name);
545 			/*
546 			 * If rename has posix semantics, then the temporary
547 			 * file may still exist when from_name and to_name point
548 			 * to the same file, so unlink it unconditionally.
549 			 */
550 			(void)unlink(tmpl);
551 		}
552 		return (ret);
553 	} else {
554 		if (verbose)
555 			printf("install: link %s -> %s\n",
556 			    from_name, to_name);
557 		return (link(from_name, to_name));
558 	}
559 }
560 
561 /*
562  * do_symlink --
563  *	Make a symbolic link, obeying dorename if set. Exit on failure.
564  */
565 static void
566 do_symlink(const char *from_name, const char *to_name,
567     const struct stat *target_sb)
568 {
569 	char tmpl[MAXPATHLEN];
570 
571 	if (safecopy && target_sb != NULL) {
572 		(void)snprintf(tmpl, sizeof(tmpl), "%s.inst.XXXXXX", to_name);
573 		/* This usage is safe. */
574 		if (quiet_mktemp(tmpl) == NULL)
575 			err(EX_OSERR, "%s: mktemp", tmpl);
576 
577 		if (symlink(from_name, tmpl) == -1)
578 			err(EX_OSERR, "symlink %s -> %s", from_name, tmpl);
579 
580 		if (target_sb->st_mode & S_IFDIR && rmdir(to_name) == -1) {
581 			(void)unlink(tmpl);
582 			err(EX_OSERR, "%s", to_name);
583 		}
584 #if HAVE_STRUCT_STAT_ST_FLAGS
585 		if (target_sb->st_flags & NOCHANGEBITS)
586 			(void)chflags(to_name, target_sb->st_flags &
587 			     ~NOCHANGEBITS);
588 #endif
589 		if (verbose)
590 			printf("install: symlink %s -> %s\n",
591 			    from_name, to_name);
592 		if (rename(tmpl, to_name) == -1) {
593 			/* Remove temporary link before exiting. */
594 			(void)unlink(tmpl);
595 			err(EX_OSERR, "%s: rename", to_name);
596 		}
597 	} else {
598 		if (verbose)
599 			printf("install: symlink %s -> %s\n",
600 			    from_name, to_name);
601 		if (symlink(from_name, to_name) == -1)
602 			err(EX_OSERR, "symlink %s -> %s", from_name, to_name);
603 	}
604 }
605 
606 /*
607  * makelink --
608  *	make a link from source to destination
609  */
610 static void
611 makelink(const char *from_name, const char *to_name,
612     const struct stat *target_sb)
613 {
614 	char	src[MAXPATHLEN], dst[MAXPATHLEN], lnk[MAXPATHLEN];
615 	struct stat	to_sb;
616 
617 	/* Try hard links first. */
618 	if (dolink & (LN_HARD|LN_MIXED)) {
619 		if (do_link(from_name, to_name, target_sb) == -1) {
620 			if ((dolink & LN_HARD) || errno != EXDEV)
621 				err(EX_OSERR, "link %s -> %s", from_name, to_name);
622 		} else {
623 			if (stat(to_name, &to_sb))
624 				err(EX_OSERR, "%s: stat", to_name);
625 			if (S_ISREG(to_sb.st_mode)) {
626 				/*
627 				 * XXX: hard links to anything other than
628 				 * plain files are not metalogged
629 				 */
630 				int omode;
631 				const char *oowner, *ogroup;
632 				char *offlags;
633 				char *dres;
634 
635 				/*
636 				 * XXX: use underlying perms, unless
637 				 * overridden on command line.
638 				 */
639 				omode = mode;
640 				if (!haveopt_m)
641 					mode = (to_sb.st_mode & 0777);
642 				oowner = owner;
643 				if (!haveopt_o)
644 					owner = NULL;
645 				ogroup = group;
646 				if (!haveopt_g)
647 					group = NULL;
648 				offlags = fflags;
649 				if (!haveopt_f)
650 					fflags = NULL;
651 				dres = digest_file(from_name);
652 				metadata_log(to_name, "file", NULL, NULL,
653 				    dres, to_sb.st_size);
654 				free(dres);
655 				mode = omode;
656 				owner = oowner;
657 				group = ogroup;
658 				fflags = offlags;
659 			}
660 			return;
661 		}
662 	}
663 
664 	/* Symbolic links. */
665 	if (dolink & LN_ABSOLUTE) {
666 		/* Convert source path to absolute. */
667 		if (realpath(from_name, src) == NULL)
668 			err(EX_OSERR, "%s: realpath", from_name);
669 		do_symlink(src, to_name, target_sb);
670 		/* XXX: src may point outside of destdir */
671 		metadata_log(to_name, "link", NULL, src, NULL, 0);
672 		return;
673 	}
674 
675 	if (dolink & LN_RELATIVE) {
676 		char *to_name_copy, *cp, *d, *ld, *ls, *s;
677 
678 		if (*from_name != '/') {
679 			/* this is already a relative link */
680 			do_symlink(from_name, to_name, target_sb);
681 			/* XXX: from_name may point outside of destdir. */
682 			metadata_log(to_name, "link", NULL, from_name, NULL, 0);
683 			return;
684 		}
685 
686 		/* Resolve pathnames. */
687 		if (realpath(from_name, src) == NULL)
688 			err(EX_OSERR, "%s: realpath", from_name);
689 
690 		/*
691 		 * The last component of to_name may be a symlink,
692 		 * so use realpath to resolve only the directory.
693 		 */
694 		to_name_copy = strdup(to_name);
695 		if (to_name_copy == NULL)
696 			err(EX_OSERR, "%s: strdup", to_name);
697 		cp = dirname(to_name_copy);
698 		if (realpath(cp, dst) == NULL)
699 			err(EX_OSERR, "%s: realpath", cp);
700 		/* .. and add the last component. */
701 		if (strcmp(dst, "/") != 0) {
702 			if (strlcat(dst, "/", sizeof(dst)) > sizeof(dst))
703 				errx(1, "resolved pathname too long");
704 		}
705 		strcpy(to_name_copy, to_name);
706 		cp = basename(to_name_copy);
707 		if (strlcat(dst, cp, sizeof(dst)) > sizeof(dst))
708 			errx(1, "resolved pathname too long");
709 		free(to_name_copy);
710 
711 		/* Trim common path components. */
712 		ls = ld = NULL;
713 		for (s = src, d = dst; *s == *d; ls = s, ld = d, s++, d++)
714 			continue;
715 		/*
716 		 * If we didn't end after a directory separator, then we've
717 		 * falsely matched the last component.  For example, if one
718 		 * invoked install -lrs /lib/foo.so /libexec/ then the source
719 		 * would terminate just after the separator while the
720 		 * destination would terminate in the middle of 'libexec',
721 		 * leading to a full directory getting falsely eaten.
722 		 */
723 		if ((ls != NULL && *ls != '/') || (ld != NULL && *ld != '/'))
724 			s--, d--;
725 		while (*s != '/')
726 			s--, d--;
727 
728 		/* Count the number of directories we need to backtrack. */
729 		for (++d, lnk[0] = '\0'; *d; d++)
730 			if (*d == '/')
731 				(void)strlcat(lnk, "../", sizeof(lnk));
732 
733 		(void)strlcat(lnk, ++s, sizeof(lnk));
734 
735 		do_symlink(lnk, to_name, target_sb);
736 		/* XXX: Link may point outside of destdir. */
737 		metadata_log(to_name, "link", NULL, lnk, NULL, 0);
738 		return;
739 	}
740 
741 	/*
742 	 * If absolute or relative was not specified, try the names the
743 	 * user provided.
744 	 */
745 	do_symlink(from_name, to_name, target_sb);
746 	/* XXX: from_name may point outside of destdir. */
747 	metadata_log(to_name, "link", NULL, from_name, NULL, 0);
748 }
749 
750 /*
751  * install --
752  *	build a path name and install the file
753  */
754 static void
755 install(const char *from_name, const char *to_name, u_long fset, u_int flags)
756 {
757 	struct stat from_sb, temp_sb, to_sb;
758 	struct timespec tsb[2];
759 	int devnull, files_match, from_fd, serrno, target;
760 	int tempcopy, temp_fd, to_fd;
761 	char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
762 	char *digestresult;
763 
764 	files_match = 0;
765 	from_fd = -1;
766 	to_fd = -1;
767 
768 	/* If try to install NULL file to a directory, fails. */
769 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
770 		if (!dolink) {
771 			if (stat(from_name, &from_sb))
772 				err(EX_OSERR, "%s", from_name);
773 			if (!S_ISREG(from_sb.st_mode)) {
774 				errno = EFTYPE;
775 				err(EX_OSERR, "%s", from_name);
776 			}
777 		}
778 		/* Build the target path. */
779 		if (flags & DIRECTORY) {
780 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s%s%s",
781 			    to_name,
782 			    to_name[strlen(to_name) - 1] == '/' ? "" : "/",
783 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
784 			to_name = pathbuf;
785 		}
786 		devnull = 0;
787 	} else {
788 		devnull = 1;
789 	}
790 
791 	target = (lstat(to_name, &to_sb) == 0);
792 
793 	if (dolink) {
794 		if (target && !safecopy) {
795 			if (to_sb.st_mode & S_IFDIR && rmdir(to_name) == -1)
796 				err(EX_OSERR, "%s", to_name);
797 #if HAVE_STRUCT_STAT_ST_FLAGS
798 			if (to_sb.st_flags & NOCHANGEBITS)
799 				(void)chflags(to_name,
800 				    to_sb.st_flags & ~NOCHANGEBITS);
801 #endif
802 			unlink(to_name);
803 		}
804 		makelink(from_name, to_name, target ? &to_sb : NULL);
805 		return;
806 	}
807 
808 	if (target && !S_ISREG(to_sb.st_mode) && !S_ISLNK(to_sb.st_mode)) {
809 		errno = EFTYPE;
810 		warn("%s", to_name);
811 		return;
812 	}
813 
814 	/* Only copy safe if the target exists. */
815 	tempcopy = safecopy && target;
816 
817 	if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
818 		err(EX_OSERR, "%s", from_name);
819 
820 	/* If we don't strip, we can compare first. */
821 	if (docompare && !dostrip && target && S_ISREG(to_sb.st_mode)) {
822 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
823 			err(EX_OSERR, "%s", to_name);
824 		if (devnull)
825 			files_match = to_sb.st_size == 0;
826 		else
827 			files_match = !(compare(from_fd, from_name,
828 			    (size_t)from_sb.st_size, to_fd,
829 			    to_name, (size_t)to_sb.st_size, &digestresult));
830 
831 		/* Close "to" file unless we match. */
832 		if (!files_match)
833 			(void)close(to_fd);
834 	}
835 
836 	if (!files_match) {
837 		if (tempcopy) {
838 			to_fd = create_tempfile(to_name, tempfile,
839 			    sizeof(tempfile));
840 			if (to_fd < 0)
841 				err(EX_OSERR, "%s", tempfile);
842 		} else {
843 			if ((to_fd = create_newfile(to_name, target,
844 			    &to_sb)) < 0)
845 				err(EX_OSERR, "%s", to_name);
846 			if (verbose)
847 				(void)printf("install: %s -> %s\n",
848 				    from_name, to_name);
849 		}
850 		if (!devnull)
851 			digestresult = copy(from_fd, from_name, to_fd,
852 			     tempcopy ? tempfile : to_name, from_sb.st_size);
853 		else
854 			digestresult = NULL;
855 	}
856 
857 	if (dostrip) {
858 		strip(tempcopy ? tempfile : to_name);
859 
860 		/*
861 		 * Re-open our fd on the target, in case we used a strip
862 		 * that does not work in-place -- like GNU binutils strip.
863 		 */
864 		close(to_fd);
865 		to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
866 		if (to_fd < 0)
867 			err(EX_OSERR, "stripping %s", to_name);
868 	}
869 
870 	/*
871 	 * Compare the stripped temp file with the target.
872 	 */
873 	if (docompare && dostrip && target && S_ISREG(to_sb.st_mode)) {
874 		temp_fd = to_fd;
875 
876 		/* Re-open to_fd using the real target name. */
877 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
878 			err(EX_OSERR, "%s", to_name);
879 
880 		if (fstat(temp_fd, &temp_sb)) {
881 			serrno = errno;
882 			(void)unlink(tempfile);
883 			errno = serrno;
884 			err(EX_OSERR, "%s", tempfile);
885 		}
886 
887 		if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
888 			    to_name, (size_t)to_sb.st_size, &digestresult)
889 			    == 0) {
890 			/*
891 			 * If target has more than one link we need to
892 			 * replace it in order to snap the extra links.
893 			 * Need to preserve target file times, though.
894 			 */
895 			if (to_sb.st_nlink != 1) {
896 				tsb[0] = to_sb.st_atim;
897 				tsb[1] = to_sb.st_mtim;
898 				(void)utimensat(AT_FDCWD, tempfile, tsb, 0);
899 			} else {
900 				files_match = 1;
901 				(void)unlink(tempfile);
902 			}
903 			(void) close(temp_fd);
904 		}
905 	} else if (dostrip)
906 		digestresult = digest_file(tempfile);
907 
908 	/*
909 	 * Move the new file into place if doing a safe copy
910 	 * and the files are different (or just not compared).
911 	 */
912 	if (tempcopy && !files_match) {
913 #if HAVE_STRUCT_STAT_ST_FLAGS
914 		/* Try to turn off the immutable bits. */
915 		if (to_sb.st_flags & NOCHANGEBITS)
916 			(void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
917 #endif
918 		if (dobackup) {
919 			if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
920 			    suffix) != strlen(to_name) + strlen(suffix)) {
921 				unlink(tempfile);
922 				errx(EX_OSERR, "%s: backup filename too long",
923 				    to_name);
924 			}
925 			if (verbose)
926 				(void)printf("install: %s -> %s\n", to_name, backup);
927 			if (unlink(backup) < 0 && errno != ENOENT) {
928 				serrno = errno;
929 #if HAVE_STRUCT_STAT_ST_FLAGS
930 				if (to_sb.st_flags & NOCHANGEBITS)
931 					(void)chflags(to_name, to_sb.st_flags);
932 #endif
933 				unlink(tempfile);
934 				errno = serrno;
935 				err(EX_OSERR, "unlink: %s", backup);
936 			}
937 			if (link(to_name, backup) < 0) {
938 				serrno = errno;
939 				unlink(tempfile);
940 #if HAVE_STRUCT_STAT_ST_FLAGS
941 				if (to_sb.st_flags & NOCHANGEBITS)
942 					(void)chflags(to_name, to_sb.st_flags);
943 #endif
944 				errno = serrno;
945 				err(EX_OSERR, "link: %s to %s", to_name,
946 				     backup);
947 			}
948 		}
949 		if (verbose)
950 			(void)printf("install: %s -> %s\n", from_name, to_name);
951 		if (rename(tempfile, to_name) < 0) {
952 			serrno = errno;
953 			unlink(tempfile);
954 			errno = serrno;
955 			err(EX_OSERR, "rename: %s to %s",
956 			    tempfile, to_name);
957 		}
958 
959 		/* Re-open to_fd so we aren't hosed by the rename(2). */
960 		(void) close(to_fd);
961 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
962 			err(EX_OSERR, "%s", to_name);
963 	}
964 
965 	/*
966 	 * Preserve the timestamp of the source file if necessary.
967 	 */
968 	if (dopreserve && !files_match && !devnull) {
969 		tsb[0] = from_sb.st_atim;
970 		tsb[1] = from_sb.st_mtim;
971 		(void)utimensat(AT_FDCWD, to_name, tsb, 0);
972 	}
973 
974 	if (fstat(to_fd, &to_sb) == -1) {
975 		serrno = errno;
976 		(void)unlink(to_name);
977 		errno = serrno;
978 		err(EX_OSERR, "%s", to_name);
979 	}
980 
981 	/*
982 	 * Set owner, group, mode for target; do the chown first,
983 	 * chown may lose the setuid bits.
984 	 */
985 	if (!dounpriv && ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
986 	    (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
987 	    (mode != (to_sb.st_mode & ALLPERMS)))) {
988 #if HAVE_STRUCT_STAT_ST_FLAGS
989 		/* Try to turn off the immutable bits. */
990 		if (to_sb.st_flags & NOCHANGEBITS)
991 			(void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
992 #endif
993 	}
994 
995 	if (!dounpriv &
996 	    (gid != (gid_t)-1 && gid != to_sb.st_gid) ||
997 	    (uid != (uid_t)-1 && uid != to_sb.st_uid))
998 		if (fchown(to_fd, uid, gid) == -1) {
999 			serrno = errno;
1000 			(void)unlink(to_name);
1001 			errno = serrno;
1002 			err(EX_OSERR,"%s: chown/chgrp", to_name);
1003 		}
1004 
1005 	if (mode != (to_sb.st_mode & ALLPERMS)) {
1006 		if (fchmod(to_fd,
1007 		     dounpriv ? mode & (S_IRWXU|S_IRWXG|S_IRWXO) : mode)) {
1008 			serrno = errno;
1009 			(void)unlink(to_name);
1010 			errno = serrno;
1011 			err(EX_OSERR, "%s: chmod", to_name);
1012 		}
1013 	}
1014 #if HAVE_STRUCT_STAT_ST_FLAGS
1015 	/*
1016 	 * If provided a set of flags, set them, otherwise, preserve the
1017 	 * flags, except for the dump flag.
1018 	 * NFS does not support flags.  Ignore EOPNOTSUPP flags if we're just
1019 	 * trying to turn off UF_NODUMP.  If we're trying to set real flags,
1020 	 * then warn if the fs doesn't support it, otherwise fail.
1021 	 */
1022 	if (!dounpriv & !devnull && (flags & SETFLAGS ||
1023 	    (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) &&
1024 	    fchflags(to_fd,
1025 	    flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
1026 		if (flags & SETFLAGS) {
1027 			if (errno == EOPNOTSUPP)
1028 				warn("%s: chflags", to_name);
1029 			else {
1030 				serrno = errno;
1031 				(void)unlink(to_name);
1032 				errno = serrno;
1033 				err(EX_OSERR, "%s: chflags", to_name);
1034 			}
1035 		}
1036 	}
1037 #endif
1038 
1039 	(void)close(to_fd);
1040 	if (!devnull)
1041 		(void)close(from_fd);
1042 
1043 	metadata_log(to_name, "file", tsb, NULL, digestresult, to_sb.st_size);
1044 	free(digestresult);
1045 }
1046 
1047 /*
1048  * compare --
1049  *	compare two files; non-zero means files differ
1050  */
1051 static int
1052 compare(int from_fd, const char *from_name __unused, size_t from_len,
1053 	int to_fd, const char *to_name __unused, size_t to_len,
1054 	char **dresp)
1055 {
1056 	char *p, *q;
1057 	int rv;
1058 	int done_compare;
1059 	DIGEST_CTX ctx;
1060 
1061 	rv = 0;
1062 	if (from_len != to_len)
1063 		return 1;
1064 
1065 	if (from_len <= MAX_CMP_SIZE) {
1066 		if (dresp != NULL)
1067 			digest_init(&ctx);
1068 		done_compare = 0;
1069 		if (trymmap(from_fd) && trymmap(to_fd)) {
1070 			p = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1071 			    from_fd, (off_t)0);
1072 			if (p == MAP_FAILED)
1073 				goto out;
1074 			q = mmap(NULL, from_len, PROT_READ, MAP_SHARED,
1075 			    to_fd, (off_t)0);
1076 			if (q == MAP_FAILED) {
1077 				munmap(p, from_len);
1078 				goto out;
1079 			}
1080 
1081 			rv = memcmp(p, q, from_len);
1082 			if (dresp != NULL)
1083 				digest_update(&ctx, p, from_len);
1084 			munmap(p, from_len);
1085 			munmap(q, from_len);
1086 			done_compare = 1;
1087 		}
1088 	out:
1089 		if (!done_compare) {
1090 			char buf1[MAXBSIZE];
1091 			char buf2[MAXBSIZE];
1092 			int n1, n2;
1093 
1094 			rv = 0;
1095 			lseek(from_fd, 0, SEEK_SET);
1096 			lseek(to_fd, 0, SEEK_SET);
1097 			while (rv == 0) {
1098 				n1 = read(from_fd, buf1, sizeof(buf1));
1099 				if (n1 == 0)
1100 					break;		/* EOF */
1101 				else if (n1 > 0) {
1102 					n2 = read(to_fd, buf2, n1);
1103 					if (n2 == n1)
1104 						rv = memcmp(buf1, buf2, n1);
1105 					else
1106 						rv = 1;	/* out of sync */
1107 				} else
1108 					rv = 1;		/* read failure */
1109 				digest_update(&ctx, buf1, n1);
1110 			}
1111 			lseek(from_fd, 0, SEEK_SET);
1112 			lseek(to_fd, 0, SEEK_SET);
1113 		}
1114 	} else
1115 		rv = 1;	/* don't bother in this case */
1116 
1117 	if (dresp != NULL) {
1118 		if (rv == 0)
1119 			*dresp = digest_end(&ctx, NULL);
1120 		else
1121 			(void)digest_end(&ctx, NULL);
1122 	}
1123 
1124 	return rv;
1125 }
1126 
1127 /*
1128  * create_tempfile --
1129  *	create a temporary file based on path and open it
1130  */
1131 static int
1132 create_tempfile(const char *path, char *temp, size_t tsize)
1133 {
1134 	char *p;
1135 
1136 	(void)strncpy(temp, path, tsize);
1137 	temp[tsize - 1] = '\0';
1138 	if ((p = strrchr(temp, '/')) != NULL)
1139 		p++;
1140 	else
1141 		p = temp;
1142 	(void)strncpy(p, "INS@XXXX", &temp[tsize - 1] - p);
1143 	temp[tsize - 1] = '\0';
1144 	return (mkstemp(temp));
1145 }
1146 
1147 /*
1148  * create_newfile --
1149  *	create a new file, overwriting an existing one if necessary
1150  */
1151 static int
1152 create_newfile(const char *path, int target, struct stat *sbp)
1153 {
1154 	char backup[MAXPATHLEN];
1155 	int saved_errno = 0;
1156 	int newfd;
1157 
1158 	if (target) {
1159 		/*
1160 		 * Unlink now... avoid ETXTBSY errors later.  Try to turn
1161 		 * off the append/immutable bits -- if we fail, go ahead,
1162 		 * it might work.
1163 		 */
1164 #if HAVE_STRUCT_STAT_ST_FLAGS
1165 		if (sbp->st_flags & NOCHANGEBITS)
1166 			(void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
1167 #endif
1168 
1169 		if (dobackup) {
1170 			if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s",
1171 			    path, suffix) != strlen(path) + strlen(suffix)) {
1172 				saved_errno = errno;
1173 #if HAVE_STRUCT_STAT_ST_FLAGS
1174 				if (sbp->st_flags & NOCHANGEBITS)
1175 					(void)chflags(path, sbp->st_flags);
1176 #endif
1177 				errno = saved_errno;
1178 				errx(EX_OSERR, "%s: backup filename too long",
1179 				    path);
1180 			}
1181 			(void)snprintf(backup, MAXPATHLEN, "%s%s",
1182 			    path, suffix);
1183 			if (verbose)
1184 				(void)printf("install: %s -> %s\n",
1185 				    path, backup);
1186 			if (rename(path, backup) < 0) {
1187 				saved_errno = errno;
1188 #if HAVE_STRUCT_STAT_ST_FLAGS
1189 				if (sbp->st_flags & NOCHANGEBITS)
1190 					(void)chflags(path, sbp->st_flags);
1191 #endif
1192 				errno = saved_errno;
1193 				err(EX_OSERR, "rename: %s to %s", path, backup);
1194 			}
1195 		} else
1196 			if (unlink(path) < 0)
1197 				saved_errno = errno;
1198 	}
1199 
1200 	newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
1201 	if (newfd < 0 && saved_errno != 0)
1202 		errno = saved_errno;
1203 	return newfd;
1204 }
1205 
1206 /*
1207  * copy --
1208  *	copy from one file to another
1209  */
1210 static char *
1211 copy(int from_fd, const char *from_name, int to_fd, const char *to_name,
1212     off_t size)
1213 {
1214 	int nr, nw;
1215 	int serrno;
1216 	char *p;
1217 	char buf[MAXBSIZE];
1218 	int done_copy;
1219 	DIGEST_CTX ctx;
1220 
1221 	/* Rewind file descriptors. */
1222 	if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1223 		err(EX_OSERR, "lseek: %s", from_name);
1224 	if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1225 		err(EX_OSERR, "lseek: %s", to_name);
1226 
1227 	digest_init(&ctx);
1228 
1229 	/*
1230 	 * Mmap and write if less than 8M (the limit is so we don't totally
1231 	 * trash memory on big files.  This is really a minor hack, but it
1232 	 * wins some CPU back.
1233 	 */
1234 	done_copy = 0;
1235 	if (size <= 8 * 1048576 && trymmap(from_fd) &&
1236 	    (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED,
1237 		    from_fd, (off_t)0)) != MAP_FAILED) {
1238 		nw = write(to_fd, p, size);
1239 		if (nw != size) {
1240 			serrno = errno;
1241 			(void)unlink(to_name);
1242 			if (nw >= 0) {
1243 				errx(EX_OSERR,
1244      "short write to %s: %jd bytes written, %jd bytes asked to write",
1245 				    to_name, (uintmax_t)nw, (uintmax_t)size);
1246 			} else {
1247 				errno = serrno;
1248 				err(EX_OSERR, "%s", to_name);
1249 			}
1250 		}
1251 		digest_update(&ctx, p, size);
1252 		(void)munmap(p, size);
1253 		done_copy = 1;
1254 	}
1255 	if (!done_copy) {
1256 		while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
1257 			if ((nw = write(to_fd, buf, nr)) != nr) {
1258 				serrno = errno;
1259 				(void)unlink(to_name);
1260 				if (nw >= 0) {
1261 					errx(EX_OSERR,
1262      "short write to %s: %jd bytes written, %jd bytes asked to write",
1263 					    to_name, (uintmax_t)nw,
1264 					    (uintmax_t)size);
1265 				} else {
1266 					errno = serrno;
1267 					err(EX_OSERR, "%s", to_name);
1268 				}
1269 			}
1270 			digest_update(&ctx, buf, nr);
1271 		}
1272 		if (nr != 0) {
1273 			serrno = errno;
1274 			(void)unlink(to_name);
1275 			errno = serrno;
1276 			err(EX_OSERR, "%s", from_name);
1277 		}
1278 	}
1279 	if (safecopy && fsync(to_fd) == -1) {
1280 		serrno = errno;
1281 		(void)unlink(to_name);
1282 		errno = serrno;
1283 		err(EX_OSERR, "fsync failed for %s", to_name);
1284 	}
1285 	return (digest_end(&ctx, NULL));
1286 }
1287 
1288 /*
1289  * strip --
1290  *	use strip(1) to strip the target file
1291  */
1292 static void
1293 strip(const char *to_name)
1294 {
1295 	const char *stripbin;
1296 	const char *args[3];
1297 	pid_t pid;
1298 	int error, status;
1299 
1300 	stripbin = getenv("STRIPBIN");
1301 	if (stripbin == NULL)
1302 		stripbin = "strip";
1303 	args[0] = stripbin;
1304 	args[1] = to_name;
1305 	args[2] = NULL;
1306 	error = posix_spawnp(&pid, stripbin, NULL, NULL,
1307 	    __DECONST(char **, args), environ);
1308 	if (error != 0) {
1309 		(void)unlink(to_name);
1310 		errc(error == EAGAIN || error == EPROCLIM || error == ENOMEM ?
1311 		    EX_TEMPFAIL : EX_OSERR, error, "spawn %s", stripbin);
1312 	}
1313 	if (waitpid(pid, &status, 0) == -1) {
1314 		error = errno;
1315 		(void)unlink(to_name);
1316 		errc(EX_SOFTWARE, error, "wait");
1317 		/* NOTREACHED */
1318 	}
1319 	if (status != 0) {
1320 		(void)unlink(to_name);
1321 		errx(EX_SOFTWARE, "strip command %s failed on %s",
1322 		    stripbin, to_name);
1323 	}
1324 }
1325 
1326 /*
1327  * install_dir --
1328  *	build directory hierarchy
1329  */
1330 static void
1331 install_dir(char *path)
1332 {
1333 	char *p;
1334 	struct stat sb;
1335 	int ch, tried_mkdir;
1336 
1337 	for (p = path;; ++p)
1338 		if (!*p || (p != path && *p  == '/')) {
1339 			tried_mkdir = 0;
1340 			ch = *p;
1341 			*p = '\0';
1342 again:
1343 			if (stat(path, &sb) < 0) {
1344 				if (errno != ENOENT || tried_mkdir)
1345 					err(EX_OSERR, "stat %s", path);
1346 				if (mkdir(path, 0755) < 0) {
1347 					tried_mkdir = 1;
1348 					if (errno == EEXIST)
1349 						goto again;
1350 					err(EX_OSERR, "mkdir %s", path);
1351 				}
1352 				if (verbose)
1353 					(void)printf("install: mkdir %s\n",
1354 					    path);
1355 			} else if (!S_ISDIR(sb.st_mode))
1356 				errx(EX_OSERR, "%s exists but is not a directory", path);
1357 			if (!(*p = ch))
1358 				break;
1359  		}
1360 
1361 	if (!dounpriv) {
1362 		if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
1363 		    chown(path, uid, gid))
1364 			warn("chown %u:%u %s", uid, gid, path);
1365 		/* XXXBED: should we do the chmod in the dounpriv case? */
1366 		if (chmod(path, mode))
1367 			warn("chmod %o %s", mode, path);
1368 	}
1369 	metadata_log(path, "dir", NULL, NULL, NULL, 0);
1370 }
1371 
1372 /*
1373  * metadata_log --
1374  *	if metafp is not NULL, output mtree(8) full path name and settings to
1375  *	metafp, to allow permissions to be set correctly by other tools,
1376  *	or to allow integrity checks to be performed.
1377  */
1378 static void
1379 metadata_log(const char *path, const char *type, struct timespec *ts,
1380 	const char *slink, const char *digestresult, off_t size)
1381 {
1382 	static const char extra[] = { ' ', '\t', '\n', '\\', '#', '\0' };
1383 	const char *p;
1384 	char *buf;
1385 	size_t destlen;
1386 	struct flock metalog_lock;
1387 
1388 	if (!metafp)
1389 		return;
1390 	/* Buffer for strsvis(3). */
1391 	buf = (char *)malloc(4 * strlen(path) + 1);
1392 	if (buf == NULL) {
1393 		warnx("%s", strerror(ENOMEM));
1394 		return;
1395 	}
1396 
1397 	/* Lock log file. */
1398 	metalog_lock.l_start = 0;
1399 	metalog_lock.l_len = 0;
1400 	metalog_lock.l_whence = SEEK_SET;
1401 	metalog_lock.l_type = F_WRLCK;
1402 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1) {
1403 		warn("can't lock %s", metafile);
1404 		free(buf);
1405 		return;
1406 	}
1407 
1408 	/* Remove destdir. */
1409 	p = path;
1410 	if (destdir) {
1411 		destlen = strlen(destdir);
1412 		if (strncmp(p, destdir, destlen) == 0 &&
1413 		    (p[destlen] == '/' || p[destlen] == '\0'))
1414 			p += destlen;
1415 	}
1416 	while (*p && *p == '/')
1417 		p++;
1418 	strsvis(buf, p, VIS_OCTAL, extra);
1419 	p = buf;
1420 	/* Print details. */
1421 	fprintf(metafp, ".%s%s type=%s", *p ? "/" : "", p, type);
1422 	if (owner)
1423 		fprintf(metafp, " uname=%s", owner);
1424 	if (group)
1425 		fprintf(metafp, " gname=%s", group);
1426 	fprintf(metafp, " mode=%#o", mode);
1427 	if (slink) {
1428 		strsvis(buf, slink, VIS_CSTYLE, extra);	/* encode link */
1429 		fprintf(metafp, " link=%s", buf);
1430 	}
1431 	if (*type == 'f') /* type=file */
1432 		fprintf(metafp, " size=%lld", (long long)size);
1433 	if (ts != NULL && dopreserve)
1434 		fprintf(metafp, " time=%lld.%09ld",
1435 			(long long)ts[1].tv_sec, ts[1].tv_nsec);
1436 	if (digestresult && digest)
1437 		fprintf(metafp, " %s=%s", digest, digestresult);
1438 	if (fflags)
1439 		fprintf(metafp, " flags=%s", fflags);
1440 	if (tags)
1441 		fprintf(metafp, " tags=%s", tags);
1442 	fputc('\n', metafp);
1443 	/* Flush line. */
1444 	fflush(metafp);
1445 
1446 	/* Unlock log file. */
1447 	metalog_lock.l_type = F_UNLCK;
1448 	if (fcntl(fileno(metafp), F_SETLKW, &metalog_lock) == -1)
1449 		warn("can't unlock %s", metafile);
1450 	free(buf);
1451 }
1452 
1453 /*
1454  * usage --
1455  *	print a usage message and die
1456  */
1457 static void
1458 usage(void)
1459 {
1460 	(void)fprintf(stderr,
1461 "usage: install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1462 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1463 "               [-B suffix] [-l linkflags] [-N dbdir]\n"
1464 "               file1 file2\n"
1465 "       install [-bCcpSsUv] [-f flags] [-g group] [-m mode] [-o owner]\n"
1466 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1467 "               [-B suffix] [-l linkflags] [-N dbdir]\n"
1468 "               file1 ... fileN directory\n"
1469 "       install -dU [-vU] [-g group] [-m mode] [-N dbdir] [-o owner]\n"
1470 "               [-M log] [-D dest] [-h hash] [-T tags]\n"
1471 "               directory ...\n");
1472 	exit(EX_USAGE);
1473 	/* NOTREACHED */
1474 }
1475 
1476 /*
1477  * trymmap --
1478  *	return true (1) if mmap should be tried, false (0) if not.
1479  */
1480 static int
1481 trymmap(int fd)
1482 {
1483 /*
1484  * The ifdef is for bootstrapping - f_fstypename doesn't exist in
1485  * pre-Lite2-merge systems.
1486  */
1487 #ifdef MFSNAMELEN
1488 	struct statfs stfs;
1489 
1490 	if (fstatfs(fd, &stfs) != 0)
1491 		return (0);
1492 	if (strcmp(stfs.f_fstypename, "ufs") == 0 ||
1493 	    strcmp(stfs.f_fstypename, "cd9660") == 0)
1494 		return (1);
1495 #endif
1496 	return (0);
1497 }
1498