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

Annotation of src/usr.bin/ssh/scp.c, Revision 1.66

1.1       deraadt     1: /*
1.38      deraadt     2:  * scp - secure remote copy.  This is basically patched BSD rcp which
                      3:  * uses ssh to do the data transfer (instead of using rcmd).
1.27      markus      4:  *
1.38      deraadt     5:  * NOTE: This version should NOT be suid root.  (This uses ssh to
                      6:  * do the transfer and ssh has the necessary privileges.)
1.27      markus      7:  *
1.38      deraadt     8:  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
                      9:  *
                     10:  * As far as I am concerned, the code I have written for this software
                     11:  * can be used freely for any purpose.  Any derived versions of this
                     12:  * software must be clearly marked as such, and if the derived work is
                     13:  * incompatible with the protocol description in the RFC file, it must be
                     14:  * called by a name other than "ssh" or "Secure Shell".
1.39      markus     15:  */
1.38      deraadt    16: /*
1.60      deraadt    17:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     18:  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
1.27      markus     19:  *
1.38      deraadt    20:  * Redistribution and use in source and binary forms, with or without
                     21:  * modification, are permitted provided that the following conditions
                     22:  * are met:
                     23:  * 1. Redistributions of source code must retain the above copyright
                     24:  *    notice, this list of conditions and the following disclaimer.
                     25:  * 2. Redistributions in binary form must reproduce the above copyright
                     26:  *    notice, this list of conditions and the following disclaimer in the
                     27:  *    documentation and/or other materials provided with the distribution.
1.27      markus     28:  *
1.38      deraadt    29:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     30:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     31:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     32:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     33:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     34:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     35:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     36:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     37:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     38:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     39:  */
1.1       deraadt    40:
                     41: /*
1.35      deraadt    42:  * Parts from:
                     43:  *
1.1       deraadt    44:  * Copyright (c) 1983, 1990, 1992, 1993, 1995
                     45:  *     The Regents of the University of California.  All rights reserved.
                     46:  *
                     47:  * Redistribution and use in source and binary forms, with or without
                     48:  * modification, are permitted provided that the following conditions
                     49:  * are met:
                     50:  * 1. Redistributions of source code must retain the above copyright
                     51:  *    notice, this list of conditions and the following disclaimer.
                     52:  * 2. Redistributions in binary form must reproduce the above copyright
                     53:  *    notice, this list of conditions and the following disclaimer in the
                     54:  *    documentation and/or other materials provided with the distribution.
                     55:  * 3. All advertising materials mentioning features or use of this software
                     56:  *    must display the following acknowledgement:
                     57:  *     This product includes software developed by the University of
                     58:  *     California, Berkeley and its contributors.
                     59:  * 4. Neither the name of the University nor the names of its contributors
                     60:  *    may be used to endorse or promote products derived from this software
                     61:  *    without specific prior written permission.
                     62:  *
                     63:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     64:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     65:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     66:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     67:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     68:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     69:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     70:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     71:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     72:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     73:  * SUCH DAMAGE.
                     74:  *
                     75:  */
                     76:
                     77: #include "includes.h"
1.66    ! stevesk    78: RCSID("$OpenBSD: scp.c,v 1.65 2001/04/06 16:46:59 deraadt Exp $");
1.1       deraadt    79:
                     80: #include "xmalloc.h"
1.51      markus     81: #include "atomicio.h"
1.50      markus     82: #include "pathnames.h"
1.51      markus     83: #include "log.h"
1.1       deraadt    84:
1.11      aaron      85: /* For progressmeter() -- number of seconds before xfer considered "stalled" */
1.4       aaron      86: #define STALLTIME      5
                     87:
1.11      aaron      88: /* Visual statistics about files as they are transferred. */
                     89: void progressmeter(int);
                     90:
                     91: /* Returns width of the terminal (for progress meter calculations). */
                     92: int getttywidth(void);
1.35      deraadt    93: int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
1.11      aaron      94:
1.41      markus     95: /* setup arguments for the call to ssh */
                     96: void addargs(char *fmt, ...) __attribute__((format(printf, 1, 2)));
                     97:
1.11      aaron      98: /* Time a transfer started. */
1.4       aaron      99: static struct timeval start;
1.11      aaron     100:
                    101: /* Number of bytes of current file transferred so far. */
1.47      markus    102: volatile u_long statbytes;
1.11      aaron     103:
                    104: /* Total size of current file. */
1.15      markus    105: off_t totalbytes = 0;
1.11      aaron     106:
                    107: /* Name of current file being transferred. */
                    108: char *curfile;
1.4       aaron     109:
1.1       deraadt   110: /* This is set to non-zero to enable verbose mode. */
1.17      markus    111: int verbose_mode = 0;
1.1       deraadt   112:
1.6       aaron     113: /* This is set to zero if the progressmeter is not desired. */
                    114: int showprogress = 1;
                    115:
1.34      deraadt   116: /* This is the program to execute for the secured connection. ("ssh" or -S) */
1.50      markus    117: char *ssh_program = _PATH_SSH_PROGRAM;
1.34      deraadt   118:
1.41      markus    119: /* This is the list of arguments that scp passes to ssh */
                    120: struct {
                    121:        char    **list;
                    122:        int     num;
                    123:        int     nalloc;
                    124: } args;
                    125:
1.20      markus    126: /*
                    127:  * This function executes the given command as the specified user on the
                    128:  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
                    129:  * assigns the input and output file descriptors on success.
                    130:  */
