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