[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.59

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