1.1       deraadt   131:
1.27      markus    132: int
1.35      deraadt   133: do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
1.1       deraadt   134: {
1.18      markus    135:        int pin[2], pout[2], reserved[2];
                    136:
                    137:        if (verbose_mode)
1.41      markus    138:                fprintf(stderr, "Executing: program %s host %s, user %s, command %s\n",
                    139:                    ssh_program, host, remuser ? remuser : "(unspecified)", cmd);
1.18      markus    140:
1.20      markus    141:        /*
                    142:         * Reserve two descriptors so that the real pipes won't get
                    143:         * descriptors 0 and 1 because that will screw up dup2 below.
                    144:         */
1.18      markus    145:        pipe(reserved);
                    146:
                    147:        /* Create a socket pair for communicating with ssh. */
                    148:        if (pipe(pin) < 0)
                    149:                fatal("pipe: %s", strerror(errno));
                    150:        if (pipe(pout) < 0)
                    151:                fatal("pipe: %s", strerror(errno));
                    152:
                    153:        /* Free the reserved descriptors. */
                    154:        close(reserved[0]);
                    155:        close(reserved[1]);
                    156:
                    157:        /* For a child to execute the command on the remote host using ssh. */
1.41      markus    158:        if (fork() == 0)  {
1.18      markus    159:                /* Child. */
                    160:                close(pin[1]);
                    161:                close(pout[0]);
                    162:                dup2(pin[0], 0);
                    163:                dup2(pout[1], 1);
                    164:                close(pin[0]);
                    165:                close(pout[1]);
                    166:
1.41      markus    167:                args.list[0] = ssh_program;
                    168:                if (remuser != NULL)
1.42      markus    169:                        addargs("-l%s", remuser);
1.41      markus    170:                addargs("%s", host);
                    171:                addargs("%s", cmd);
1.18      markus    172:
1.41      markus    173:                execvp(ssh_program, args.list);
1.34      deraadt   174:                perror(ssh_program);
1.18      markus    175:                exit(1);
                    176:        }
                    177:        /* Parent.  Close the other side, and return the local side. */
                    178:        close(pin[0]);
                    179:        *fdout = pin[1];
                    180:        close(pout[1]);
                    181:        *fdin = pout[0];
                    182:        return 0;
1.1       deraadt   183: }
                    184:
                    185: typedef struct {
                    186:        int cnt;
                    187:        char *buf;
                    188: } BUF;
                    189:
1.18      markus    190: BUF *allocbuf(BUF *, int, int);
                    191: char *colon(char *);
                    192: void lostconn(int);
                    193: void nospace(void);
                    194: int okname(char *);
                    195: void run_err(const char *,...);
                    196: void verifydir(char *);
1.1       deraadt   197:
                    198: struct passwd *pwd;
1.18      markus    199: uid_t userid;
1.1       deraadt   200: int errs, remin, remout;
                    201: int pflag, iamremote, iamrecursive, targetshouldbedirectory;
                    202:
                    203: #define        CMDNEEDS        64
                    204: char cmd[CMDNEEDS];            /* must hold "rcp -r -p -d\0" */
                    205:
1.18      markus    206: int response(void);
                    207: void rsource(char *, struct stat *);
                    208: void sink(int, char *[]);
                    209: void source(int, char *[]);
                    210: void tolocal(int, char *[]);
1.56      itojun    211: char *cleanhostname(char *);
1.18      markus    212: void toremote(char *, int, char *[]);
                    213: void usage(void);
1.1       deraadt   214:
                    215: int
                    216: main(argc, argv)
                    217:        int argc;
                    218:        char *argv[];
                    219: {
                    220:        int ch, fflag, tflag;
                    221:        char *targ;
                    222:        extern char *optarg;
                    223:        extern int optind;
                    224:
1.41      markus    225:        args.list = NULL;
                    226:        addargs("ssh");         /* overwritten with ssh_program */
                    227:        addargs("-x");
                    228:        addargs("-oFallBackToRsh no");
                    229:
1.1       deraadt   230:        fflag = tflag = 0;
1.49      markus    231:        while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:o:")) != -1)
1.18      markus    232:                switch (ch) {
                    233:                /* User-visible flags. */
1.23      markus    234:                case '4':
1.41      markus    235:                case '6':
                    236:                case 'C':
                    237:                        addargs("-%c", ch);
                    238:                        break;
                    239:                case 'o':
                    240:                case 'c':
                    241:                case 'i':
1.42      markus    242:                        addargs("-%c%s", ch, optarg);
1.23      markus    243:                        break;
1.41      markus    244:                case 'P':
1.42      markus    245:                        addargs("-p%s", optarg);
1.41      markus    246:                        break;
                    247:                case 'B':
1.42      markus    248:                        addargs("-oBatchmode yes");
1.23      markus    249:                        break;
1.1       deraadt   250:                case 'p':
                    251:                        pflag = 1;
                    252:                        break;
                    253:                case 'r':
                    254:                        iamrecursive = 1;
                    255:                        break;
1.34      deraadt   256:                case 'S':
1.41      markus    257:                        ssh_program = xstrdup(optarg);
                    258:                        break;
                    259:                case 'v':
                    260:                        verbose_mode = 1;
                    261:                        break;
                    262:                case 'q':
                    263:                        showprogress = 0;
1.34      deraadt   264:                        break;
                    265:
1.18      markus    266:                /* Server options. */
1.1       deraadt   267:                case 'd':
                    268:                        targetshouldbedirectory = 1;
                    269:                        break;
1.18      markus    270:                case 'f':       /* "from" */
1.1       deraadt   271:                        iamremote = 1;
                    272:                        fflag = 1;
                    273:                        break;
1.18      markus    274:                case 't':       /* "to" */
1.1       deraadt   275:                        iamremote = 1;
                    276:                        tflag = 1;
                    277:                        break;
                    278:                default:
                    279:                        usage();
                    280:                }
                    281:        argc -= optind;
                    282:        argv += optind;
                    283:
                    284:        if ((pwd = getpwuid(userid = getuid())) == NULL)
1.18      markus    285:                fatal("unknown user %d", (int) userid);
1.1       deraadt   286:
1.18      markus    287:        if (!isatty(STDERR_FILENO))
1.7       deraadt   288:                showprogress = 0;
                    289:
1.1       deraadt   290:        remin = STDIN_FILENO;
                    291:        remout = STDOUT_FILENO;
                    292:
1.52      stevesk   293:        if (fflag) {
1.18      markus    294:                /* Follow "protocol", send data. */
                    295:                (void) response();
1.1       deraadt   296:                source(argc, argv);
                    297:                exit(errs != 0);
                    298:        }
1.18      markus    299:        if (tflag) {
                    300:                /* Receive data. */
1.1       deraadt   301:                sink(argc, argv);
                    302:                exit(errs != 0);
                    303:        }
                    304:        if (argc < 2)
                    305:                usage();
                    306:        if (argc > 2)
                    307:                targetshouldbedirectory = 1;
                    308:
                    309:        remin = remout = -1;
                    310:        /* Command to be executed on remote system using "ssh". */
1.55      deraadt   311:        (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
                    312:            verbose_mode ? " -v" : "",
1.35      deraadt   313:            iamrecursive ? " -r" : "", pflag ? " -p" : "",
                    314:            targetshouldbedirectory ? " -d" : "");
1.1       deraadt   315:
1.18      markus    316:        (void) signal(SIGPIPE, lostconn);
1.1       deraadt   317:
                    318:        if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
                    319:                toremote(targ, argc, argv);
                    320:        else {
1.18      markus    321:                tolocal(argc, argv);    /* Dest is local host. */
1.1       deraadt   322:                if (targetshouldbedirectory)
                    323:                        verifydir(argv[argc - 1]);
                    324:        }
                    325:        exit(errs != 0);
                    326: }
                    327:
