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