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