1.23      markus    328: char *
                    329: cleanhostname(host)
                    330:        char *host;
                    331: {
                    332:        if (*host == '[' && host[strlen(host) - 1] == ']') {
                    333:                host[strlen(host) - 1] = '\0';
                    334:                return (host + 1);
                    335:        } else
                    336:                return host;
                    337: }
                    338:
1.1       deraadt   339: void
                    340: toremote(targ, argc, argv)
                    341:        char *targ, *argv[];
                    342:        int argc;
                    343: {
                    344:        int i, len;
                    345:        char *bp, *host, *src, *suser, *thost, *tuser;
                    346:
                    347:        *targ++ = 0;
                    348:        if (*targ == 0)
                    349:                targ = ".";
                    350:
                    351:        if ((thost = strchr(argv[argc - 1], '@'))) {
                    352:                /* user@host */
                    353:                *thost++ = 0;
                    354:                tuser = argv[argc - 1];
                    355:                if (*tuser == '\0')
                    356:                        tuser = NULL;
                    357:                else if (!okname(tuser))
                    358:                        exit(1);
                    359:        } else {
                    360:                thost = argv[argc - 1];
                    361:                tuser = NULL;
                    362:        }
                    363:
                    364:        for (i = 0; i < argc - 1; i++) {
                    365:                src = colon(argv[i]);
1.18      markus    366:                if (src) {      /* remote to remote */
1.1       deraadt   367:                        *src++ = 0;
                    368:                        if (*src == 0)
                    369:                                src = ".";
                    370:                        host = strchr(argv[i], '@');
1.34      deraadt   371:                        len = strlen(ssh_program) + strlen(argv[i]) +
1.35      deraadt   372:                            strlen(src) + (tuser ? strlen(tuser) : 0) +
                    373:                            strlen(thost) + strlen(targ) + CMDNEEDS + 32;
1.18      markus    374:                        bp = xmalloc(len);
1.1       deraadt   375:                        if (host) {
                    376:                                *host++ = 0;
1.23      markus    377:                                host = cleanhostname(host);
1.1       deraadt   378:                                suser = argv[i];
                    379:                                if (*suser == '\0')
                    380:                                        suser = pwd->pw_name;
                    381:                                else if (!okname(suser))
                    382:                                        continue;
1.55      deraadt   383:                                snprintf(bp, len,
                    384:                                    "%s%s -x -o'FallBackToRsh no' -n "
                    385:                                    "-l %s %s %s %s '%s%s%s:%s'",
1.44      deraadt   386:                                    ssh_program, verbose_mode ? " -v" : "",
                    387:                                    suser, host, cmd, src,
                    388:                                    tuser ? tuser : "", tuser ? "@" : "",
                    389:                                    thost, targ);
1.23      markus    390:                        } else {
                    391:                                host = cleanhostname(argv[i]);
1.55      deraadt   392:                                snprintf(bp, len,
                    393:                                    "exec %s%s -x -o'FallBackToRsh no' -n %s "
                    394:                                    "%s %s '%s%s%s:%s'",
1.44      deraadt   395:                                    ssh_program, verbose_mode ? " -v" : "",
                    396:                                    host, cmd, src,
                    397:                                    tuser ? tuser : "", tuser ? "@" : "",
                    398:                                    thost, targ);
1.23      markus    399:                        }
1.18      markus    400:                        if (verbose_mode)
                    401:                                fprintf(stderr, "Executing: %s\n", bp);
                    402:                        (void) system(bp);
                    403:                        (void) xfree(bp);
                    404:                } else {        /* local to remote */
1.1       deraadt   405:                        if (remin == -1) {
                    406:                                len = strlen(targ) + CMDNEEDS + 20;
1.18      markus    407:                                bp = xmalloc(len);
1.55      deraadt   408:                                (void) snprintf(bp, len, "%s -t %s", cmd, targ);
1.23      markus    409:                                host = cleanhostname(thost);
1.35      deraadt   410:                                if (do_cmd(host, tuser, bp, &remin,
                    411:                                    &remout, argc) < 0)
1.18      markus    412:                                        exit(1);
1.1       deraadt   413:                                if (response() < 0)
                    414:                                        exit(1);
1.18      markus    415:                                (void) xfree(bp);
1.1       deraadt   416:                        }
1.18      markus    417:                        source(1, argv + i);
1.1       deraadt   418:                }
                    419:        }
                    420: }
                    421:
                    422: void
                    423: tolocal(argc, argv)
                    424:        int argc;
                    425:        char *argv[];
                    426: {
                    427:        int i, len;
                    428:        char *bp, *host, *src, *suser;
                    429:
                    430:        for (i = 0; i < argc - 1; i++) {
1.18      markus    431:                if (!(src = colon(argv[i]))) {  /* Local to local. */
1.1       deraadt   432:                        len = strlen(_PATH_CP) + strlen(argv[i]) +
1.35      deraadt   433:                            strlen(argv[argc - 1]) + 20;
1.1       deraadt   434:                        bp = xmalloc(len);
1.55      deraadt   435:                        (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
1.35      deraadt   436:                            iamrecursive ? " -r" : "", pflag ? " -p" : "",
                    437:                            argv[i], argv[argc - 1]);
1.18      markus    438:                        if (verbose_mode)
                    439:                                fprintf(stderr, "Executing: %s\n", bp);
1.1       deraadt   440:                        if (system(bp))
                    441:                                ++errs;
1.18      markus    442:                        (void) xfree(bp);
1.1       deraadt   443:                        continue;
                    444:                }
                    445:                *src++ = 0;
                    446:                if (*src == 0)
                    447:                        src = ".";
                    448:                if ((host = strchr(argv[i], '@')) == NULL) {
                    449:                        host = argv[i];
                    450:                        suser = NULL;
                    451:                } else {
                    452:                        *host++ = 0;
                    453:                        suser = argv[i];
                    454:                        if (*suser == '\0')
                    455:                                suser = pwd->pw_name;
                    456:                        else if (!okname(suser))
                    457:                                continue;
                    458:                }
1.23      markus    459:                host = cleanhostname(host);
1.1       deraadt   460:                len = strlen(src) + CMDNEEDS + 20;
1.18      markus    461:                bp = xmalloc(len);
1.55      deraadt   462:                (void) snprintf(bp, len, "%s -f %s", cmd, src);
1.35      deraadt   463:                if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
1.18      markus    464:                        (void) xfree(bp);
                    465:                        ++errs;
                    466:                        continue;
1.1       deraadt   467:                }
1.18      markus    468:                xfree(bp);
1.1       deraadt   469:                sink(1, argv + argc - 1);
1.18      markus    470:                (void) close(remin);
1.1       deraadt   471:                remin = remout = -1;
                    472:        }
                    473: }
                    474:
                    475: void
                    476: source(argc, argv)
                    477:        int argc;
                    478:        char *argv[];
                    479: {
                    480:        struct stat stb;
                    481:        static BUF buffer;
                    482:        BUF *bp;
                    483:        off_t i;
                    484:        int amt, fd, haderr, indx, result;
                    485:        char *last, *name, buf[2048];
1.65      deraadt   486:        int len;
1.1       deraadt   487:
                    488:        for (indx = 0; indx < argc; ++indx) {
1.18      markus    489:                name = argv[indx];
1.11      aaron     490:                statbytes = 0;
1.65      deraadt   491:                len = strlen(name);
                    492:                while (len > 1 && name[len-1] == '/')
                    493:                        name[--len] = '\0';
1.1       deraadt   494:                if ((fd = open(name, O_RDONLY, 0)) < 0)
                    495:                        goto syserr;
                    496:                if (fstat(fd, &stb) < 0) {
                    497: syserr:                        run_err("%s: %s", name, strerror(errno));
                    498:                        goto next;
                    499:                }
                    500:                switch (stb.st_mode & S_IFMT) {
                    501:                case S_IFREG:
                    502:                        break;
                    503:                case S_IFDIR:
                    504:                        if (iamrecursive) {
                    505:                                rsource(name, &stb);
                    506:                                goto next;
                    507:                        }
                    508:                        /* FALLTHROUGH */
                    509:                default:
                    510:                        run_err("%s: not a regular file", name);
                    511:                        goto next;
                    512:                }
                    513:                if ((last = strrchr(name, '/')) == NULL)
                    514:                        last = name;
                    515:                else
                    516:                        ++last;
1.11      aaron     517:                curfile = last;
1.1       deraadt   518:                if (pflag) {
                    519:                        /*
                    520:                         * Make it compatible with possible future
                    521:                         * versions expecting microseconds.
                    522:                         */
1.55      deraadt   523:                        (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1.47      markus    524:                            (u_long) stb.st_mtime,
                    525:                            (u_long) stb.st_atime);
1.29      deraadt   526:                        (void) atomicio(write, remout, buf, strlen(buf));
1.1       deraadt   527:                        if (response() < 0)
                    528:                                goto next;
                    529:                }
                    530: #define        FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1.61      markus    531:                snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1.47      markus    532:                    (u_int) (stb.st_mode & FILEMODEMASK),
1.62      markus    533:                    (long long)stb.st_size, last);
1.18      markus    534:                if (verbose_mode) {
                    535:                        fprintf(stderr, "Sending file modes: %s", buf);
                    536:                        fflush(stderr);
                    537:                }
1.29      deraadt   538:                (void) atomicio(write, remout, buf, strlen(buf));
1.1       deraadt   539:                if (response() < 0)
                    540:                        goto next;
                    541:                if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
1.18      markus    542: next:                  (void) close(fd);
1.1       deraadt   543:                        continue;
                    544:                }
