[BACK]Return to xinstall.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / xinstall

Annotation of src/usr.bin/xinstall/xinstall.c, Revision 1.63

1.63    ! millert     1: /*     $OpenBSD: xinstall.c,v 1.62 2015/07/19 18:27:26 jasper Exp $    */
1.2       deraadt     2: /*     $NetBSD: xinstall.c,v 1.9 1995/12/20 10:25:17 jonathan Exp $    */
1.1       deraadt     3:
                      4: /*
                      5:  * Copyright (c) 1987, 1993
                      6:  *     The Regents of the University of California.  All rights reserved.
                      7:  *
                      8:  * Redistribution and use in source and binary forms, with or without
                      9:  * modification, are permitted provided that the following conditions
                     10:  * are met:
                     11:  * 1. Redistributions of source code must retain the above copyright
                     12:  *    notice, this list of conditions and the following disclaimer.
                     13:  * 2. Redistributions in binary form must reproduce the above copyright
                     14:  *    notice, this list of conditions and the following disclaimer in the
                     15:  *    documentation and/or other materials provided with the distribution.
1.34      millert    16:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    17:  *    may be used to endorse or promote products derived from this software
                     18:  *    without specific prior written permission.
                     19:  *
                     20:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     21:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     22:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     23:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     24:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     25:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     26:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     27:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     28:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     29:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     30:  * SUCH DAMAGE.
                     31:  */
                     32:
1.58      deraadt    33: #include <sys/param.h> /* MAXBSIZE */
1.1       deraadt    34: #include <sys/wait.h>
                     35: #include <sys/mman.h>
                     36: #include <sys/stat.h>
                     37:
                     38: #include <ctype.h>
1.4       millert    39: #include <err.h>
1.1       deraadt    40: #include <errno.h>
                     41: #include <fcntl.h>
                     42: #include <grp.h>
                     43: #include <paths.h>
                     44: #include <pwd.h>
                     45: #include <stdio.h>
                     46: #include <stdlib.h>
                     47: #include <string.h>
                     48: #include <unistd.h>
1.58      deraadt    49: #include <limits.h>
1.4       millert    50: #include <utime.h>
1.60      jasper     51: #include <libgen.h>
1.1       deraadt    52:
                     53: #include "pathnames.h"
                     54:
1.58      deraadt    55: #define MINIMUM(a, b)  (((a) < (b)) ? (a) : (b))
                     56:
1.19      millert    57: #define        DIRECTORY       0x01            /* Tell install it's a directory. */
                     58: #define        SETFLAGS        0x02            /* Tell install to set flags. */
                     59: #define NOCHANGEBITS   (UF_IMMUTABLE | UF_APPEND | SF_IMMUTABLE | SF_APPEND)
                     60: #define BACKUP_SUFFIX  ".old"
                     61:
1.1       deraadt    62: struct passwd *pp;
                     63: struct group *gp;
1.60      jasper     64: int dobackup, docompare, dodest, dodir, dopreserve, dostrip, safecopy;
1.1       deraadt    65: int mode = S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH;
1.58      deraadt    66: char pathbuf[PATH_MAX], tempfile[PATH_MAX];
1.19      millert    67: char *suffix = BACKUP_SUFFIX;
1.1       deraadt    68: uid_t uid;
                     69: gid_t gid;
                     70:
1.31      millert    71: void   copy(int, char *, int, char *, off_t, int);
1.59      guenther   72: int    compare(int, const char *, off_t, int, const char *, off_t);
1.31      millert    73: void   install(char *, char *, u_long, u_int);
1.62      jasper     74: void   install_dir(char *, int);
1.31      millert    75: void   strip(char *);
                     76: void   usage(void);
                     77: int    create_newfile(char *, struct stat *);
                     78: int    create_tempfile(char *, char *, size_t);
                     79: int    file_write(int, char *, size_t, int *, int *, int);
1.33      tedu       80: void   file_flush(int, int);
1.1       deraadt    81:
                     82: int
