xref: /freebsd/usr.bin/xinstall/xinstall.c (revision aa64588d28258aef88cc33b8043112e8856948d0)
1 /*
2  * Copyright (c) 1987, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1987, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)xinstall.c	8.1 (Berkeley) 7/21/93";
43 #endif /* not lint */
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/mman.h>
51 #include <sys/mount.h>
52 #include <sys/stat.h>
53 #include <sys/time.h>
54 #include <sys/wait.h>
55 
56 #include <err.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <grp.h>
60 #include <paths.h>
61 #include <pwd.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <sysexits.h>
66 #include <unistd.h>
67 
68 /* Bootstrap aid - this doesn't exist in most older releases */
69 #ifndef MAP_FAILED
70 #define MAP_FAILED ((void *)-1)	/* from <sys/mman.h> */
71 #endif
72 
73 #define MAX_CMP_SIZE	(16 * 1024 * 1024)
74 
75 #define	DIRECTORY	0x01		/* Tell install it's a directory. */
76 #define	SETFLAGS	0x02		/* Tell install to set flags. */
77 #define	NOCHANGEBITS	(UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
78 #define	BACKUP_SUFFIX	".old"
79 
80 struct passwd *pp;
81 struct group *gp;
82 gid_t gid;
83 uid_t uid;
84 int dobackup, docompare, dodir, dopreserve, dostrip, nommap, safecopy, verbose;
85 mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
86 const char *suffix = BACKUP_SUFFIX;
87 
88 static int	compare(int, const char *, size_t, int, const char *, size_t);
89 static void	copy(int, const char *, int, const char *, off_t);
90 static int	create_newfile(const char *, int, struct stat *);
91 static int	create_tempfile(const char *, char *, size_t);
92 static void	install(const char *, const char *, u_long, u_int);
93 static void	install_dir(char *);
94 static u_long	numeric_id(const char *, const char *);
95 static void	strip(const char *);
96 static int	trymmap(int);
97 static void	usage(void);
98 
99 int
100 main(int argc, char *argv[])
101 {
102 	struct stat from_sb, to_sb;
103 	mode_t *set;
104 	u_long fset;
105 	int ch, no_target;
106 	u_int iflags;
107 	char *flags;
108 	const char *group, *owner, *to_name;
109 
110 	iflags = 0;
111 	group = owner = NULL;
112 	while ((ch = getopt(argc, argv, "B:bCcdf:g:Mm:o:pSsv")) != -1)
113 		switch((char)ch) {
114 		case 'B':
115 			suffix = optarg;
116 			/* FALLTHROUGH */
117 		case 'b':
118 			dobackup = 1;
119 			break;
120 		case 'C':
121 			docompare = 1;
122 			break;
123 		case 'c':
124 			/* For backwards compatibility. */
125 			break;
126 		case 'd':
127 			dodir = 1;
128 			break;
129 		case 'f':
130 			flags = optarg;
131 			if (strtofflags(&flags, &fset, NULL))
132 				errx(EX_USAGE, "%s: invalid flag", flags);
133 			iflags |= SETFLAGS;
134 			break;
135 		case 'g':
136 			group = optarg;
137 			break;
138 		case 'M':
139 			nommap = 1;
140 			break;
141 		case 'm':
142 			if (!(set = setmode(optarg)))
143 				errx(EX_USAGE, "invalid file mode: %s",
144 				     optarg);
145 			mode = getmode(set, 0);
146 			free(set);
147 			break;
148 		case 'o':
149 			owner = optarg;
150 			break;
151 		case 'p':
152 			docompare = dopreserve = 1;
153 			break;
154 		case 'S':
155 			safecopy = 1;
156 			break;
157 		case 's':
158 			dostrip = 1;
159 			break;
160 		case 'v':
161 			verbose = 1;
162 			break;
163 		case '?':
164 		default:
165 			usage();
166 		}
167 	argc -= optind;
168 	argv += optind;
169 
170 	/* some options make no sense when creating directories */
171 	if (dostrip && dodir) {
172 		warnx("-d and -s may not be specified together");
173 		usage();
174 	}
175 
176 	if (getenv("DONTSTRIP") != NULL) {
177 		warnx("DONTSTRIP set - will not strip installed binaries");
178 		dostrip = 0;
179 	}
180 
181 	/* must have at least two arguments, except when creating directories */
182 	if (argc == 0 || (argc == 1 && !dodir))
183 		usage();
184 
185 	/* need to make a temp copy so we can compare stripped version */
186 	if (docompare && dostrip)
187 		safecopy = 1;
188 
189 	/* get group and owner id's */
190 	if (group != NULL) {
191 		if ((gp = getgrnam(group)) != NULL)
192 			gid = gp->gr_gid;
193 		else
194 			gid = (gid_t)numeric_id(group, "group");
195 	} else
196 		gid = (gid_t)-1;
197 
198 	if (owner != NULL) {
199 		if ((pp = getpwnam(owner)) != NULL)
200 			uid = pp->pw_uid;
201 		else
202 			uid = (uid_t)numeric_id(owner, "user");
203 	} else
204 		uid = (uid_t)-1;
205 
206 	if (dodir) {
207 		for (; *argv != NULL; ++argv)
208 			install_dir(*argv);
209 		exit(EX_OK);
210 		/* NOTREACHED */
211 	}
212 
213 	no_target = stat(to_name = argv[argc - 1], &to_sb);
214 	if (!no_target && S_ISDIR(to_sb.st_mode)) {
215 		for (; *argv != to_name; ++argv)
216 			install(*argv, to_name, fset, iflags | DIRECTORY);
217 		exit(EX_OK);
218 		/* NOTREACHED */
219 	}
220 
221 	/* can't do file1 file2 directory/file */
222 	if (argc != 2) {
223 		if (no_target)
224 			warnx("target directory `%s' does not exist",
225 			    argv[argc - 1]);
226 		else
227 			warnx("target `%s' is not a directory",
228 			    argv[argc - 1]);
229 		usage();
230 	}
231 
232 	if (!no_target) {
233 		if (stat(*argv, &from_sb))
234 			err(EX_OSERR, "%s", *argv);
235 		if (!S_ISREG(to_sb.st_mode)) {
236 			errno = EFTYPE;
237 			err(EX_OSERR, "%s", to_name);
238 		}
239 		if (to_sb.st_dev == from_sb.st_dev &&
240 		    to_sb.st_ino == from_sb.st_ino)
241 			errx(EX_USAGE,
242 			    "%s and %s are the same file", *argv, to_name);
243 	}
244 	install(*argv, to_name, fset, iflags);
245 	exit(EX_OK);
246 	/* NOTREACHED */
247 }
248 
249 static u_long
250 numeric_id(const char *name, const char *type)
251 {
252 	u_long val;
253 	char *ep;
254 
255 	/*
256 	 * XXX
257 	 * We know that uid_t's and gid_t's are unsigned longs.
258 	 */
259 	errno = 0;
260 	val = strtoul(name, &ep, 10);
261 	if (errno)
262 		err(EX_NOUSER, "%s", name);
263 	if (*ep != '\0')
264 		errx(EX_NOUSER, "unknown %s %s", type, name);
265 	return (val);
266 }
267 
268 /*
269  * install --
270  *	build a path name and install the file
271  */
272 static void
273 install(const char *from_name, const char *to_name, u_long fset, u_int flags)
274 {
275 	struct stat from_sb, temp_sb, to_sb;
276 	struct timeval tvb[2];
277 	int devnull, files_match, from_fd, serrno, target;
278 	int tempcopy, temp_fd, to_fd;
279 	char backup[MAXPATHLEN], *p, pathbuf[MAXPATHLEN], tempfile[MAXPATHLEN];
280 
281 	files_match = 0;
282 	from_fd = -1;
283 	to_fd = -1;
284 
285 	/* If try to install NULL file to a directory, fails. */
286 	if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
287 		if (stat(from_name, &from_sb))
288 			err(EX_OSERR, "%s", from_name);
289 		if (!S_ISREG(from_sb.st_mode)) {
290 			errno = EFTYPE;
291 			err(EX_OSERR, "%s", from_name);
292 		}
293 		/* Build the target path. */
294 		if (flags & DIRECTORY) {
295 			(void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
296 			    to_name,
297 			    (p = strrchr(from_name, '/')) ? ++p : from_name);
298 			to_name = pathbuf;
299 		}
300 		devnull = 0;
301 	} else {
302 		devnull = 1;
303 	}
304 
305 	target = stat(to_name, &to_sb) == 0;
306 
307 	/* Only install to regular files. */
308 	if (target && !S_ISREG(to_sb.st_mode)) {
309 		errno = EFTYPE;
310 		warn("%s", to_name);
311 		return;
312 	}
313 
314 	/* Only copy safe if the target exists. */
315 	tempcopy = safecopy && target;
316 
317 	if (!devnull && (from_fd = open(from_name, O_RDONLY, 0)) < 0)
318 		err(EX_OSERR, "%s", from_name);
319 
320 	/* If we don't strip, we can compare first. */
321 	if (docompare && !dostrip && target) {
322 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
323 			err(EX_OSERR, "%s", to_name);
324 		if (devnull)
325 			files_match = to_sb.st_size == 0;
326 		else
327 			files_match = !(compare(from_fd, from_name,
328 			    (size_t)from_sb.st_size, to_fd,
329 			    to_name, (size_t)to_sb.st_size));
330 
331 		/* Close "to" file unless we match. */
332 		if (!files_match)
333 			(void)close(to_fd);
334 	}
335 
336 	if (!files_match) {
337 		if (tempcopy) {
338 			to_fd = create_tempfile(to_name, tempfile,
339 			    sizeof(tempfile));
340 			if (to_fd < 0)
341 				err(EX_OSERR, "%s", tempfile);
342 		} else {
343 			if ((to_fd = create_newfile(to_name, target,
344 			    &to_sb)) < 0)
345 				err(EX_OSERR, "%s", to_name);
346 			if (verbose)
347 				(void)printf("install: %s -> %s\n",
348 				    from_name, to_name);
349 		}
350 		if (!devnull)
351 			copy(from_fd, from_name, to_fd,
352 			     tempcopy ? tempfile : to_name, from_sb.st_size);
353 	}
354 
355 	if (dostrip) {
356 		strip(tempcopy ? tempfile : to_name);
357 
358 		/*
359 		 * Re-open our fd on the target, in case we used a strip
360 		 * that does not work in-place -- like GNU binutils strip.
361 		 */
362 		close(to_fd);
363 		to_fd = open(tempcopy ? tempfile : to_name, O_RDONLY, 0);
364 		if (to_fd < 0)
365 			err(EX_OSERR, "stripping %s", to_name);
366 	}
367 
368 	/*
369 	 * Compare the stripped temp file with the target.
370 	 */
371 	if (docompare && dostrip && target) {
372 		temp_fd = to_fd;
373 
374 		/* Re-open to_fd using the real target name. */
375 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
376 			err(EX_OSERR, "%s", to_name);
377 
378 		if (fstat(temp_fd, &temp_sb)) {
379 			serrno = errno;
380 			(void)unlink(tempfile);
381 			errno = serrno;
382 			err(EX_OSERR, "%s", tempfile);
383 		}
384 
385 		if (compare(temp_fd, tempfile, (size_t)temp_sb.st_size, to_fd,
386 			    to_name, (size_t)to_sb.st_size) == 0) {
387 			/*
388 			 * If target has more than one link we need to
389 			 * replace it in order to snap the extra links.
390 			 * Need to preserve target file times, though.
391 			 */
392 			if (to_sb.st_nlink != 1) {
393 				tvb[0].tv_sec = to_sb.st_atime;
394 				tvb[0].tv_usec = 0;
395 				tvb[1].tv_sec = to_sb.st_mtime;
396 				tvb[1].tv_usec = 0;
397 				(void)utimes(tempfile, tvb);
398 			} else {
399 				files_match = 1;
400 				(void)unlink(tempfile);
401 			}
402 			(void) close(temp_fd);
403 		}
404 	}
405 
406 	/*
407 	 * Move the new file into place if doing a safe copy
408 	 * and the files are different (or just not compared).
409 	 */
410 	if (tempcopy && !files_match) {
411 		/* Try to turn off the immutable bits. */
412 		if (to_sb.st_flags & NOCHANGEBITS)
413 			(void)chflags(to_name, to_sb.st_flags & ~NOCHANGEBITS);
414 		if (dobackup) {
415 			if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s", to_name,
416 			    suffix) != strlen(to_name) + strlen(suffix)) {
417 				unlink(tempfile);
418 				errx(EX_OSERR, "%s: backup filename too long",
419 				    to_name);
420 			}
421 			if (verbose)
422 				(void)printf("install: %s -> %s\n", to_name, backup);
423 			if (rename(to_name, backup) < 0) {
424 				serrno = errno;
425 				unlink(tempfile);
426 				errno = serrno;
427 				err(EX_OSERR, "rename: %s to %s", to_name,
428 				     backup);
429 			}
430 		}
431 		if (verbose)
432 			(void)printf("install: %s -> %s\n", from_name, to_name);
433 		if (rename(tempfile, to_name) < 0) {
434 			serrno = errno;
435 			unlink(tempfile);
436 			errno = serrno;
437 			err(EX_OSERR, "rename: %s to %s",
438 			    tempfile, to_name);
439 		}
440 
441 		/* Re-open to_fd so we aren't hosed by the rename(2). */
442 		(void) close(to_fd);
443 		if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
444 			err(EX_OSERR, "%s", to_name);
445 	}
446 
447 	/*
448 	 * Preserve the timestamp of the source file if necessary.
449 	 */
450 	if (dopreserve && !files_match && !devnull) {
451 		tvb[0].tv_sec = from_sb.st_atime;
452 		tvb[0].tv_usec = 0;
453 		tvb[1].tv_sec = from_sb.st_mtime;
454 		tvb[1].tv_usec = 0;
455 		(void)utimes(to_name, tvb);
456 	}
457 
458 	if (fstat(to_fd, &to_sb) == -1) {
459 		serrno = errno;
460 		(void)unlink(to_name);
461 		errno = serrno;
462 		err(EX_OSERR, "%s", to_name);
463 	}
464 
465 	/*
466 	 * Set owner, group, mode for target; do the chown first,
467 	 * chown may lose the setuid bits.
468 	 */
469 	if ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
470 	    (uid != (uid_t)-1 && uid != to_sb.st_uid) ||
471 	    (mode != (to_sb.st_mode & ALLPERMS))) {
472 		/* Try to turn off the immutable bits. */
473 		if (to_sb.st_flags & NOCHANGEBITS)
474 			(void)fchflags(to_fd, to_sb.st_flags & ~NOCHANGEBITS);
475 	}
476 
477 	if ((gid != (gid_t)-1 && gid != to_sb.st_gid) ||
478 	    (uid != (uid_t)-1 && uid != to_sb.st_uid))
479 		if (fchown(to_fd, uid, gid) == -1) {
480 			serrno = errno;
481 			(void)unlink(to_name);
482 			errno = serrno;
483 			err(EX_OSERR,"%s: chown/chgrp", to_name);
484 		}
485 
486 	if (mode != (to_sb.st_mode & ALLPERMS))
487 		if (fchmod(to_fd, mode)) {
488 			serrno = errno;
489 			(void)unlink(to_name);
490 			errno = serrno;
491 			err(EX_OSERR, "%s: chmod", to_name);
492 		}
493 
494 	/*
495 	 * If provided a set of flags, set them, otherwise, preserve the
496 	 * flags, except for the dump flag.
497 	 * NFS does not support flags.  Ignore EOPNOTSUPP flags if we're just
498 	 * trying to turn off UF_NODUMP.  If we're trying to set real flags,
499 	 * then warn if the the fs doesn't support it, otherwise fail.
500 	 */
501 	if (!devnull && (flags & SETFLAGS ||
502 	    (from_sb.st_flags & ~UF_NODUMP) != to_sb.st_flags) &&
503 	    fchflags(to_fd,
504 	    flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
505 		if (flags & SETFLAGS) {
506 			if (errno == EOPNOTSUPP)
507 				warn("%s: chflags", to_name);
508 			else {
509 				serrno = errno;
510 				(void)unlink(to_name);
511 				errno = serrno;
512 				err(EX_OSERR, "%s: chflags", to_name);
513 			}
514 		}
515 	}
516 
517 	(void)close(to_fd);
518 	if (!devnull)
519 		(void)close(from_fd);
520 }
521 
522 /*
523  * compare --
524  *	compare two files; non-zero means files differ
525  */
526 static int
527 compare(int from_fd, const char *from_name __unused, size_t from_len,
528 	int to_fd, const char *to_name __unused, size_t to_len)
529 {
530 	char *p, *q;
531 	int rv;
532 	int done_compare;
533 
534 	rv = 0;
535 	if (from_len != to_len)
536 		return 1;
537 
538 	if (from_len <= MAX_CMP_SIZE) {
539 		done_compare = 0;
540 		if (trymmap(from_fd) && trymmap(to_fd)) {
541 			p = mmap(NULL, from_len, PROT_READ, MAP_SHARED, from_fd, (off_t)0);
542 			if (p == (char *)MAP_FAILED)
543 				goto out;
544 			q = mmap(NULL, from_len, PROT_READ, MAP_SHARED, to_fd, (off_t)0);
545 			if (q == (char *)MAP_FAILED) {
546 				munmap(p, from_len);
547 				goto out;
548 			}
549 
550 			rv = memcmp(p, q, from_len);
551 			munmap(p, from_len);
552 			munmap(q, from_len);
553 			done_compare = 1;
554 		}
555 	out:
556 		if (!done_compare) {
557 			char buf1[MAXBSIZE];
558 			char buf2[MAXBSIZE];
559 			int n1, n2;
560 
561 			rv = 0;
562 			lseek(from_fd, 0, SEEK_SET);
563 			lseek(to_fd, 0, SEEK_SET);
564 			while (rv == 0) {
565 				n1 = read(from_fd, buf1, sizeof(buf1));
566 				if (n1 == 0)
567 					break;		/* EOF */
568 				else if (n1 > 0) {
569 					n2 = read(to_fd, buf2, n1);
570 					if (n2 == n1)
571 						rv = memcmp(buf1, buf2, n1);
572 					else
573 						rv = 1;	/* out of sync */
574 				} else
575 					rv = 1;		/* read failure */
576 			}
577 			lseek(from_fd, 0, SEEK_SET);
578 			lseek(to_fd, 0, SEEK_SET);
579 		}
580 	} else
581 		rv = 1;	/* don't bother in this case */
582 
583 	return rv;
584 }
585 
586 /*
587  * create_tempfile --
588  *	create a temporary file based on path and open it
589  */
590 static int
591 create_tempfile(const char *path, char *temp, size_t tsize)
592 {
593 	char *p;
594 
595 	(void)strncpy(temp, path, tsize);
596 	temp[tsize - 1] = '\0';
597 	if ((p = strrchr(temp, '/')) != NULL)
598 		p++;
599 	else
600 		p = temp;
601 	(void)strncpy(p, "INS@XXXX", &temp[tsize - 1] - p);
602 	temp[tsize - 1] = '\0';
603 	return (mkstemp(temp));
604 }
605 
606 /*
607  * create_newfile --
608  *	create a new file, overwriting an existing one if necessary
609  */
610 static int
611 create_newfile(const char *path, int target, struct stat *sbp)
612 {
613 	char backup[MAXPATHLEN];
614 	int saved_errno = 0;
615 	int newfd;
616 
617 	if (target) {
618 		/*
619 		 * Unlink now... avoid ETXTBSY errors later.  Try to turn
620 		 * off the append/immutable bits -- if we fail, go ahead,
621 		 * it might work.
622 		 */
623 		if (sbp->st_flags & NOCHANGEBITS)
624 			(void)chflags(path, sbp->st_flags & ~NOCHANGEBITS);
625 
626 		if (dobackup) {
627 			if ((size_t)snprintf(backup, MAXPATHLEN, "%s%s",
628 			    path, suffix) != strlen(path) + strlen(suffix))
629 				errx(EX_OSERR, "%s: backup filename too long",
630 				    path);
631 			(void)snprintf(backup, MAXPATHLEN, "%s%s",
632 			    path, suffix);
633 			if (verbose)
634 				(void)printf("install: %s -> %s\n",
635 				    path, backup);
636 			if (rename(path, backup) < 0)
637 				err(EX_OSERR, "rename: %s to %s", path, backup);
638 		} else
639 			if (unlink(path) < 0)
640 				saved_errno = errno;
641 	}
642 
643 	newfd = open(path, O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
644 	if (newfd < 0 && saved_errno != 0)
645 		errno = saved_errno;
646 	return newfd;
647 }
648 
649 /*
650  * copy --
651  *	copy from one file to another
652  */
653 static void
654 copy(int from_fd, const char *from_name, int to_fd, const char *to_name,
655     off_t size)
656 {
657 	int nr, nw;
658 	int serrno;
659 	char *p, buf[MAXBSIZE];
660 	int done_copy;
661 
662 	/* Rewind file descriptors. */
663 	if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
664 		err(EX_OSERR, "lseek: %s", from_name);
665 	if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
666 		err(EX_OSERR, "lseek: %s", to_name);
667 
668 	/*
669 	 * Mmap and write if less than 8M (the limit is so we don't totally
670 	 * trash memory on big files.  This is really a minor hack, but it
671 	 * wins some CPU back.
672 	 */
673 	done_copy = 0;
674 	if (size <= 8 * 1048576 && trymmap(from_fd) &&
675 	    (p = mmap(NULL, (size_t)size, PROT_READ, MAP_SHARED,
676 		    from_fd, (off_t)0)) != (char *)MAP_FAILED) {
677 		if ((nw = write(to_fd, p, size)) != size) {
678 			serrno = errno;
679 			(void)unlink(to_name);
680 			errno = nw > 0 ? EIO : serrno;
681 			err(EX_OSERR, "%s", to_name);
682 		}
683 		done_copy = 1;
684 	}
685 	if (!done_copy) {
686 		while ((nr = read(from_fd, buf, sizeof(buf))) > 0)
687 			if ((nw = write(to_fd, buf, nr)) != nr) {
688 				serrno = errno;
689 				(void)unlink(to_name);
690 				errno = nw > 0 ? EIO : serrno;
691 				err(EX_OSERR, "%s", to_name);
692 			}
693 		if (nr != 0) {
694 			serrno = errno;
695 			(void)unlink(to_name);
696 			errno = serrno;
697 			err(EX_OSERR, "%s", from_name);
698 		}
699 	}
700 }
701 
702 /*
703  * strip --
704  *	use strip(1) to strip the target file
705  */
706 static void
707 strip(const char *to_name)
708 {
709 	const char *stripbin;
710 	int serrno, status;
711 
712 	switch (fork()) {
713 	case -1:
714 		serrno = errno;
715 		(void)unlink(to_name);
716 		errno = serrno;
717 		err(EX_TEMPFAIL, "fork");
718 	case 0:
719 		stripbin = getenv("STRIPBIN");
720 		if (stripbin == NULL)
721 			stripbin = "strip";
722 		execlp(stripbin, stripbin, to_name, (char *)NULL);
723 		err(EX_OSERR, "exec(%s)", stripbin);
724 	default:
725 		if (wait(&status) == -1 || status) {
726 			serrno = errno;
727 			(void)unlink(to_name);
728 			errc(EX_SOFTWARE, serrno, "wait");
729 			/* NOTREACHED */
730 		}
731 	}
732 }
733 
734 /*
735  * install_dir --
736  *	build directory hierarchy
737  */
738 static void
739 install_dir(char *path)
740 {
741 	char *p;
742 	struct stat sb;
743 	int ch;
744 
745 	for (p = path;; ++p)
746 		if (!*p || (p != path && *p  == '/')) {
747 			ch = *p;
748 			*p = '\0';
749 			if (stat(path, &sb)) {
750 				if (errno != ENOENT || mkdir(path, 0755) < 0) {
751 					err(EX_OSERR, "mkdir %s", path);
752 					/* NOTREACHED */
753 				} else if (verbose)
754 					(void)printf("install: mkdir %s\n",
755 						     path);
756 			} else if (!S_ISDIR(sb.st_mode))
757 				errx(EX_OSERR, "%s exists but is not a directory", path);
758 			if (!(*p = ch))
759 				break;
760  		}
761 
762 	if ((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid))
763 		warn("chown %u:%u %s", uid, gid, path);
764 	if (chmod(path, mode))
765 		warn("chmod %o %s", mode, path);
766 }
767 
768 /*
769  * usage --
770  *	print a usage message and die
771  */
772 static void
773 usage(void)
774 {
775 	(void)fprintf(stderr,
776 "usage: install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]\n"
777 "               [-o owner] file1 file2\n"
778 "       install [-bCcpSsv] [-B suffix] [-f flags] [-g group] [-m mode]\n"
779 "               [-o owner] file1 ... fileN directory\n"
780 "       install -d [-v] [-g group] [-m mode] [-o owner] directory ...\n");
781 	exit(EX_USAGE);
782 	/* NOTREACHED */
783 }
784 
785 /*
786  * trymmap --
787  *	return true (1) if mmap should be tried, false (0) if not.
788  */
789 static int
790 trymmap(int fd)
791 {
792 /*
793  * The ifdef is for bootstrapping - f_fstypename doesn't exist in
794  * pre-Lite2-merge systems.
795  */
796 #ifdef MFSNAMELEN
797 	struct statfs stfs;
798 
799 	if (nommap || fstatfs(fd, &stfs) != 0)
800 		return (0);
801 	if (strcmp(stfs.f_fstypename, "ufs") == 0 ||
802 	    strcmp(stfs.f_fstypename, "cd9660") == 0)
803 		return (1);
804 #endif
805 	return (0);
806 }
807