1.12      aaron     545:                if (showprogress) {
                    546:                        totalbytes = stb.st_size;
1.6       aaron     547:                        progressmeter(-1);
1.12      aaron     548:                }
1.1       deraadt   549:                /* Keep writing after an error so that we stay sync'd up. */
                    550:                for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
                    551:                        amt = bp->cnt;
                    552:                        if (i + amt > stb.st_size)
                    553:                                amt = stb.st_size - i;
                    554:                        if (!haderr) {
1.30      deraadt   555:                                result = atomicio(read, fd, bp->buf, amt);
1.1       deraadt   556:                                if (result != amt)
                    557:                                        haderr = result >= 0 ? EIO : errno;
                    558:                        }
                    559:                        if (haderr)
1.29      deraadt   560:                                (void) atomicio(write, remout, bp->buf, amt);
1.1       deraadt   561:                        else {
1.29      deraadt   562:                                result = atomicio(write, remout, bp->buf, amt);
1.1       deraadt   563:                                if (result != amt)
                    564:                                        haderr = result >= 0 ? EIO : errno;
1.4       aaron     565:                                statbytes += result;
1.1       deraadt   566:                        }
                    567:                }
1.18      markus    568:                if (showprogress)
1.6       aaron     569:                        progressmeter(1);
1.4       aaron     570:
1.1       deraadt   571:                if (close(fd) < 0 && !haderr)
                    572:                        haderr = errno;
                    573:                if (!haderr)
1.29      deraadt   574:                        (void) atomicio(write, remout, "", 1);
1.1       deraadt   575:                else
                    576:                        run_err("%s: %s", name, strerror(haderr));