1.35      deraadt    83: main(int argc, char *argv[])
1.1       deraadt    84: {
                     85:        struct stat from_sb, to_sb;
1.41      otto       86:        void *set;
1.23      mickey     87:        u_int32_t fset;
1.1       deraadt    88:        u_int iflags;
                     89:        int ch, no_target;
                     90:        char *flags, *to_name, *group = NULL, *owner = NULL;
                     91:
                     92:        iflags = 0;
1.60      jasper     93:        while ((ch = getopt(argc, argv, "B:bCcDdf:g:m:o:pSs")) != -1)
1.56      okan       94:                switch(ch) {
1.4       millert    95:                case 'C':
                     96:                        docompare = 1;
                     97:                        break;
1.19      millert    98:                case 'B':
                     99:                        suffix = optarg;
                    100:                        /* fall through; -B implies -b */
                    101:                case 'b':
                    102:                        dobackup = 1;
                    103:                        break;
1.1       deraadt   104:                case 'c':
1.4       millert   105:                        /* For backwards compatibility. */
1.1       deraadt   106:                        break;
                    107:                case 'f':
                    108:                        flags = optarg;
1.23      mickey    109:                        if (strtofflags(&flags, &fset, NULL))
1.63    ! millert   110:                                errx(1, "%s: invalid flag", flags);
1.1       deraadt   111:                        iflags |= SETFLAGS;
                    112:                        break;
                    113:                case 'g':
                    114:                        group = optarg;
                    115:                        break;
                    116:                case 'm':
                    117:                        if (!(set = setmode(optarg)))
1.63    ! millert   118:                                errx(1, "%s: invalid file mode", optarg);
1.1       deraadt   119:                        mode = getmode(set, 0);
1.16      deraadt   120:                        free(set);
1.1       deraadt   121:                        break;
                    122:                case 'o':
                    123:                        owner = optarg;
                    124:                        break;
1.4       millert   125:                case 'p':
                    126:                        docompare = dopreserve = 1;
                    127:                        break;
                    128:                case 'S':
                    129:                        safecopy = 1;
                    130:                        break;
1.1       deraadt   131:                case 's':
                    132:                        dostrip = 1;
                    133:                        break;
1.60      jasper    134:                case 'D':
                    135:                        dodest = 1;
                    136:                        break;
1.1       deraadt   137:                case 'd':
                    138:                        dodir = 1;
                    139:                        break;
                    140:                case '?':
                    141:                default:
                    142:                        usage();
                    143:                }
                    144:        argc -= optind;
                    145:        argv += optind;
                    146:
1.4       millert   147:        /* some options make no sense when creating directories */
                    148:        if ((safecopy || docompare || dostrip) && dodir)
1.1       deraadt   149:                usage();
                    150:
                    151:        /* must have at least two arguments, except when creating directories */
                    152:        if (argc < 2 && !dodir)
                    153:                usage();
                    154:
1.4       millert   155:        /* need to make a temp copy so we can compare stripped version */
                    156:        if (docompare && dostrip)
                    157:                safecopy = 1;
                    158:
1.1       deraadt   159:        /* get group and owner id's */
1.55      deraadt   160:        if (group && !(gp = getgrnam(group)) && !isdigit((unsigned char)*group))
1.63    ! millert   161:                errx(1, "unknown group %s", group);
1.4       millert   162:        gid = (group) ? ((gp) ? gp->gr_gid : (gid_t)strtoul(group, NULL, 10)) : (gid_t)-1;
1.55      deraadt   163:        if (owner && !(pp = getpwnam(owner)) && !isdigit((unsigned char)*owner))
1.63    ! millert   164:                errx(1, "unknown user %s", owner);
1.4       millert   165:        uid = (owner) ? ((pp) ? pp->pw_uid : (uid_t)strtoul(owner, NULL, 10)) : (uid_t)-1;
1.1       deraadt   166:
                    167:        if (dodir) {
                    168:                for (; *argv != NULL; ++argv)
1.62      jasper    169:                        install_dir(*argv, mode);
1.63    ! millert   170:                exit(0);
1.1       deraadt   171:                /* NOTREACHED */
                    172:        }
                    173:
1.60      jasper    174:        if (dodest) {
                    175:                char *dest = dirname(argv[argc - 1]);
                    176:                if (dest == NULL)
1.63    ! millert   177:                        errx(1, "cannot determine dirname");
1.62      jasper    178:                /*
                    179:                 * When -D is passed, do not chmod the directory with the mode set for
                    180:                 * the target file. If more restrictive permissions are required then
                    181:                 * '-d -m' ought to be used instead.
                    182:                 */
                    183:                install_dir(dest, 0755);
1.60      jasper    184:        }
                    185:
1.1       deraadt   186:        no_target = stat(to_name = argv[argc - 1], &to_sb);
                    187:        if (!no_target && S_ISDIR(to_sb.st_mode)) {
                    188:                for (; *argv != to_name; ++argv)
                    189:                        install(*argv, to_name, fset, iflags | DIRECTORY);
1.63    ! millert   190:                exit(0);
1.4       millert   191:                /* NOTREACHED */
1.1       deraadt   192:        }
                    193:
                    194:        /* can't do file1 file2 directory/file */
                    195:        if (argc != 2)
1.63    ! millert   196:                errx(1, "Target: %s", argv[argc-1]);
1.1       deraadt   197:
                    198:        if (!no_target) {
                    199:                if (stat(*argv, &from_sb))
1.63    ! millert   200:                        err(1, "%s", *argv);
1.1       deraadt   201:                if (!S_ISREG(to_sb.st_mode))
1.63    ! millert   202:                        errc(1, EFTYPE, "%s", to_name);
1.1       deraadt   203:                if (to_sb.st_dev == from_sb.st_dev &&
                    204:                    to_sb.st_ino == from_sb.st_ino)
1.63    ! millert   205:                        errx(1, "%s and %s are the same file", *argv, to_name);
1.1       deraadt   206:        }
                    207:        install(*argv, to_name, fset, iflags);
1.63    ! millert   208:        exit(0);
1.4       millert   209:        /* NOTREACHED */
1.1       deraadt   210: }
                    211:
                    212: /*
                    213:  * install --
                    214:  *     build a path name and install the file
                    215:  */
                    216: void
