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