1.18      markus    577:                (void) response();
1.1       deraadt   578:        }
                    579: }
                    580:
                    581: void
                    582: rsource(name, statp)
                    583:        char *name;
                    584:        struct stat *statp;
                    585: {
                    586:        DIR *dirp;
                    587:        struct dirent *dp;
                    588:        char *last, *vect[1], path[1100];
                    589:
                    590:        if (!(dirp = opendir(name))) {
                    591:                run_err("%s: %s", name, strerror(errno));
                    592:                return;
                    593:        }
                    594:        last = strrchr(name, '/');
                    595:        if (last == 0)
                    596:                last = name;
                    597:        else
                    598:                last++;
                    599:        if (pflag) {
1.55      deraadt   600:                (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1.47      markus    601:                    (u_long) statp->st_mtime,
                    602:                    (u_long) statp->st_atime);
1.29      deraadt   603:                (void) atomicio(write, remout, path, strlen(path));
1.1       deraadt   604:                if (response() < 0) {
                    605:                        closedir(dirp);
                    606:                        return;
                    607:                }
                    608:        }
1.55      deraadt   609:        (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1.47      markus    610:            (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1.18      markus    611:        if (verbose_mode)
                    612:                fprintf(stderr, "Entering directory: %s", path);
1.29      deraadt   613:        (void) atomicio(write, remout, path, strlen(path));
1.1       deraadt   614:        if (response() < 0) {
                    615:                closedir(dirp);
                    616:                return;
                    617:        }
1.63      stevesk   618:        while ((dp = readdir(dirp)) != NULL) {
1.1       deraadt   619:                if (dp->d_ino == 0)
                    620:                        continue;
                    621:                if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
                    622:                        continue;
                    623:                if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
                    624:                        run_err("%s/%s: name too long", name, dp->d_name);
                    625:                        continue;
                    626:                }
1.55      deraadt   627:                (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1.1       deraadt   628:                vect[0] = path;
                    629:                source(1, vect);
                    630:        }
1.18      markus    631:        (void) closedir(dirp);
1.29      deraadt   632:        (void) atomicio(write, remout, "E\n", 2);
1.18      markus    633:        (void) response();
1.1       deraadt   634: }
                    635:
                    636: void
                    637: sink(argc, argv)
                    638:        int argc;
                    639:        char *argv[];
                    640: {
                    641:        static BUF buffer;
                    642:        struct stat stb;
1.18      markus    643:        enum {
                    644:                YES, NO, DISPLAYED
                    645:        } wrerr;
1.1       deraadt   646:        BUF *bp;
                    647:        off_t i, j;
                    648:        int amt, count, exists, first, mask, mode, ofd, omode;
1.36      deraadt   649:        off_t size;
                    650:        int setimes, targisdir, wrerrno = 0;
1.1       deraadt   651:        char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
1.40      markus    652:        struct timeval tv[2];
1.1       deraadt   653:
1.66    ! stevesk   654: #define        atime   tv[0]
        !           655: #define        mtime   tv[1]
1.1       deraadt   656: #define        SCREWUP(str)    { why = str; goto screwup; }
                    657:
                    658:        setimes = targisdir = 0;
                    659:        mask = umask(0);
                    660:        if (!pflag)
1.18      markus    661:                (void) umask(mask);
1.1       deraadt   662:        if (argc != 1) {
                    663:                run_err("ambiguous target");
                    664:                exit(1);
                    665:        }
                    666:        targ = *argv;
                    667:        if (targetshouldbedirectory)
                    668:                verifydir(targ);
1.18      markus    669:
1.29      deraadt   670:        (void) atomicio(write, remout, "", 1);
1.1       deraadt   671:        if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
                    672:                targisdir = 1;
                    673:        for (first = 1;; first = 0) {
                    674:                cp = buf;
1.30      deraadt   675:                if (atomicio(read, remin, cp, 1) <= 0)
1.1       deraadt   676:                        return;
                    677:                if (*cp++ == '\n')
                    678:                        SCREWUP("unexpected <newline>");
                    679:                do {
1.30      deraadt   680:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt   681:                                SCREWUP("lost connection");
                    682:                        *cp++ = ch;
                    683:                } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
                    684:                *cp = 0;
                    685:
                    686:                if (buf[0] == '\01' || buf[0] == '\02') {
                    687:                        if (iamremote == 0)
1.29      deraadt   688:                                (void) atomicio(write, STDERR_FILENO,
1.44      deraadt   689:                                    buf + 1, strlen(buf + 1));
1.1       deraadt   690:                        if (buf[0] == '\02')
                    691:                                exit(1);
                    692:                        ++errs;
                    693:                        continue;
                    694:                }
                    695:                if (buf[0] == 'E') {
1.29      deraadt   696:                        (void) atomicio(write, remout, "", 1);
1.1       deraadt   697:                        return;
                    698:                }
                    699:                if (ch == '\n')
                    700:                        *--cp = 0;
                    701:
                    702:                cp = buf;
                    703:                if (*cp == 'T') {
                    704:                        setimes++;
                    705:                        cp++;
1.66    ! stevesk   706:                        mtime.tv_sec = strtol(cp, &cp, 10);
        !           707:                        if (!cp || *cp++ != ' ')
1.1       deraadt   708:                                SCREWUP("mtime.sec not delimited");
1.66    ! stevesk   709:                        mtime.tv_usec = strtol(cp, &cp, 10);
        !           710:                        if (!cp || *cp++ != ' ')
1.1       deraadt   711:                                SCREWUP("mtime.usec not delimited");
1.66    ! stevesk   712:                        atime.tv_sec = strtol(cp, &cp, 10);
        !           713:                        if (!cp || *cp++ != ' ')
1.1       deraadt   714:                                SCREWUP("atime.sec not delimited");
1.66    ! stevesk   715:                        atime.tv_usec = strtol(cp, &cp, 10);
        !           716:                        if (!cp || *cp++ != '\0')
1.1       deraadt   717:                                SCREWUP("atime.usec not delimited");
1.29      deraadt   718:                        (void) atomicio(write, remout, "", 1);
1.1       deraadt   719:                        continue;
                    720:                }
                    721:                if (*cp != 'C' && *cp != 'D') {
                    722:                        /*
                    723:                         * Check for the case "rcp remote:foo\* local:bar".
                    724:                         * In this case, the line "No match." can be returned
                    725:                         * by the shell before the rcp command on the remote is
                    726:                         * executed so the ^Aerror_message convention isn't
                    727:                         * followed.
                    728:                         */
                    729:                        if (first) {
                    730:                                run_err("%s", cp);
                    731:                                exit(1);
                    732:                        }
                    733:                        SCREWUP("expected control record");
                    734:                }
                    735:                mode = 0;
                    736:                for (++cp; cp < buf + 5; cp++) {
                    737:                        if (*cp < '0' || *cp > '7')
                    738:                                SCREWUP("bad mode");
                    739:                        mode = (mode << 3) | (*cp - '0');
                    740:                }
                    741:                if (*cp++ != ' ')
                    742:                        SCREWUP("mode not delimited");
                    743:
1.63      stevesk   744:                for (size = 0; isdigit(*cp);)
1.1       deraadt   745:                        size = size * 10 + (*cp++ - '0');
                    746:                if (*cp++ != ' ')
                    747:                        SCREWUP("size not delimited");
                    748:                if (targisdir) {
                    749:                        static char *namebuf;
                    750:                        static int cursize;
                    751:                        size_t need;
                    752:
                    753:                        need = strlen(targ) + strlen(cp) + 250;
1.55      deraadt   754:                        if (need > cursize) {
1.58      danh      755:                                if (namebuf)
                    756:                                        xfree(namebuf);
1.18      markus    757:                                namebuf = xmalloc(need);
1.55      deraadt   758:                                cursize = need;
                    759:                        }
                    760:                        (void) snprintf(namebuf, need, "%s%s%s", targ,
1.35      deraadt   761:                            *targ ? "/" : "", cp);
1.1       deraadt   762:                        np = namebuf;
                    763:                } else
                    764:                        np = targ;
1.12      aaron     765:                curfile = cp;
1.1       deraadt   766:                exists = stat(np, &stb) == 0;
                    767:                if (buf[0] == 'D') {
                    768:                        int mod_flag = pflag;
                    769:                        if (exists) {
                    770:                                if (!S_ISDIR(stb.st_mode)) {
                    771:                                        errno = ENOTDIR;
                    772:                                        goto bad;
                    773:                                }
                    774:                                if (pflag)
1.18      markus    775:                                        (void) chmod(np, mode);
1.1       deraadt   776:                        } else {
1.18      markus    777:                                /* Handle copying from a read-only
                    778:                                   directory */
1.1       deraadt   779:                                mod_flag = 1;
                    780:                                if (mkdir(np, mode | S_IRWXU) < 0)
                    781:                                        goto bad;
                    782:                        }
1.58      danh      783:                        vect[0] = xstrdup(np);
1.1       deraadt   784:                        sink(1, vect);
                    785:                        if (setimes) {
                    786:                                setimes = 0;
1.59      deraadt   787:                                if (utimes(vect[0], tv) < 0)
1.18      markus    788:                                        run_err("%s: set times: %s",
1.59      deraadt   789:                                            vect[0], strerror(errno));
1.1       deraadt   790:                        }
                    791:                        if (mod_flag)
1.59      deraadt   792:                                (void) chmod(vect[0], mode);
                    793:                        if (vect[0])
                    794:                                xfree(vect[0]);
1.1       deraadt   795:                        continue;
                    796:                }
                    797:                omode = mode;
                    798:                mode |= S_IWRITE;
1.18      markus    799:                if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
1.1       deraadt   800: bad:                   run_err("%s: %s", np, strerror(errno));
                    801:                        continue;
                    802:                }
1.29      deraadt   803:                (void) atomicio(write, remout, "", 1);
1.1       deraadt   804:                if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
1.18      markus    805:                        (void) close(ofd);
1.1       deraadt   806:                        continue;
                    807:                }
                    808:                cp = bp->buf;
                    809:                wrerr = NO;
1.7       deraadt   810:
                    811:                if (showprogress) {
                    812:                        totalbytes = size;
                    813:                        progressmeter(-1);
                    814:                }
1.12      aaron     815:                statbytes = 0;
1.1       deraadt   816:                for (count = i = 0; i < size; i += 4096) {
                    817:                        amt = 4096;
                    818:                        if (i + amt > size)
                    819:                                amt = size - i;
                    820:                        count += amt;
                    821:                        do {
1.43      markus    822:                                j = read(remin, cp, amt);
                    823:                                if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
                    824:                                        continue;
                    825:                                } else if (j <= 0) {
1.1       deraadt   826:                                        run_err("%s", j ? strerror(errno) :
1.63      stevesk   827:                                            "dropped connection");
1.1       deraadt   828:                                        exit(1);
                    829:                                }
                    830:                                amt -= j;
                    831:                                cp += j;
1.18      markus    832:                                statbytes += j;
1.1       deraadt   833:                        } while (amt > 0);
                    834:                        if (count == bp->cnt) {
                    835:                                /* Keep reading so we stay sync'd up. */
                    836:                                if (wrerr == NO) {
1.30      deraadt   837:                                        j = atomicio(write, ofd, bp->buf, count);
1.1       deraadt   838:                                        if (j != count) {
                    839:                                                wrerr = YES;
1.18      markus    840:                                                wrerrno = j >= 0 ? EIO : errno;
1.1       deraadt   841:                                        }
                    842:                                }
                    843:                                count = 0;
                    844:                                cp = bp->buf;
                    845:                        }
                    846:                }
1.7       deraadt   847:                if (showprogress)
                    848:                        progressmeter(1);
1.1       deraadt   849:                if (count != 0 && wrerr == NO &&
1.30      deraadt   850:                    (j = atomicio(write, ofd, bp->buf, count)) != count) {
1.1       deraadt   851:                        wrerr = YES;
1.18      markus    852:                        wrerrno = j >= 0 ? EIO : errno;
1.1       deraadt   853:                }
                    854: #if 0
                    855:                if (ftruncate(ofd, size)) {
                    856:                        run_err("%s: truncate: %s", np, strerror(errno));
                    857:                        wrerr = DISPLAYED;
                    858:                }
                    859: #endif
                    860:                if (pflag) {
                    861:                        if (exists || omode != mode)
                    862:                                if (fchmod(ofd, omode))
                    863:                                        run_err("%s: set mode: %s",
1.63      stevesk   864:                                            np, strerror(errno));
1.1       deraadt   865:                } else {
                    866:                        if (!exists && omode != mode)
                    867:                                if (fchmod(ofd, omode & ~mask))
                    868:                                        run_err("%s: set mode: %s",
1.63      stevesk   869:                                            np, strerror(errno));
1.1       deraadt   870:                }
1.33      provos    871:                if (close(ofd) == -1) {
                    872:                        wrerr = YES;
                    873:                        wrerrno = errno;
                    874:                }
1.18      markus    875:                (void) response();
1.1       deraadt   876:                if (setimes && wrerr == NO) {
                    877:                        setimes = 0;
1.40      markus    878:                        if (utimes(np, tv) < 0) {
1.1       deraadt   879:                                run_err("%s: set times: %s",
1.63      stevesk   880:                                    np, strerror(errno));
1.1       deraadt   881:                                wrerr = DISPLAYED;
                    882:                        }
                    883:                }
1.18      markus    884:                switch (wrerr) {
1.1       deraadt   885:                case YES:
                    886:                        run_err("%s: %s", np, strerror(wrerrno));
                    887:                        break;
                    888:                case NO:
1.29      deraadt   889:                        (void) atomicio(write, remout, "", 1);
1.1       deraadt   890:                        break;
                    891:                case DISPLAYED:
                    892:                        break;
                    893:                }
                    894:        }
                    895: screwup:
                    896:        run_err("protocol error: %s", why);
                    897:        exit(1);
                    898: }
                    899:
                    900: int
                    901: response()
                    902: {
                    903:        char ch, *cp, resp, rbuf[2048];
                    904:
1.30      deraadt   905:        if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1.1       deraadt   906:                lostconn(0);
                    907:
                    908:        cp = rbuf;
1.18      markus    909:        switch (resp) {
                    910:        case 0:         /* ok */
1.1       deraadt   911:                return (0);
                    912:        default:
                    913:                *cp++ = resp;
                    914:                /* FALLTHROUGH */
1.18      markus    915:        case 1:         /* error, followed by error msg */
                    916:        case 2:         /* fatal error, "" */
1.1       deraadt   917:                do {
1.30      deraadt   918:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt   919:                                lostconn(0);
                    920:                        *cp++ = ch;
                    921:                } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
                    922:
                    923:                if (!iamremote)
1.29      deraadt   924:                        (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
1.1       deraadt   925:                ++errs;
                    926:                if (resp == 1)
                    927:                        return (-1);
                    928:                exit(1);
                    929:        }
                    930:        /* NOTREACHED */
                    931: }
                    932:
                    933: void
                    934: usage()
                    935: {
1.34      deraadt   936:        (void) fprintf(stderr, "usage: scp "
1.64      stevesk   937:            "[-pqrvBC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2\n"
                    938:            "   or: scp [options] f1 ... fn directory\n");
1.1       deraadt   939:        exit(1);
                    940: }
                    941:
                    942: void
1.18      markus    943: run_err(const char *fmt,...)
1.1       deraadt   944: {
                    945:        static FILE *fp;
                    946:        va_list ap;
                    947:        va_start(ap, fmt);
                    948:
                    949:        ++errs;
                    950:        if (fp == NULL && !(fp = fdopen(remout, "w")))
                    951:                return;
1.18      markus    952:        (void) fprintf(fp, "%c", 0x01);
                    953:        (void) fprintf(fp, "scp: ");
                    954:        (void) vfprintf(fp, fmt, ap);
                    955:        (void) fprintf(fp, "\n");
                    956:        (void) fflush(fp);
                    957:
                    958:        if (!iamremote) {
                    959:                vfprintf(stderr, fmt, ap);
                    960:                fprintf(stderr, "\n");
                    961:        }
1.1       deraadt   962:        va_end(ap);
                    963: }
                    964:
                    965: char *
                    966: colon(cp)
                    967:        char *cp;
                    968: {
1.23      markus    969:        int flag = 0;
                    970:
1.1       deraadt   971:        if (*cp == ':')         /* Leading colon is part of file name. */
                    972:                return (0);
1.23      markus    973:        if (*cp == '[')
                    974:                flag = 1;
1.1       deraadt   975:
                    976:        for (; *cp; ++cp) {
1.23      markus    977:                if (*cp == '@' && *(cp+1) == '[')
                    978:                        flag = 1;
                    979:                if (*cp == ']' && *(cp+1) == ':' && flag)
                    980:                        return (cp+1);
                    981:                if (*cp == ':' && !flag)
1.1       deraadt   982:                        return (cp);
                    983:                if (*cp == '/')
                    984:                        return (0);
                    985:        }
                    986:        return (0);
                    987: }
                    988:
                    989: void
                    990: verifydir(cp)
                    991:        char *cp;
                    992: {
                    993:        struct stat stb;
                    994:
                    995:        if (!stat(cp, &stb)) {
                    996:                if (S_ISDIR(stb.st_mode))
                    997:                        return;
                    998:                errno = ENOTDIR;
                    999:        }
                   1000:        run_err("%s: %s", cp, strerror(errno));
                   1001:        exit(1);
                   1002: }
                   1003:
                   1004: int
                   1005: okname(cp0)
                   1006:        char *cp0;
                   1007: {
                   1008:        int c;
                   1009:        char *cp;
                   1010:
                   1011:        cp = cp0;
                   1012:        do {
                   1013:                c = *cp;
                   1014:                if (c & 0200)
                   1015:                        goto bad;
1.46      markus   1016:                if (!isalpha(c) && !isdigit(c) &&
                   1017:                    c != '_' && c != '-' && c != '.' && c != '+')
1.1       deraadt  1018:                        goto bad;
                   1019:        } while (*++cp);
                   1020:        return (1);
                   1021:
1.25      markus   1022: bad:   fprintf(stderr, "%s: invalid user name\n", cp0);
1.1       deraadt  1023:        return (0);
                   1024: }
                   1025:
                   1026: BUF *
                   1027: allocbuf(bp, fd, blksize)
                   1028:        BUF *bp;
                   1029:        int fd, blksize;
                   1030: {
                   1031:        size_t size;
                   1032:        struct stat stb;
                   1033:
                   1034:        if (fstat(fd, &stb) < 0) {
                   1035:                run_err("fstat: %s", strerror(errno));
                   1036:                return (0);
                   1037:        }
1.18      markus   1038:        if (stb.st_blksize == 0)
                   1039:                size = blksize;
                   1040:        else
                   1041:                size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1.35      deraadt  1042:                    stb.st_blksize;
1.1       deraadt  1043:        if (bp->cnt >= size)
                   1044:                return (bp);
1.18      markus   1045:        if (bp->buf == NULL)
                   1046:                bp->buf = xmalloc(size);
                   1047:        else
                   1048:                bp->buf = xrealloc(bp->buf, size);
1.1       deraadt  1049:        bp->cnt = size;
                   1050:        return (bp);
                   1051: }
                   1052:
                   1053: void
                   1054: lostconn(signo)
                   1055:        int signo;
                   1056: {
                   1057:        if (!iamremote)
                   1058:                fprintf(stderr, "lost connection\n");
                   1059:        exit(1);
                   1060: }
1.4       aaron    1061:
1.10      deraadt  1062:
1.8       deraadt  1063: void
                   1064: alarmtimer(int wait)
1.4       aaron    1065: {
1.18      markus   1066:        struct itimerval itv;
1.4       aaron    1067:
1.18      markus   1068:        itv.it_value.tv_sec = wait;
                   1069:        itv.it_value.tv_usec = 0;
                   1070:        itv.it_interval = itv.it_value;
                   1071:        setitimer(ITIMER_REAL, &itv, NULL);
1.4       aaron    1072: }
                   1073:
1.8       deraadt  1074: void
1.26      markus   1075: updateprogressmeter(int ignore)
1.4       aaron    1076: {
1.9       deraadt  1077:        int save_errno = errno;
                   1078:
1.4       aaron    1079:        progressmeter(0);
1.9       deraadt  1080:        errno = save_errno;
1.4       aaron    1081: }
                   1082:
1.16      deraadt  1083: int
1.56      itojun   1084: foregroundproc(void)
1.16      deraadt  1085: {
                   1086:        static pid_t pgrp = -1;
                   1087:        int ctty_pgrp;
                   1088:
                   1089:        if (pgrp == -1)
                   1090:                pgrp = getpgrp();
                   1091:
1.18      markus   1092:        return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
                   1093:                 ctty_pgrp == pgrp));