1.35      deraadt   217: install(char *from_name, char *to_name, u_long fset, u_int flags)
1.1       deraadt   218: {
                    219:        struct stat from_sb, to_sb;
1.59      guenther  220:        struct timespec ts[2];
1.4       millert   221:        int devnull, from_fd, to_fd, serrno, files_match = 0;
1.1       deraadt   222:        char *p;
                    223:
1.4       millert   224:        (void)memset((void *)&from_sb, 0, sizeof(from_sb));
                    225:        (void)memset((void *)&to_sb, 0, sizeof(to_sb));
                    226:
1.1       deraadt   227:        /* If try to install NULL file to a directory, fails. */
                    228:        if (flags & DIRECTORY || strcmp(from_name, _PATH_DEVNULL)) {
                    229:                if (stat(from_name, &from_sb))
1.63    ! millert   230:                        err(1, "%s", from_name);
1.1       deraadt   231:                if (!S_ISREG(from_sb.st_mode))
1.63    ! millert   232:                        errc(1, EFTYPE, "%s", from_name);
1.1       deraadt   233:                /* Build the target path. */
                    234:                if (flags & DIRECTORY) {
                    235:                        (void)snprintf(pathbuf, sizeof(pathbuf), "%s/%s",
                    236:                            to_name,
1.11      millert   237:                            (p = strrchr(from_name, '/')) ? ++p : from_name);
1.1       deraadt   238:                        to_name = pathbuf;
                    239:                }
                    240:                devnull = 0;
                    241:        } else {
                    242:                devnull = 1;
                    243:        }
                    244:
1.4       millert   245:        if (stat(to_name, &to_sb) == 0) {
                    246:                /* Only compare against regular files. */
                    247:                if (docompare && !S_ISREG(to_sb.st_mode)) {
                    248:                        docompare = 0;
1.57      guenther  249:                        warnc(EFTYPE, "%s", to_name);
1.4       millert   250:                }
                    251:        } else if (docompare) {
                    252:                /* File does not exist so silently ignore compare flag. */
                    253:                docompare = 0;
                    254:        }
                    255:
1.52      millert   256:        if (!devnull) {
                    257:                if ((from_fd = open(from_name, O_RDONLY, 0)) < 0)
1.63    ! millert   258:                        err(1, "%s", from_name);
1.52      millert   259:        }
                    260:
1.4       millert   261:        if (safecopy) {
                    262:                to_fd = create_tempfile(to_name, tempfile, sizeof(tempfile));
                    263:                if (to_fd < 0)
1.63    ! millert   264:                        err(1, "%s", tempfile);
1.4       millert   265:        } else if (docompare && !dostrip) {
                    266:                if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
1.63    ! millert   267:                        err(1, "%s", to_name);
1.4       millert   268:        } else {
                    269:                if ((to_fd = create_newfile(to_name, &to_sb)) < 0)
1.63    ! millert   270:                        err(1, "%s", to_name);
1.4       millert   271:        }
                    272:
1.1       deraadt   273:        if (!devnull) {
1.4       millert   274:                if (docompare && !safecopy) {
                    275:                        files_match = !(compare(from_fd, from_name,
1.59      guenther  276:                                        from_sb.st_size, to_fd,
                    277:                                        to_name, to_sb.st_size));
1.4       millert   278:
                    279:                        /* Truncate "to" file for copy unless we match */
                    280:                        if (!files_match) {
                    281:                                (void)close(to_fd);
                    282:                                if ((to_fd = create_newfile(to_name, &to_sb)) < 0)
1.63    ! millert   283:                                        err(1, "%s", to_name);
1.4       millert   284:                        }
1.1       deraadt   285:                }
1.4       millert   286:                if (!files_match)
                    287:                        copy(from_fd, from_name, to_fd,
1.17      millert   288:                             safecopy ? tempfile : to_name, from_sb.st_size,
                    289:                             ((off_t)from_sb.st_blocks * S_BLKSIZE < from_sb.st_size));
1.1       deraadt   290:        }
1.2       deraadt   291:
                    292:        if (dostrip) {
1.4       millert   293:                strip(safecopy ? tempfile : to_name);
1.2       deraadt   294:
                    295:                /*
                    296:                 * Re-open our fd on the target, in case we used a strip
                    297:                 *  that does not work in-place -- like gnu binutils strip.
                    298:                 */
                    299:                close(to_fd);
1.4       millert   300:                if ((to_fd = open(safecopy ? tempfile : to_name, O_RDONLY,
                    301:                     0)) < 0)
1.63    ! millert   302:                        err(1, "stripping %s", to_name);
1.4       millert   303:        }
                    304:
                    305:        /*
                    306:         * Compare the (possibly stripped) temp file to the target.
                    307:         */
                    308:        if (safecopy && docompare) {
                    309:                int temp_fd = to_fd;
                    310:                struct stat temp_sb;
                    311:
                    312:                /* Re-open to_fd using the real target name. */
                    313:                if ((to_fd = open(to_name, O_RDONLY, 0)) < 0)
1.63    ! millert   314:                        err(1, "%s", to_name);
1.4       millert   315:
                    316:                if (fstat(temp_fd, &temp_sb)) {
                    317:                        serrno = errno;
                    318:                        (void)unlink(tempfile);
1.63    ! millert   319:                        errc(1, serrno, "%s", tempfile);
1.4       millert   320:                }
                    321:
1.59      guenther  322:                if (compare(temp_fd, tempfile, temp_sb.st_size, to_fd,
                    323:                            to_name, to_sb.st_size) == 0) {
1.4       millert   324:                        /*
                    325:                         * If target has more than one link we need to
                    326:                         * replace it in order to snap the extra links.
                    327:                         * Need to preserve target file times, though.
                    328:                         */
                    329:                        if (to_sb.st_nlink != 1) {
1.59      guenther  330:                                ts[0] = to_sb.st_atim;
                    331:                                ts[1] = to_sb.st_mtim;
                    332:                                futimens(temp_fd, ts);
1.4       millert   333:                        } else {
                    334:                                files_match = 1;
                    335:                                (void)unlink(tempfile);
                    336:                        }
                    337:                }
1.48      phessler  338:                (void)close(to_fd);
                    339:                to_fd = temp_fd;
1.4       millert   340:        }
                    341:
                    342:        /*
1.30      millert   343:         * Preserve the timestamp of the source file if necessary.
1.4       millert   344:         */
                    345:        if (dopreserve && !files_match) {
1.59      guenther  346:                ts[0] = from_sb.st_atim;
                    347:                ts[1] = from_sb.st_mtim;
                    348:                futimens(to_fd, ts);
1.2       deraadt   349:        }
                    350:
1.1       deraadt   351:        /*
                    352:         * Set owner, group, mode for target; do the chown first,
                    353:         * chown may lose the setuid bits.
                    354:         */
1.48      phessler  355:        if ((gid != (gid_t)-1 || uid != (uid_t)-1) &&
                    356:            fchown(to_fd, uid, gid)) {
1.1       deraadt   357:                serrno = errno;
1.48      phessler  358:                (void)unlink(safecopy ? tempfile : to_name);
1.63    ! millert   359:                errx(1, "%s: chown/chgrp: %s",
1.48      phessler  360:                    safecopy ? tempfile : to_name, strerror(serrno));
1.1       deraadt   361:        }
                    362:        if (fchmod(to_fd, mode)) {
                    363:                serrno = errno;
1.48      phessler  364:                (void)unlink(safecopy ? tempfile : to_name);
1.63    ! millert   365:                errx(1, "%s: chmod: %s", safecopy ? tempfile : to_name,
1.48      phessler  366:                    strerror(serrno));
1.1       deraadt   367:        }
                    368:
                    369:        /*
                    370:         * If provided a set of flags, set them, otherwise, preserve the
                    371:         * flags, except for the dump flag.
                    372:         */
                    373:        if (fchflags(to_fd,
                    374:            flags & SETFLAGS ? fset : from_sb.st_flags & ~UF_NODUMP)) {
1.12      millert   375:                if (errno != EOPNOTSUPP || (from_sb.st_flags & ~UF_NODUMP) != 0)
1.61      jasper    376:                        warnx("%s: chflags: %s",
1.48      phessler  377:                            safecopy ? tempfile :to_name, strerror(errno));
1.1       deraadt   378:        }
                    379:
                    380:        (void)close(to_fd);
1.18      millert   381:        if (!devnull)
                    382:                (void)close(from_fd);
1.48      phessler  383:
                    384:        /*
                    385:         * Move the new file into place if doing a safe copy
                    386:         * and the files are different (or just not compared).
                    387:         */
                    388:        if (safecopy && !files_match) {
                    389:                /* Try to turn off the immutable bits. */
                    390:                if (to_sb.st_flags & (NOCHANGEBITS))
                    391:                        (void)chflags(to_name, to_sb.st_flags & ~(NOCHANGEBITS));
                    392:                if (dobackup) {
1.58      deraadt   393:                        char backup[PATH_MAX];
                    394:                        (void)snprintf(backup, PATH_MAX, "%s%s", to_name,
1.48      phessler  395:                            suffix);
                    396:                        /* It is ok for the target file not to exist. */
                    397:                        if (rename(to_name, backup) < 0 && errno != ENOENT) {
                    398:                                serrno = errno;
                    399:                                unlink(tempfile);
1.63    ! millert   400:                                errx(1, "rename: %s to %s: %s", to_name,
1.48      phessler  401:                                     backup, strerror(serrno));
                    402:                        }
                    403:                }
                    404:                if (rename(tempfile, to_name) < 0 ) {
                    405:                        serrno = errno;
                    406:                        unlink(tempfile);
1.63    ! millert   407:                        errx(1, "rename: %s to %s: %s", tempfile,
1.48      phessler  408:                             to_name, strerror(serrno));
                    409:                }
                    410:        }
1.1       deraadt   411: }
                    412:
                    413: /*
                    414:  * copy --
                    415:  *     copy from one file to another
                    416:  */
                    417: void
