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