1.16      deraadt  1094: }
                   1095:
1.8       deraadt  1096: void
                   1097: progressmeter(int flag)
1.4       aaron    1098: {
                   1099:        static const char prefixes[] = " KMGTP";
                   1100:        static struct timeval lastupdate;
1.11      aaron    1101:        static off_t lastsize;
1.4       aaron    1102:        struct timeval now, td, wait;
                   1103:        off_t cursize, abbrevsize;
                   1104:        double elapsed;
                   1105:        int ratio, barlength, i, remaining;
                   1106:        char buf[256];
                   1107:
                   1108:        if (flag == -1) {
1.18      markus   1109:                (void) gettimeofday(&start, (struct timezone *) 0);
1.4       aaron    1110:                lastupdate = start;
1.11      aaron    1111:                lastsize = 0;
1.18      markus   1112:        }
1.16      deraadt  1113:        if (foregroundproc() == 0)
                   1114:                return;
                   1115:
1.18      markus   1116:        (void) gettimeofday(&now, (struct timezone *) 0);
1.4       aaron    1117:        cursize = statbytes;
1.13      aaron    1118:        if (totalbytes != 0) {
1.21      markus   1119:                ratio = 100.0 * cursize / totalbytes;
1.13      aaron    1120:                ratio = MAX(ratio, 0);
                   1121:                ratio = MIN(ratio, 100);
1.18      markus   1122:        } else
1.13      aaron    1123:                ratio = 100;
                   1124:
1.18      markus   1125:        snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1.4       aaron    1126:
1.11      aaron    1127:        barlength = getttywidth() - 51;
1.4       aaron    1128:        if (barlength > 0) {
                   1129:                i = barlength * ratio / 100;
                   1130:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.35      deraadt  1131:                    "|%.*s%*s|", i,
                   1132:                    "*****************************************************************************"
                   1133:                    "*****************************************************************************",
                   1134:                    barlength - i, "");
1.4       aaron    1135:        }
                   1136:        i = 0;
                   1137:        abbrevsize = cursize;
                   1138:        while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
                   1139:                i++;
                   1140:                abbrevsize >>= 10;
                   1141:        }