1.35      deraadt   418: copy(int from_fd, char *from_name, int to_fd, char *to_name, off_t size,
                    419:     int sparse)
1.1       deraadt   420: {
1.29      mpech     421:        ssize_t nr, nw;
1.1       deraadt   422:        int serrno;
                    423:        char *p, buf[MAXBSIZE];
                    424:
1.51      millert   425:        if (size == 0)
                    426:                return;
                    427:
1.7       millert   428:        /* Rewind file descriptors. */
                    429:        if (lseek(from_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1.63    ! millert   430:                err(1, "lseek: %s", from_name);
1.7       millert   431:        if (lseek(to_fd, (off_t)0, SEEK_SET) == (off_t)-1)
1.63    ! millert   432:                err(1, "lseek: %s", to_name);
1.7       millert   433:
1.1       deraadt   434:        /*
                    435:         * Mmap and write if less than 8M (the limit is so we don't totally
                    436:         * trash memory on big files.  This is really a minor hack, but it
1.17      millert   437:         * wins some CPU back.  Sparse files need special treatment.
1.1       deraadt   438:         */
1.51      millert   439:        if (!sparse && size <= 8 * 1048576) {
1.50      espie     440:                size_t siz;
1.17      millert   441:
1.19      millert   442:                if ((p = mmap(NULL, (size_t)size, PROT_READ, MAP_PRIVATE,
1.38      grange    443:                    from_fd, (off_t)0)) == MAP_FAILED) {
1.6       millert   444:                        serrno = errno;
                    445:                        (void)unlink(to_name);
1.63    ! millert   446:                        errc(1, serrno, "%s", from_name);
1.6       millert   447:                }
1.50      espie     448:                madvise(p, size, MADV_SEQUENTIAL);
1.3       deraadt   449:                siz = (size_t)size;
1.6       millert   450:                if ((nw = write(to_fd, p, siz)) != siz) {
                    451:                        serrno = errno;
                    452:                        (void)unlink(to_name);
1.63    ! millert   453:                        errx(1, "%s: %s",
1.6       millert   454:                            to_name, strerror(nw > 0 ? EIO : serrno));
                    455:                }
1.4       millert   456:                (void) munmap(p, (size_t)size);
1.1       deraadt   457:        } else {
1.17      millert   458:                int sz, rem, isem = 1;
                    459:                struct stat sb;
                    460:
                    461:                /*
                    462:                 * Pass the blocksize of the file being written to the write
                    463:                 * routine.  if the size is zero, use the default S_BLKSIZE.
                    464:                 */
                    465:                if (fstat(to_fd, &sb) != 0 || sb.st_blksize == 0)
                    466:                        sz = S_BLKSIZE;
                    467:                else
                    468:                        sz = sb.st_blksize;
1.20      millert   469:                rem = sz;
1.17      millert   470:
                    471:                while ((nr = read(from_fd, buf, sizeof(buf))) > 0) {
                    472:                        if (sparse)
                    473:                                nw = file_write(to_fd, buf, nr, &rem, &isem, sz);
                    474:                        else
                    475:                                nw = write(to_fd, buf, nr);
                    476:                        if (nw != nr) {
1.1       deraadt   477:                                serrno = errno;
                    478:                                (void)unlink(to_name);
1.63    ! millert   479:                                errx(1, "%s: %s",
1.1       deraadt   480:                                    to_name, strerror(nw > 0 ? EIO : serrno));
                    481:                        }
1.17      millert   482:                }
1.33      tedu      483:                if (sparse)
                    484:                        file_flush(to_fd, isem);
1.1       deraadt   485:                if (nr != 0) {
                    486:                        serrno = errno;
                    487:                        (void)unlink(to_name);
1.63    ! millert   488:                        errc(1, serrno, "%s", from_name);
1.1       deraadt   489:                }
                    490:        }
                    491: }
                    492:
                    493: /*
1.4       millert   494:  * compare --
                    495:  *     compare two files; non-zero means files differ
                    496:  */
                    497: int
1.59      guenther  498: compare(int from_fd, const char *from_name, off_t from_len, int to_fd,
                    499:     const char *to_name, off_t to_len)
1.4       millert   500: {
                    501:        caddr_t p1, p2;
1.59      guenther  502:        size_t length;
                    503:        off_t from_off, to_off, remainder;
1.4       millert   504:        int dfound;
                    505:
1.50      espie     506:        if (from_len == 0 && from_len == to_len)
                    507:                return (0);
                    508:
1.4       millert   509:        if (from_len != to_len)
1.50      espie     510:                return (1);
1.4       millert   511:
                    512:        /*
                    513:         * Compare the two files being careful not to mmap
                    514:         * more than 8M at a time.
                    515:         */
1.21      millert   516:        from_off = to_off = (off_t)0;
1.4       millert   517:        remainder = from_len;
                    518:        do {
1.58      deraadt   519:                length = MINIMUM(remainder, 8 * 1048576);
1.4       millert   520:                remainder -= length;
                    521:
1.22      mickey    522:                if ((p1 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
1.38      grange    523:                    from_fd, from_off)) == MAP_FAILED)
1.63    ! millert   524:                        err(1, "%s", from_name);
1.22      mickey    525:                if ((p2 = mmap(NULL, length, PROT_READ, MAP_PRIVATE,
1.38      grange    526:                    to_fd, to_off)) == MAP_FAILED)
1.63    ! millert   527:                        err(1, "%s", to_name);
1.39      mickey    528:                if (length) {
                    529:                        madvise(p1, length, MADV_SEQUENTIAL);
                    530:                        madvise(p2, length, MADV_SEQUENTIAL);
                    531:                }
1.4       millert   532:
                    533:                dfound = memcmp(p1, p2, length);
                    534:
                    535:                (void) munmap(p1, length);
                    536:                (void) munmap(p2, length);
1.21      millert   537:
                    538:                from_off += length;
                    539:                to_off += length;
1.4       millert   540:
1.7       millert   541:        } while (!dfound && remainder > 0);
1.4       millert   542:
                    543:        return(dfound);
                    544: }
                    545:
                    546: /*
1.1       deraadt   547:  * strip --
                    548:  *     use strip(1) to strip the target file
                    549:  */
                    550: void
1.35      deraadt   551: strip(char *to_name)
1.1       deraadt   552: {
                    553:        int serrno, status;
1.26      millert   554:        char * volatile path_strip;
1.18      millert   555:
1.13      millert   556:        if (issetugid() || (path_strip = getenv("STRIP")) == NULL)
                    557:                path_strip = _PATH_STRIP;
1.1       deraadt   558:
                    559:        switch (vfork()) {
                    560:        case -1:
                    561:                serrno = errno;
                    562:                (void)unlink(to_name);
1.63    ! millert   563:                errc(1, serrno, "forks");
1.1       deraadt   564:        case 0:
1.44      moritz    565:                execl(path_strip, "strip", "--", to_name, (char *)NULL);
1.13      millert   566:                warn("%s", path_strip);
1.63    ! millert   567:                _exit(1);
1.1       deraadt   568:        default:
1.14      millert   569:                if (wait(&status) == -1 || !WIFEXITED(status))
1.1       deraadt   570:                        (void)unlink(to_name);
                    571:        }
                    572: }
                    573:
                    574: /*
                    575:  * install_dir --
1.42      jsg       576:  *     build directory hierarchy
1.1       deraadt   577:  */
                    578: void
1.62      jasper    579: install_dir(char *path, int mode)
1.1       deraadt   580: {
1.29      mpech     581:        char *p;
1.8       imp       582:        struct stat sb;
                    583:        int ch;
                    584:
                    585:        for (p = path;; ++p)
                    586:                if (!*p || (p != path && *p  == '/')) {
                    587:                        ch = *p;
                    588:                        *p = '\0';
1.54      naddy     589:                        if (mkdir(path, 0777)) {
                    590:                                int mkdir_errno = errno;
                    591:                                if (stat(path, &sb)) {
                    592:                                        /* Not there; use mkdir()s errno */
1.63    ! millert   593:                                        errc(1, mkdir_errno, "%s",
1.57      guenther  594:                                            path);
1.54      naddy     595:                                        /* NOTREACHED */
                    596:                                }
                    597:                                if (!S_ISDIR(sb.st_mode)) {
                    598:                                        /* Is there, but isn't a directory */
1.63    ! millert   599:                                        errc(1, ENOTDIR, "%s", path);
1.1       deraadt   600:                                        /* NOTREACHED */
1.8       imp       601:                                }
                    602:                        }
                    603:                        if (!(*p = ch))
1.1       deraadt   604:                                break;
1.8       imp       605:                }
1.1       deraadt   606:
1.4       millert   607:        if (((gid != (gid_t)-1 || uid != (uid_t)-1) && chown(path, uid, gid)) ||
1.8       imp       608:            chmod(path, mode)) {
                    609:                warn("%s", path);
                    610:        }
1.1       deraadt   611: }
                    612:
                    613: /*
                    614:  * usage --
                    615:  *     print a usage message and die
                    616:  */
                    617: void
1.35      deraadt   618: usage(void)
1.1       deraadt   619: {
                    620:        (void)fprintf(stderr, "\
1.60      jasper    621: usage: install [-bCcDdpSs] [-B suffix] [-f flags] [-g group] [-m mode] [-o owner]\n           source ... target ...\n");
1.63    ! millert   622:        exit(1);
1.4       millert   623:        /* NOTREACHED */
                    624: }
                    625:
                    626: /*
                    627:  * create_tempfile --
                    628:  *     create a temporary file based on path and open it
                    629:  */
                    630: int
1.35      deraadt   631: create_tempfile(char *path, char *temp, size_t tsize)
1.4       millert   632: {
                    633:        char *p;
                    634:
1.43      millert   635:        strlcpy(temp, path, tsize);
                    636:        if ((p = strrchr(temp, '/')) != NULL)
1.4       millert   637:                p++;
                    638:        else
                    639:                p = temp;
1.43      millert   640:        *p = '\0';
                    641:        strlcat(p, "INS@XXXXXXXXXX", tsize);
1.4       millert   642:
                    643:        return(mkstemp(temp));
                    644: }
                    645:
                    646: /*
                    647:  * create_newfile --
1.30      millert   648:  *     create a new file, overwriting an existing one if necessary
1.4       millert   649:  */
                    650: int
1.35      deraadt   651: create_newfile(char *path, struct stat *sbp)
1.4       millert   652: {
1.58      deraadt   653:        char backup[PATH_MAX];
1.19      millert   654:
1.4       millert   655:        /*
                    656:         * Unlink now... avoid ETXTBSY errors later.  Try and turn
                    657:         * off the append/immutable bits -- if we fail, go ahead,
                    658:         * it might work.
                    659:         */
                    660:        if (sbp->st_flags & (NOCHANGEBITS))
                    661:                (void)chflags(path, sbp->st_flags & ~(NOCHANGEBITS));
                    662:
1.19      millert   663:        if (dobackup) {
1.58      deraadt   664:                (void)snprintf(backup, PATH_MAX, "%s%s", path, suffix);
1.28      heko      665:                /* It is ok for the target file not to exist. */
                    666:                if (rename(path, backup) < 0 && errno != ENOENT)
1.63    ! millert   667:                        err(1, "rename: %s to %s (errno %d)", path, backup, errno);
1.53      miod      668:        } else {
                    669:                if (unlink(path) < 0 && errno != ENOENT)
1.63    ! millert   670:                        err(1, "%s", path);
1.53      miod      671:        }
1.4       millert   672:
1.52      millert   673:        return(open(path, O_CREAT | O_RDWR | O_EXCL, S_IRUSR | S_IWUSR));
1.17      millert   674: }
                    675:
                    676: /*
                    677:  * file_write()
                    678:  *     Write/copy a file (during copy or archive extract). This routine knows
                    679:  *     how to copy files with lseek holes in it. (Which are read as file
                    680:  *     blocks containing all 0's but do not have any file blocks associated
                    681:  *     with the data). Typical examples of these are files created by dbm
                    682:  *     variants (.pag files). While the file size of these files are huge, the
                    683:  *     actual storage is quite small (the files are sparse). The problem is
                    684:  *     the holes read as all zeros so are probably stored on the archive that
                    685:  *     way (there is no way to determine if the file block is really a hole,
                    686:  *     we only know that a file block of all zero's can be a hole).
                    687:  *     At this writing, no major archive format knows how to archive files
                    688:  *     with holes. However, on extraction (or during copy, -rw) we have to
                    689:  *     deal with these files. Without detecting the holes, the files can
                    690:  *     consume a lot of file space if just written to disk. This replacement
                    691:  *     for write when passed the basic allocation size of a file system block,
                    692:  *     uses lseek whenever it detects the input data is all 0 within that
                    693:  *     file block. In more detail, the strategy is as follows:
                    694:  *     While the input is all zero keep doing an lseek. Keep track of when we
1.45      krw       695:  *     pass over file block boundaries. Only write when we hit a non zero
1.17      millert   696:  *     input. once we have written a file block, we continue to write it to
                    697:  *     the end (we stop looking at the input). When we reach the start of the
                    698:  *     next file block, start checking for zero blocks again. Working on file
1.45      krw       699:  *     block boundaries significantly reduces the overhead when copying files
1.17      millert   700:  *     that are NOT very sparse. This overhead (when compared to a write) is
                    701:  *     almost below the measurement resolution on many systems. Without it,
                    702:  *     files with holes cannot be safely copied. It does has a side effect as
                    703:  *     it can put holes into files that did not have them before, but that is
                    704:  *     not a problem since the file contents are unchanged (in fact it saves
                    705:  *     file space). (Except on paging files for diskless clients. But since we
                    706:  *     cannot determine one of those file from here, we ignore them). If this
                    707:  *     ever ends up on a system where CTG files are supported and the holes
                    708:  *     are not desired, just do a conditional test in those routines that
                    709:  *     call file_write() and have it call write() instead. BEFORE CLOSING THE
                    710:  *     FILE, make sure to call file_flush() when the last write finishes with
                    711:  *     an empty block. A lot of file systems will not create an lseek hole at
                    712:  *     the end. In this case we drop a single 0 at the end to force the
                    713:  *     trailing 0's in the file.
                    714:  *     ---Parameters---
                    715:  *     rem: how many bytes left in this file system block
                    716:  *     isempt: have we written to the file block yet (is it empty)
                    717:  *     sz: basic file block allocation size
                    718:  *     cnt: number of bytes on this write
                    719:  *     str: buffer to write
                    720:  * Return:
                    721:  *     number of bytes written, -1 on write (or lseek) error.
                    722:  */
                    723:
                    724: int
1.35      deraadt   725: file_write(int fd, char *str, size_t cnt, int *rem, int *isempt, int sz)
1.17      millert   726: {
1.29      mpech     727:        char *pt;
                    728:        char *end;
                    729:        size_t wcnt;
                    730:        char *st = str;
1.17      millert   731:
                    732:        /*
                    733:         * while we have data to process
                    734:         */
                    735:        while (cnt) {
                    736:                if (!*rem) {
                    737:                        /*
                    738:                         * We are now at the start of file system block again
                    739:                         * (or what we think one is...). start looking for
                    740:                         * empty blocks again
                    741:                         */
                    742:                        *isempt = 1;
                    743:                        *rem = sz;
                    744:                }
                    745:
                    746:                /*
                    747:                 * only examine up to the end of the current file block or
                    748:                 * remaining characters to write, whatever is smaller
                    749:                 */
1.58      deraadt   750:                wcnt = MINIMUM(cnt, *rem);
1.17      millert   751:                cnt -= wcnt;
                    752:                *rem -= wcnt;
                    753:                if (*isempt) {
                    754:                        /*
                    755:                         * have not written to this block yet, so we keep
                    756:                         * looking for zero's
                    757:                         */
                    758:                        pt = st;
                    759:                        end = st + wcnt;
                    760:
                    761:                        /*
                    762:                         * look for a zero filled buffer
                    763:                         */
                    764:                        while ((pt < end) && (*pt == '\0'))
                    765:                                ++pt;
                    766:
                    767:                        if (pt == end) {
                    768:                                /*
                    769:                                 * skip, buf is empty so far
                    770:                                 */
                    771:                                if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
                    772:                                        warn("lseek");
                    773:                                        return(-1);
                    774:                                }
                    775:                                st = pt;
                    776:                                continue;
                    777:                        }
                    778:                        /*
                    779:                         * drat, the buf is not zero filled
                    780:                         */
                    781:                        *isempt = 0;
                    782:                }
                    783:
                    784:                /*
                    785:                 * have non-zero data in this file system block, have to write
                    786:                 */
                    787:                if (write(fd, st, wcnt) != wcnt) {
                    788:                        warn("write");
                    789:                        return(-1);
                    790:                }
                    791:                st += wcnt;
                    792:        }
                    793:        return(st - str);
1.33      tedu      794: }
                    795:
                    796: /*
                    797:  * file_flush()
                    798:  *     when the last file block in a file is zero, many file systems will not
                    799:  *     let us create a hole at the end. To get the last block with zeros, we
                    800:  *     write the last BYTE with a zero (back up one byte and write a zero).
                    801:  */
                    802: void
                    803: file_flush(int fd, int isempt)
                    804: {
                    805:        static char blnk[] = "\0";
                    806:
                    807:        /*
                    808:         * silly test, but make sure we are only called when the last block is
                    809:         * filled with all zeros.
                    810:         */
                    811:        if (!isempt)
                    812:                return;
                    813:
                    814:        /*
                    815:         * move back one byte and write a zero
                    816:         */
                    817:        if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
                    818:                warn("Failed seek on file");
                    819:                return;
                    820:        }
                    821:
                    822:        if (write(fd, blnk, 1) < 0)
                    823:                warn("Failed write to file");
                    824:        return;
1.1       deraadt   825: }