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