1.54      itojun   1142:        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5llu %c%c ",
1.53      deraadt  1143:            (unsigned long long) abbrevsize, prefixes[i],
                   1144:            prefixes[i] == ' ' ? ' ' : 'B');
1.4       aaron    1145:
                   1146:        timersub(&now, &lastupdate, &wait);
                   1147:        if (cursize > lastsize) {
                   1148:                lastupdate = now;
                   1149:                lastsize = cursize;
                   1150:                if (wait.tv_sec >= STALLTIME) {
                   1151:                        start.tv_sec += wait.tv_sec;
                   1152:                        start.tv_usec += wait.tv_usec;
                   1153:                }
                   1154:                wait.tv_sec = 0;
                   1155:        }
                   1156:        timersub(&now, &start, &td);
1.6       aaron    1157:        elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1.4       aaron    1158:
1.44      deraadt  1159:        if (flag != 1 &&
                   1160:            (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
1.4       aaron    1161:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.44      deraadt  1162:                    "   --:-- ETA");
1.4       aaron    1163:        } else if (wait.tv_sec >= STALLTIME) {
                   1164:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.44      deraadt  1165:                    " - stalled -");
1.4       aaron    1166:        } else {
1.28      deraadt  1167:                if (flag != 1)
1.44      deraadt  1168:                        remaining = (int)(totalbytes / (statbytes / elapsed) -
                   1169:                            elapsed);
1.28      deraadt  1170:                else
                   1171:                        remaining = elapsed;
                   1172:
1.14      aaron    1173:                i = remaining / 3600;
1.4       aaron    1174:                if (i)
                   1175:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.35      deraadt  1176:                            "%2d:", i);
