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