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