1.4       aaron    1177:                else
                   1178:                        snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.35      deraadt  1179:                            "   ");
1.4       aaron    1180:                i = remaining % 3600;
                   1181:                snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1.35      deraadt  1182:                    "%02d:%02d%s", i / 60, i % 60,
                   1183:                    (flag != 1) ? " ETA" : "    ");
1.4       aaron    1184:        }
1.10      deraadt  1185:        atomicio(write, fileno(stdout), buf, strlen(buf));
1.4       aaron    1186:
                   1187:        if (flag == -1) {
1.26      markus   1188:                signal(SIGALRM, updateprogressmeter);
1.4       aaron    1189:                alarmtimer(1);
                   1190:        } else if (flag == 1) {
1.10      deraadt  1191:                alarmtimer(0);
1.29      deraadt  1192:                atomicio(write, fileno(stdout), "\n", 1);
1.12      aaron    1193:                statbytes = 0;
1.4       aaron    1194:        }
                   1195: }
                   1196:
1.8       deraadt  1197: int
                   1198: getttywidth(void)
1.4       aaron    1199: {
                   1200:        struct winsize winsize;
                   1201:
                   1202:        if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1.18      markus   1203:                return (winsize.ws_col ? winsize.ws_col : 80);
1.4       aaron    1204:        else
1.18      markus   1205:                return (80);
1.41      markus   1206: }
                   1207:
                   1208: void
                   1209: addargs(char *fmt, ...)
                   1210: {
                   1211:        va_list ap;
                   1212:        char buf[1024];
                   1213:
                   1214:        va_start(ap, fmt);
                   1215:        vsnprintf(buf, sizeof(buf), fmt, ap);
                   1216:        va_end(ap);
                   1217:
                   1218:        if (args.list == NULL) {
                   1219:                args.nalloc = 32;
                   1220:                args.num = 0;
                   1221:                args.list = xmalloc(args.nalloc * sizeof(char *));
                   1222:        } else if (args.num+2 >= args.nalloc) {
                   1223:                args.nalloc *= 2;
                   1224:                args.list = xrealloc(args.list, args.nalloc * sizeof(char *));
                   1225:        }
                   1226:        args.list[args.num++] = xstrdup(buf);
                   1227:        args.list[args.num] = NULL;
1.4       aaron    1228: }