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