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