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

1.187   ! deraadt     1: /* $OpenBSD: scp.c,v 1.186 2016/05/25 23:48:45 schwarze Exp $ */
1.1       deraadt     2: /*
1.38      deraadt     3:  * scp - secure remote copy.  This is basically patched BSD rcp which
                      4:  * uses ssh to do the data transfer (instead of using rcmd).
1.27      markus      5:  *
1.38      deraadt     6:  * NOTE: This version should NOT be suid root.  (This uses ssh to
                      7:  * do the transfer and ssh has the necessary privileges.)
1.27      markus      8:  *
1.38      deraadt     9:  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
                     10:  *
                     11:  * As far as I am concerned, the code I have written for this software
                     12:  * can be used freely for any purpose.  Any derived versions of this
                     13:  * software must be clearly marked as such, and if the derived work is
                     14:  * incompatible with the protocol description in the RFC file, it must be
                     15:  * called by a name other than "ssh" or "Secure Shell".
1.39      markus     16:  */
1.38      deraadt    17: /*
1.60      deraadt    18:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     19:  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
1.27      markus     20:  *
1.38      deraadt    21:  * Redistribution and use in source and binary forms, with or without
                     22:  * modification, are permitted provided that the following conditions
                     23:  * are met:
                     24:  * 1. Redistributions of source code must retain the above copyright
                     25:  *    notice, this list of conditions and the following disclaimer.
                     26:  * 2. Redistributions in binary form must reproduce the above copyright
                     27:  *    notice, this list of conditions and the following disclaimer in the
                     28:  *    documentation and/or other materials provided with the distribution.
1.27      markus     29:  *
1.38      deraadt    30:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     31:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     32:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     33:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     34:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     35:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     36:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     37:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     38:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     39:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
                     40:  */
1.1       deraadt    41:
                     42: /*
1.35      deraadt    43:  * Parts from:
                     44:  *
1.1       deraadt    45:  * Copyright (c) 1983, 1990, 1992, 1993, 1995
                     46:  *     The Regents of the University of California.  All rights reserved.
                     47:  *
                     48:  * Redistribution and use in source and binary forms, with or without
                     49:  * modification, are permitted provided that the following conditions
                     50:  * are met:
                     51:  * 1. Redistributions of source code must retain the above copyright
                     52:  *    notice, this list of conditions and the following disclaimer.
                     53:  * 2. Redistributions in binary form must reproduce the above copyright
                     54:  *    notice, this list of conditions and the following disclaimer in the
                     55:  *    documentation and/or other materials provided with the distribution.
1.103     millert    56:  * 3. Neither the name of the University nor the names of its contributors
1.1       deraadt    57:  *    may be used to endorse or promote products derived from this software
                     58:  *    without specific prior written permission.
                     59:  *
                     60:  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
                     61:  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
                     62:  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
                     63:  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
                     64:  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
                     65:  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
                     66:  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
                     67:  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
                     68:  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
                     69:  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
                     70:  * SUCH DAMAGE.
                     71:  *
                     72:  */
                     73:
1.132     stevesk    74: #include <sys/types.h>
1.161     djm        75: #include <sys/poll.h>
1.132     stevesk    76: #include <sys/wait.h>
1.134     stevesk    77: #include <sys/stat.h>
1.151     stevesk    78: #include <sys/time.h>
1.155     deraadt    79: #include <sys/uio.h>
1.131     stevesk    80:
1.135     stevesk    81: #include <ctype.h>
1.131     stevesk    82: #include <dirent.h>
1.147     stevesk    83: #include <errno.h>
1.144     stevesk    84: #include <fcntl.h>
1.186     schwarze   85: #include <locale.h>
1.143     stevesk    86: #include <pwd.h>
1.133     stevesk    87: #include <signal.h>
1.146     stevesk    88: #include <stdarg.h>
1.154     stevesk    89: #include <stdio.h>
1.153     stevesk    90: #include <stdlib.h>
1.150     stevesk    91: #include <string.h>
1.149     stevesk    92: #include <time.h>
1.148     stevesk    93: #include <unistd.h>
1.181     deraadt    94: #include <limits.h>
1.158     dtucker    95: #include <vis.h>
1.1       deraadt    96:
                     97: #include "xmalloc.h"
1.51      markus     98: #include "atomicio.h"
1.50      markus     99: #include "pathnames.h"
1.51      markus    100: #include "log.h"
1.69      mouring   101: #include "misc.h"
1.97      fgsch     102: #include "progressmeter.h"
1.186     schwarze  103: #include "utf8.h"
1.1       deraadt   104:
1.161     djm       105: #define COPY_BUFLEN    16384
                    106:
1.140     deraadt   107: int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
1.169     markus    108: int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
1.11      aaron     109:
1.70      mouring   110: /* Struct for addargs */
                    111: arglist args;
1.168     djm       112: arglist remote_remote_args;
1.41      markus    113:
1.99      markus    114: /* Bandwidth limit */
1.167     djm       115: long long limit_kbps = 0;
                    116: struct bwlimit bwlimit;
1.99      markus    117:
1.11      aaron     118: /* Name of current file being transferred. */
                    119: char *curfile;
1.4       aaron     120:
1.1       deraadt   121: /* This is set to non-zero to enable verbose mode. */
1.17      markus    122: int verbose_mode = 0;
1.1       deraadt   123:
1.6       aaron     124: /* This is set to zero if the progressmeter is not desired. */
                    125: int showprogress = 1;
                    126:
1.169     markus    127: /*
                    128:  * This is set to non-zero if remote-remote copy should be piped
                    129:  * through this process.
                    130:  */
                    131: int throughlocal = 0;
                    132:
1.34      deraadt   133: /* This is the program to execute for the secured connection. ("ssh" or -S) */
1.50      markus    134: char *ssh_program = _PATH_SSH_PROGRAM;
1.34      deraadt   135:
1.92      markus    136: /* This is used to store the pid of ssh_program */
1.105     djm       137: pid_t do_cmd_pid = -1;
                    138:
                    139: static void
                    140: killchild(int signo)
                    141: {
1.119     dtucker   142:        if (do_cmd_pid > 1) {
1.123     avsm      143:                kill(do_cmd_pid, signo ? signo : SIGTERM);
1.119     dtucker   144:                waitpid(do_cmd_pid, NULL, 0);
                    145:        }
1.105     djm       146:
1.123     avsm      147:        if (signo)
                    148:                _exit(1);
                    149:        exit(1);
1.105     djm       150: }
1.92      markus    151:
1.166     millert   152: static void
                    153: suspchild(int signo)
                    154: {
                    155:        int status;
                    156:
                    157:        if (do_cmd_pid > 1) {
                    158:                kill(do_cmd_pid, signo);
                    159:                while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
                    160:                    errno == EINTR)
                    161:                        ;
                    162:                kill(getpid(), SIGSTOP);
                    163:        }
                    164: }
                    165:
1.129     djm       166: static int
                    167: do_local_cmd(arglist *a)
                    168: {
                    169:        u_int i;
                    170:        int status;
                    171:        pid_t pid;
                    172:
                    173:        if (a->num == 0)
                    174:                fatal("do_local_cmd: no arguments");
                    175:
                    176:        if (verbose_mode) {
                    177:                fprintf(stderr, "Executing:");
                    178:                for (i = 0; i < a->num; i++)
1.186     schwarze  179:                        fmprintf(stderr, " %s", a->list[i]);
1.129     djm       180:                fprintf(stderr, "\n");
                    181:        }
                    182:        if ((pid = fork()) == -1)
                    183:                fatal("do_local_cmd: fork: %s", strerror(errno));
                    184:
                    185:        if (pid == 0) {
                    186:                execvp(a->list[0], a->list);
                    187:                perror(a->list[0]);
                    188:                exit(1);
                    189:        }
                    190:
                    191:        do_cmd_pid = pid;
                    192:        signal(SIGTERM, killchild);
                    193:        signal(SIGINT, killchild);
                    194:        signal(SIGHUP, killchild);
                    195:
                    196:        while (waitpid(pid, &status, 0) == -1)
                    197:                if (errno != EINTR)
                    198:                        fatal("do_local_cmd: waitpid: %s", strerror(errno));
                    199:
                    200:        do_cmd_pid = -1;
                    201:
                    202:        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
                    203:                return (-1);
                    204:
                    205:        return (0);
                    206: }
                    207:
1.20      markus    208: /*
                    209:  * This function executes the given command as the specified user on the
                    210:  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
                    211:  * assigns the input and output file descriptors on success.
                    212:  */
1.1       deraadt   213:
1.27      markus    214: int
1.140     deraadt   215: do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
1.1       deraadt   216: {
1.18      markus    217:        int pin[2], pout[2], reserved[2];
                    218:
                    219:        if (verbose_mode)
1.186     schwarze  220:                fmprintf(stderr,
1.78      deraadt   221:                    "Executing: program %s host %s, user %s, command %s\n",
                    222:                    ssh_program, host,
                    223:                    remuser ? remuser : "(unspecified)", cmd);
1.18      markus    224:
1.20      markus    225:        /*
                    226:         * Reserve two descriptors so that the real pipes won't get
                    227:         * descriptors 0 and 1 because that will screw up dup2 below.
                    228:         */
1.142     markus    229:        if (pipe(reserved) < 0)
                    230:                fatal("pipe: %s", strerror(errno));
1.18      markus    231:
                    232:        /* Create a socket pair for communicating with ssh. */
                    233:        if (pipe(pin) < 0)
                    234:                fatal("pipe: %s", strerror(errno));
                    235:        if (pipe(pout) < 0)
                    236:                fatal("pipe: %s", strerror(errno));
                    237:
                    238:        /* Free the reserved descriptors. */
                    239:        close(reserved[0]);
                    240:        close(reserved[1]);
1.166     millert   241:
                    242:        signal(SIGTSTP, suspchild);
                    243:        signal(SIGTTIN, suspchild);
                    244:        signal(SIGTTOU, suspchild);
1.18      markus    245:
1.106     nino      246:        /* Fork a child to execute the command on the remote host using ssh. */
1.92      markus    247:        do_cmd_pid = fork();
                    248:        if (do_cmd_pid == 0) {
1.18      markus    249:                /* Child. */
                    250:                close(pin[1]);
                    251:                close(pout[0]);
                    252:                dup2(pin[0], 0);
                    253:                dup2(pout[1], 1);
                    254:                close(pin[0]);
                    255:                close(pout[1]);
                    256:
1.129     djm       257:                replacearg(&args, 0, "%s", ssh_program);
1.165     guenther  258:                if (remuser != NULL) {
                    259:                        addargs(&args, "-l");
                    260:                        addargs(&args, "%s", remuser);
                    261:                }
                    262:                addargs(&args, "--");
1.70      mouring   263:                addargs(&args, "%s", host);
                    264:                addargs(&args, "%s", cmd);
1.18      markus    265:
1.41      markus    266:                execvp(ssh_program, args.list);
1.34      deraadt   267:                perror(ssh_program);
1.18      markus    268:                exit(1);
1.92      markus    269:        } else if (do_cmd_pid == -1) {
                    270:                fatal("fork: %s", strerror(errno));
1.18      markus    271:        }
                    272:        /* Parent.  Close the other side, and return the local side. */
                    273:        close(pin[0]);
                    274:        *fdout = pin[1];
                    275:        close(pout[1]);
                    276:        *fdin = pout[0];
1.105     djm       277:        signal(SIGTERM, killchild);
                    278:        signal(SIGINT, killchild);
                    279:        signal(SIGHUP, killchild);
1.18      markus    280:        return 0;
1.1       deraadt   281: }
                    282:
1.169     markus    283: /*
                    284:  * This functions executes a command simlar to do_cmd(), but expects the
                    285:  * input and output descriptors to be setup by a previous call to do_cmd().
                    286:  * This way the input and output of two commands can be connected.
                    287:  */
                    288: int
                    289: do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
                    290: {
                    291:        pid_t pid;
                    292:        int status;
                    293:
                    294:        if (verbose_mode)
1.186     schwarze  295:                fmprintf(stderr,
1.169     markus    296:                    "Executing: 2nd program %s host %s, user %s, command %s\n",
                    297:                    ssh_program, host,
                    298:                    remuser ? remuser : "(unspecified)", cmd);
                    299:
                    300:        /* Fork a child to execute the command on the remote host using ssh. */
                    301:        pid = fork();
                    302:        if (pid == 0) {
                    303:                dup2(fdin, 0);
                    304:                dup2(fdout, 1);
                    305:
                    306:                replacearg(&args, 0, "%s", ssh_program);
                    307:                if (remuser != NULL) {
                    308:                        addargs(&args, "-l");
                    309:                        addargs(&args, "%s", remuser);
                    310:                }
                    311:                addargs(&args, "--");
                    312:                addargs(&args, "%s", host);
                    313:                addargs(&args, "%s", cmd);
                    314:
                    315:                execvp(ssh_program, args.list);
                    316:                perror(ssh_program);
                    317:                exit(1);
                    318:        } else if (pid == -1) {
                    319:                fatal("fork: %s", strerror(errno));
                    320:        }
                    321:        while (waitpid(pid, &status, 0) == -1)
                    322:                if (errno != EINTR)
                    323:                        fatal("do_cmd2: waitpid: %s", strerror(errno));
                    324:        return 0;
                    325: }
                    326:
1.1       deraadt   327: typedef struct {
1.124     djm       328:        size_t cnt;
1.1       deraadt   329:        char *buf;
                    330: } BUF;
                    331:
1.18      markus    332: BUF *allocbuf(BUF *, int, int);
                    333: void lostconn(int);
                    334: int okname(char *);
                    335: void run_err(const char *,...);
                    336: void verifydir(char *);
1.1       deraadt   337:
                    338: struct passwd *pwd;
1.18      markus    339: uid_t userid;
1.1       deraadt   340: int errs, remin, remout;
                    341: int pflag, iamremote, iamrecursive, targetshouldbedirectory;
                    342:
                    343: #define        CMDNEEDS        64
                    344: char cmd[CMDNEEDS];            /* must hold "rcp -r -p -d\0" */
                    345:
1.18      markus    346: int response(void);
                    347: void rsource(char *, struct stat *);
                    348: void sink(int, char *[]);
                    349: void source(int, char *[]);
                    350: void tolocal(int, char *[]);
                    351: void toremote(char *, int, char *[]);
                    352: void usage(void);
1.1       deraadt   353:
                    354: int
1.104     djm       355: main(int argc, char **argv)
1.1       deraadt   356: {
1.145     djm       357:        int ch, fflag, tflag, status, n;
1.167     djm       358:        char *targ, **newargv;
                    359:        const char *errstr;
1.1       deraadt   360:        extern char *optarg;
                    361:        extern int optind;
1.126     djm       362:
                    363:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    364:        sanitise_stdfd();
1.145     djm       365:
1.186     schwarze  366:        setlocale(LC_CTYPE, "");
                    367:
1.145     djm       368:        /* Copy argv, because we modify it */
1.187   ! deraadt   369:        newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
1.145     djm       370:        for (n = 0; n < argc; n++)
                    371:                newargv[n] = xstrdup(argv[n]);
                    372:        argv = newargv;
1.1       deraadt   373:
1.129     djm       374:        memset(&args, '\0', sizeof(args));
1.168     djm       375:        memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
                    376:        args.list = remote_remote_args.list = NULL;
1.129     djm       377:        addargs(&args, "%s", ssh_program);
1.70      mouring   378:        addargs(&args, "-x");
1.168     djm       379:        addargs(&args, "-oForwardAgent=no");
                    380:        addargs(&args, "-oPermitLocalCommand=no");
                    381:        addargs(&args, "-oClearAllForwardings=yes");
1.41      markus    382:
1.1       deraadt   383:        fflag = tflag = 0;
1.169     markus    384:        while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
1.18      markus    385:                switch (ch) {
                    386:                /* User-visible flags. */
1.100     markus    387:                case '1':
                    388:                case '2':
1.23      markus    389:                case '4':
1.41      markus    390:                case '6':
                    391:                case 'C':
1.70      mouring   392:                        addargs(&args, "-%c", ch);
1.168     djm       393:                        addargs(&remote_remote_args, "-%c", ch);
1.41      markus    394:                        break;
1.169     markus    395:                case '3':
                    396:                        throughlocal = 1;
                    397:                        break;
1.41      markus    398:                case 'o':
                    399:                case 'c':
                    400:                case 'i':
1.83      stevesk   401:                case 'F':
1.168     djm       402:                        addargs(&remote_remote_args, "-%c", ch);
                    403:                        addargs(&remote_remote_args, "%s", optarg);
1.165     guenther  404:                        addargs(&args, "-%c", ch);
                    405:                        addargs(&args, "%s", optarg);
1.23      markus    406:                        break;
1.41      markus    407:                case 'P':
1.168     djm       408:                        addargs(&remote_remote_args, "-p");
                    409:                        addargs(&remote_remote_args, "%s", optarg);
1.165     guenther  410:                        addargs(&args, "-p");
                    411:                        addargs(&args, "%s", optarg);
1.41      markus    412:                        break;
                    413:                case 'B':
1.168     djm       414:                        addargs(&remote_remote_args, "-oBatchmode=yes");
                    415:                        addargs(&args, "-oBatchmode=yes");
1.23      markus    416:                        break;
1.99      markus    417:                case 'l':
1.167     djm       418:                        limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
                    419:                            &errstr);
                    420:                        if (errstr != NULL)
1.99      markus    421:                                usage();
1.167     djm       422:                        limit_kbps *= 1024; /* kbps */
                    423:                        bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
1.99      markus    424:                        break;
1.1       deraadt   425:                case 'p':
                    426:                        pflag = 1;
                    427:                        break;
                    428:                case 'r':
                    429:                        iamrecursive = 1;
                    430:                        break;
1.34      deraadt   431:                case 'S':
1.41      markus    432:                        ssh_program = xstrdup(optarg);
                    433:                        break;
                    434:                case 'v':
1.72      markus    435:                        addargs(&args, "-v");
1.168     djm       436:                        addargs(&remote_remote_args, "-v");
1.41      markus    437:                        verbose_mode = 1;
                    438:                        break;
                    439:                case 'q':
1.111     dtucker   440:                        addargs(&args, "-q");
1.168     djm       441:                        addargs(&remote_remote_args, "-q");
1.41      markus    442:                        showprogress = 0;
1.34      deraadt   443:                        break;
                    444:
1.18      markus    445:                /* Server options. */
1.1       deraadt   446:                case 'd':
                    447:                        targetshouldbedirectory = 1;
                    448:                        break;
1.18      markus    449:                case 'f':       /* "from" */
1.1       deraadt   450:                        iamremote = 1;
                    451:                        fflag = 1;
                    452:                        break;
1.18      markus    453:                case 't':       /* "to" */
1.1       deraadt   454:                        iamremote = 1;
                    455:                        tflag = 1;
                    456:                        break;
                    457:                default:
                    458:                        usage();
                    459:                }
                    460:        argc -= optind;
                    461:        argv += optind;
                    462:
                    463:        if ((pwd = getpwuid(userid = getuid())) == NULL)
1.108     deraadt   464:                fatal("unknown user %u", (u_int) userid);
1.1       deraadt   465:
1.156     djm       466:        if (!isatty(STDOUT_FILENO))
1.7       deraadt   467:                showprogress = 0;
1.184     deraadt   468:
                    469:        if (pflag) {
                    470:                /* Cannot pledge: -p allows setuid/setgid files... */
                    471:        } else {
                    472:                if (pledge("stdio rpath wpath cpath fattr tty proc exec",
                    473:                    NULL) == -1) {
                    474:                        perror("pledge");
                    475:                        exit(1);
                    476:                }
                    477:        }
1.7       deraadt   478:
1.1       deraadt   479:        remin = STDIN_FILENO;
                    480:        remout = STDOUT_FILENO;
                    481:
1.52      stevesk   482:        if (fflag) {
1.18      markus    483:                /* Follow "protocol", send data. */
                    484:                (void) response();
1.1       deraadt   485:                source(argc, argv);
                    486:                exit(errs != 0);
                    487:        }
1.18      markus    488:        if (tflag) {
                    489:                /* Receive data. */
1.1       deraadt   490:                sink(argc, argv);
                    491:                exit(errs != 0);
                    492:        }
                    493:        if (argc < 2)
                    494:                usage();
                    495:        if (argc > 2)
                    496:                targetshouldbedirectory = 1;
                    497:
                    498:        remin = remout = -1;
1.92      markus    499:        do_cmd_pid = -1;
1.1       deraadt   500:        /* Command to be executed on remote system using "ssh". */
1.55      deraadt   501:        (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
                    502:            verbose_mode ? " -v" : "",
1.35      deraadt   503:            iamrecursive ? " -r" : "", pflag ? " -p" : "",
                    504:            targetshouldbedirectory ? " -d" : "");
1.1       deraadt   505:
1.18      markus    506:        (void) signal(SIGPIPE, lostconn);
1.1       deraadt   507:
                    508:        if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
                    509:                toremote(targ, argc, argv);
                    510:        else {
                    511:                if (targetshouldbedirectory)
                    512:                        verifydir(argv[argc - 1]);
1.130     djm       513:                tolocal(argc, argv);    /* Dest is local host. */
1.92      markus    514:        }
                    515:        /*
                    516:         * Finally check the exit status of the ssh process, if one was forked
1.164     stevesk   517:         * and no error has occurred yet
1.92      markus    518:         */
                    519:        if (do_cmd_pid != -1 && errs == 0) {
                    520:                if (remin != -1)
                    521:                    (void) close(remin);
                    522:                if (remout != -1)
                    523:                    (void) close(remout);
                    524:                if (waitpid(do_cmd_pid, &status, 0) == -1)
                    525:                        errs = 1;
                    526:                else {
                    527:                        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
                    528:                                errs = 1;
                    529:                }
1.1       deraadt   530:        }
                    531:        exit(errs != 0);
                    532: }
                    533:
1.167     djm       534: /* Callback from atomicio6 to update progress meter and limit bandwidth */
                    535: static int
                    536: scpio(void *_cnt, size_t s)
1.161     djm       537: {
1.167     djm       538:        off_t *cnt = (off_t *)_cnt;
                    539:
                    540:        *cnt += s;
                    541:        if (limit_kbps > 0)
                    542:                bandwidth_limit(&bwlimit, s);
                    543:        return 0;
1.161     djm       544: }
                    545:
1.176     guenther  546: static int
                    547: do_times(int fd, int verb, const struct stat *sb)
                    548: {
                    549:        /* strlen(2^64) == 20; strlen(10^6) == 7 */
                    550:        char buf[(20 + 7 + 2) * 2 + 2];
                    551:
                    552:        (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
                    553:            (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
                    554:            (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
                    555:        if (verb) {
                    556:                fprintf(stderr, "File mtime %lld atime %lld\n",
                    557:                    (long long)sb->st_mtime, (long long)sb->st_atime);
                    558:                fprintf(stderr, "Sending file timestamps: %s", buf);
                    559:        }
                    560:        (void) atomicio(vwrite, fd, buf, strlen(buf));
                    561:        return (response());
                    562: }
                    563:
1.1       deraadt   564: void
1.104     djm       565: toremote(char *targ, int argc, char **argv)
1.1       deraadt   566: {
1.120     deraadt   567:        char *bp, *host, *src, *suser, *thost, *tuser, *arg;
1.129     djm       568:        arglist alist;
1.140     deraadt   569:        int i;
1.168     djm       570:        u_int j;
1.129     djm       571:
                    572:        memset(&alist, '\0', sizeof(alist));
                    573:        alist.list = NULL;
1.1       deraadt   574:
                    575:        *targ++ = 0;
                    576:        if (*targ == 0)
                    577:                targ = ".";
                    578:
1.121     djm       579:        arg = xstrdup(argv[argc - 1]);
1.120     deraadt   580:        if ((thost = strrchr(arg, '@'))) {
1.1       deraadt   581:                /* user@host */
                    582:                *thost++ = 0;
1.120     deraadt   583:                tuser = arg;
1.1       deraadt   584:                if (*tuser == '\0')
                    585:                        tuser = NULL;
                    586:        } else {
1.120     deraadt   587:                thost = arg;
1.1       deraadt   588:                tuser = NULL;
                    589:        }
                    590:
1.129     djm       591:        if (tuser != NULL && !okname(tuser)) {
1.173     djm       592:                free(arg);
1.129     djm       593:                return;
                    594:        }
                    595:
1.1       deraadt   596:        for (i = 0; i < argc - 1; i++) {
                    597:                src = colon(argv[i]);
1.169     markus    598:                if (src && throughlocal) {      /* extended remote to remote */
                    599:                        *src++ = 0;
                    600:                        if (*src == 0)
                    601:                                src = ".";
                    602:                        host = strrchr(argv[i], '@');
                    603:                        if (host) {
                    604:                                *host++ = 0;
                    605:                                host = cleanhostname(host);
                    606:                                suser = argv[i];
                    607:                                if (*suser == '\0')
                    608:                                        suser = pwd->pw_name;
                    609:                                else if (!okname(suser))
                    610:                                        continue;
                    611:                        } else {
                    612:                                host = cleanhostname(argv[i]);
                    613:                                suser = NULL;
                    614:                        }
1.171     djm       615:                        xasprintf(&bp, "%s -f %s%s", cmd,
                    616:                            *src == '-' ? "-- " : "", src);
1.169     markus    617:                        if (do_cmd(host, suser, bp, &remin, &remout) < 0)
                    618:                                exit(1);
1.173     djm       619:                        free(bp);
1.169     markus    620:                        host = cleanhostname(thost);
1.171     djm       621:                        xasprintf(&bp, "%s -t %s%s", cmd,
                    622:                            *targ == '-' ? "-- " : "", targ);
1.169     markus    623:                        if (do_cmd2(host, tuser, bp, remin, remout) < 0)
                    624:                                exit(1);
1.173     djm       625:                        free(bp);
1.169     markus    626:                        (void) close(remin);
                    627:                        (void) close(remout);
                    628:                        remin = remout = -1;
                    629:                } else if (src) {       /* standard remote to remote */
1.129     djm       630:                        freeargs(&alist);
                    631:                        addargs(&alist, "%s", ssh_program);
                    632:                        addargs(&alist, "-x");
1.168     djm       633:                        addargs(&alist, "-oClearAllForwardings=yes");
1.129     djm       634:                        addargs(&alist, "-n");
1.168     djm       635:                        for (j = 0; j < remote_remote_args.num; j++) {
                    636:                                addargs(&alist, "%s",
                    637:                                    remote_remote_args.list[j]);
                    638:                        }
1.1       deraadt   639:                        *src++ = 0;
                    640:                        if (*src == 0)
                    641:                                src = ".";
1.94      markus    642:                        host = strrchr(argv[i], '@');
1.129     djm       643:
1.1       deraadt   644:                        if (host) {
                    645:                                *host++ = 0;
1.23      markus    646:                                host = cleanhostname(host);
1.1       deraadt   647:                                suser = argv[i];
                    648:                                if (*suser == '\0')
                    649:                                        suser = pwd->pw_name;
1.129     djm       650:                                else if (!okname(suser))
1.101     markus    651:                                        continue;
1.129     djm       652:                                addargs(&alist, "-l");
                    653:                                addargs(&alist, "%s", suser);
1.23      markus    654:                        } else {
                    655:                                host = cleanhostname(argv[i]);
                    656:                        }
1.165     guenther  657:                        addargs(&alist, "--");
1.129     djm       658:                        addargs(&alist, "%s", host);
                    659:                        addargs(&alist, "%s", cmd);
                    660:                        addargs(&alist, "%s", src);
                    661:                        addargs(&alist, "%s%s%s:%s",
                    662:                            tuser ? tuser : "", tuser ? "@" : "",
                    663:                            thost, targ);
                    664:                        if (do_local_cmd(&alist) != 0)
1.109     markus    665:                                errs = 1;
1.18      markus    666:                } else {        /* local to remote */
1.1       deraadt   667:                        if (remin == -1) {
1.171     djm       668:                                xasprintf(&bp, "%s -t %s%s", cmd,
                    669:                                    *targ == '-' ? "-- " : "", targ);
1.23      markus    670:                                host = cleanhostname(thost);
1.35      deraadt   671:                                if (do_cmd(host, tuser, bp, &remin,
1.140     deraadt   672:                                    &remout) < 0)
1.18      markus    673:                                        exit(1);
1.1       deraadt   674:                                if (response() < 0)
                    675:                                        exit(1);
1.173     djm       676:                                free(bp);
1.1       deraadt   677:                        }
1.18      markus    678:                        source(1, argv + i);
1.1       deraadt   679:                }
                    680:        }
1.173     djm       681:        free(arg);
1.1       deraadt   682: }
                    683:
                    684: void
1.104     djm       685: tolocal(int argc, char **argv)
1.1       deraadt   686: {
                    687:        char *bp, *host, *src, *suser;
1.129     djm       688:        arglist alist;
1.140     deraadt   689:        int i;
1.129     djm       690:
                    691:        memset(&alist, '\0', sizeof(alist));
                    692:        alist.list = NULL;
1.1       deraadt   693:
                    694:        for (i = 0; i < argc - 1; i++) {
1.18      markus    695:                if (!(src = colon(argv[i]))) {  /* Local to local. */
1.129     djm       696:                        freeargs(&alist);
                    697:                        addargs(&alist, "%s", _PATH_CP);
                    698:                        if (iamrecursive)
                    699:                                addargs(&alist, "-r");
                    700:                        if (pflag)
                    701:                                addargs(&alist, "-p");
1.165     guenther  702:                        addargs(&alist, "--");
1.129     djm       703:                        addargs(&alist, "%s", argv[i]);
                    704:                        addargs(&alist, "%s", argv[argc-1]);
                    705:                        if (do_local_cmd(&alist))
1.1       deraadt   706:                                ++errs;
                    707:                        continue;
                    708:                }
                    709:                *src++ = 0;
                    710:                if (*src == 0)
                    711:                        src = ".";
1.94      markus    712:                if ((host = strrchr(argv[i], '@')) == NULL) {
1.1       deraadt   713:                        host = argv[i];
                    714:                        suser = NULL;
                    715:                } else {
                    716:                        *host++ = 0;
                    717:                        suser = argv[i];
                    718:                        if (*suser == '\0')
                    719:                                suser = pwd->pw_name;
                    720:                }
1.23      markus    721:                host = cleanhostname(host);
1.171     djm       722:                xasprintf(&bp, "%s -f %s%s",
                    723:                    cmd, *src == '-' ? "-- " : "", src);
1.140     deraadt   724:                if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
1.173     djm       725:                        free(bp);
1.18      markus    726:                        ++errs;
                    727:                        continue;
1.1       deraadt   728:                }
1.173     djm       729:                free(bp);
1.1       deraadt   730:                sink(1, argv + argc - 1);
1.18      markus    731:                (void) close(remin);
1.1       deraadt   732:                remin = remout = -1;
                    733:        }
                    734: }
                    735:
                    736: void
1.104     djm       737: source(int argc, char **argv)
1.1       deraadt   738: {
                    739:        struct stat stb;
                    740:        static BUF buffer;
                    741:        BUF *bp;
1.163     dtucker   742:        off_t i, statbytes;
1.180     djm       743:        size_t amt, nr;
1.125     dtucker   744:        int fd = -1, haderr, indx;
1.181     deraadt   745:        char *last, *name, buf[2048], encname[PATH_MAX];
1.65      deraadt   746:        int len;
1.1       deraadt   747:
                    748:        for (indx = 0; indx < argc; ++indx) {
1.18      markus    749:                name = argv[indx];
1.11      aaron     750:                statbytes = 0;
1.65      deraadt   751:                len = strlen(name);
                    752:                while (len > 1 && name[len-1] == '/')
                    753:                        name[--len] = '\0';
1.158     dtucker   754:                if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
                    755:                        goto syserr;
1.85      markus    756:                if (strchr(name, '\n') != NULL) {
1.158     dtucker   757:                        strnvis(encname, name, sizeof(encname), VIS_NL);
                    758:                        name = encname;
1.85      markus    759:                }
1.1       deraadt   760:                if (fstat(fd, &stb) < 0) {
                    761: syserr:                        run_err("%s: %s", name, strerror(errno));
                    762:                        goto next;
                    763:                }
1.163     dtucker   764:                if (stb.st_size < 0) {
                    765:                        run_err("%s: %s", name, "Negative file size");
                    766:                        goto next;
                    767:                }
1.157     djm       768:                unset_nonblock(fd);
1.1       deraadt   769:                switch (stb.st_mode & S_IFMT) {
                    770:                case S_IFREG:
                    771:                        break;
                    772:                case S_IFDIR:
                    773:                        if (iamrecursive) {
                    774:                                rsource(name, &stb);
                    775:                                goto next;
                    776:                        }
                    777:                        /* FALLTHROUGH */
                    778:                default:
                    779:                        run_err("%s: not a regular file", name);
                    780:                        goto next;
                    781:                }
                    782:                if ((last = strrchr(name, '/')) == NULL)
                    783:                        last = name;
                    784:                else
                    785:                        ++last;
1.11      aaron     786:                curfile = last;
1.1       deraadt   787:                if (pflag) {
1.176     guenther  788:                        if (do_times(remout, verbose_mode, &stb) < 0)
1.1       deraadt   789:                                goto next;
                    790:                }
                    791: #define        FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1.61      markus    792:                snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1.47      markus    793:                    (u_int) (stb.st_mode & FILEMODEMASK),
1.62      markus    794:                    (long long)stb.st_size, last);
1.186     schwarze  795:                if (verbose_mode)
                    796:                        fmprintf(stderr, "Sending file modes: %s", buf);
1.107     deraadt   797:                (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1       deraadt   798:                if (response() < 0)
                    799:                        goto next;
1.161     djm       800:                if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1.127     deraadt   801: next:                  if (fd != -1) {
                    802:                                (void) close(fd);
                    803:                                fd = -1;
                    804:                        }
1.1       deraadt   805:                        continue;
                    806:                }
1.97      fgsch     807:                if (showprogress)
                    808:                        start_progress_meter(curfile, stb.st_size, &statbytes);
1.161     djm       809:                set_nonblock(remout);
1.1       deraadt   810:                for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
                    811:                        amt = bp->cnt;
1.163     dtucker   812:                        if (i + (off_t)amt > stb.st_size)
1.1       deraadt   813:                                amt = stb.st_size - i;
                    814:                        if (!haderr) {
1.180     djm       815:                                if ((nr = atomicio(read, fd,
                    816:                                    bp->buf, amt)) != amt) {
1.122     avsm      817:                                        haderr = errno;
1.180     djm       818:                                        memset(bp->buf + nr, 0, amt - nr);
                    819:                                }
1.1       deraadt   820:                        }
1.161     djm       821:                        /* Keep writing after error to retain sync */
                    822:                        if (haderr) {
                    823:                                (void)atomicio(vwrite, remout, bp->buf, amt);
1.180     djm       824:                                memset(bp->buf, 0, amt);
1.161     djm       825:                                continue;
1.1       deraadt   826:                        }
1.167     djm       827:                        if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1.161     djm       828:                            &statbytes) != amt)
                    829:                                haderr = errno;
1.1       deraadt   830:                }
1.161     djm       831:                unset_nonblock(remout);
1.4       aaron     832:
1.127     deraadt   833:                if (fd != -1) {
                    834:                        if (close(fd) < 0 && !haderr)
                    835:                                haderr = errno;
                    836:                        fd = -1;
                    837:                }
1.1       deraadt   838:                if (!haderr)
1.107     deraadt   839:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt   840:                else
                    841:                        run_err("%s: %s", name, strerror(haderr));
1.18      markus    842:                (void) response();
1.185     dtucker   843:                if (showprogress)
                    844:                        stop_progress_meter();
1.1       deraadt   845:        }
                    846: }
                    847:
                    848: void
1.104     djm       849: rsource(char *name, struct stat *statp)
1.1       deraadt   850: {
                    851:        DIR *dirp;
                    852:        struct dirent *dp;
1.181     deraadt   853:        char *last, *vect[1], path[PATH_MAX];
1.1       deraadt   854:
                    855:        if (!(dirp = opendir(name))) {
                    856:                run_err("%s: %s", name, strerror(errno));
                    857:                return;
                    858:        }
                    859:        last = strrchr(name, '/');
1.183     mmcc      860:        if (last == NULL)
1.1       deraadt   861:                last = name;
                    862:        else
                    863:                last++;
                    864:        if (pflag) {
1.176     guenther  865:                if (do_times(remout, verbose_mode, statp) < 0) {
1.1       deraadt   866:                        closedir(dirp);
                    867:                        return;
                    868:                }
                    869:        }
1.55      deraadt   870:        (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1.47      markus    871:            (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1.18      markus    872:        if (verbose_mode)
1.186     schwarze  873:                fmprintf(stderr, "Entering directory: %s", path);
1.107     deraadt   874:        (void) atomicio(vwrite, remout, path, strlen(path));
1.1       deraadt   875:        if (response() < 0) {
                    876:                closedir(dirp);
                    877:                return;
                    878:        }
1.63      stevesk   879:        while ((dp = readdir(dirp)) != NULL) {
1.1       deraadt   880:                if (dp->d_ino == 0)
                    881:                        continue;
                    882:                if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
                    883:                        continue;
                    884:                if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
                    885:                        run_err("%s/%s: name too long", name, dp->d_name);
                    886:                        continue;
                    887:                }
1.55      deraadt   888:                (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1.1       deraadt   889:                vect[0] = path;
                    890:                source(1, vect);
                    891:        }
1.18      markus    892:        (void) closedir(dirp);
1.107     deraadt   893:        (void) atomicio(vwrite, remout, "E\n", 2);
1.18      markus    894:        (void) response();
1.1       deraadt   895: }
                    896:
                    897: void
1.104     djm       898: sink(int argc, char **argv)
1.1       deraadt   899: {
                    900:        static BUF buffer;
                    901:        struct stat stb;
1.18      markus    902:        enum {
                    903:                YES, NO, DISPLAYED
                    904:        } wrerr;
1.1       deraadt   905:        BUF *bp;
1.122     avsm      906:        off_t i;
1.124     djm       907:        size_t j, count;
1.140     deraadt   908:        int amt, exists, first, ofd;
                    909:        mode_t mode, omode, mask;
1.97      fgsch     910:        off_t size, statbytes;
1.176     guenther  911:        unsigned long long ull;
1.36      deraadt   912:        int setimes, targisdir, wrerrno = 0;
1.186     schwarze  913:        char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1.40      markus    914:        struct timeval tv[2];
1.1       deraadt   915:
1.66      stevesk   916: #define        atime   tv[0]
                    917: #define        mtime   tv[1]
1.118     deraadt   918: #define        SCREWUP(str)    { why = str; goto screwup; }
1.1       deraadt   919:
                    920:        setimes = targisdir = 0;
                    921:        mask = umask(0);
                    922:        if (!pflag)
1.18      markus    923:                (void) umask(mask);
1.1       deraadt   924:        if (argc != 1) {
                    925:                run_err("ambiguous target");
                    926:                exit(1);
                    927:        }
                    928:        targ = *argv;
                    929:        if (targetshouldbedirectory)
                    930:                verifydir(targ);
1.18      markus    931:
1.107     deraadt   932:        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt   933:        if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
                    934:                targisdir = 1;
                    935:        for (first = 1;; first = 0) {
                    936:                cp = buf;
1.122     avsm      937:                if (atomicio(read, remin, cp, 1) != 1)
1.1       deraadt   938:                        return;
                    939:                if (*cp++ == '\n')
                    940:                        SCREWUP("unexpected <newline>");
                    941:                do {
1.30      deraadt   942:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt   943:                                SCREWUP("lost connection");
                    944:                        *cp++ = ch;
                    945:                } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
                    946:                *cp = 0;
1.114     markus    947:                if (verbose_mode)
1.186     schwarze  948:                        fmprintf(stderr, "Sink: %s", buf);
1.1       deraadt   949:
                    950:                if (buf[0] == '\01' || buf[0] == '\02') {
1.186     schwarze  951:                        if (iamremote == 0) {
                    952:                                (void) snmprintf(visbuf, sizeof(visbuf),
                    953:                                    NULL, "%s", buf + 1);
1.107     deraadt   954:                                (void) atomicio(vwrite, STDERR_FILENO,
1.186     schwarze  955:                                    visbuf, strlen(visbuf));
                    956:                        }
1.1       deraadt   957:                        if (buf[0] == '\02')
                    958:                                exit(1);
                    959:                        ++errs;
                    960:                        continue;
                    961:                }
                    962:                if (buf[0] == 'E') {
1.107     deraadt   963:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt   964:                        return;
                    965:                }
                    966:                if (ch == '\n')
                    967:                        *--cp = 0;
                    968:
                    969:                cp = buf;
                    970:                if (*cp == 'T') {
                    971:                        setimes++;
                    972:                        cp++;
1.176     guenther  973:                        if (!isdigit((unsigned char)*cp))
                    974:                                SCREWUP("mtime.sec not present");
                    975:                        ull = strtoull(cp, &cp, 10);
1.66      stevesk   976:                        if (!cp || *cp++ != ' ')
1.1       deraadt   977:                                SCREWUP("mtime.sec not delimited");
1.178     djm       978:                        if ((time_t)ull < 0 ||
                    979:                            (unsigned long long)(time_t)ull != ull)
1.176     guenther  980:                                setimes = 0;    /* out of range */
                    981:                        mtime.tv_sec = ull;
1.66      stevesk   982:                        mtime.tv_usec = strtol(cp, &cp, 10);
1.176     guenther  983:                        if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
                    984:                            mtime.tv_usec > 999999)
1.1       deraadt   985:                                SCREWUP("mtime.usec not delimited");
1.176     guenther  986:                        if (!isdigit((unsigned char)*cp))
                    987:                                SCREWUP("atime.sec not present");
                    988:                        ull = strtoull(cp, &cp, 10);
1.66      stevesk   989:                        if (!cp || *cp++ != ' ')
1.1       deraadt   990:                                SCREWUP("atime.sec not delimited");
1.178     djm       991:                        if ((time_t)ull < 0 ||
                    992:                            (unsigned long long)(time_t)ull != ull)
1.176     guenther  993:                                setimes = 0;    /* out of range */
                    994:                        atime.tv_sec = ull;
1.66      stevesk   995:                        atime.tv_usec = strtol(cp, &cp, 10);
1.176     guenther  996:                        if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
                    997:                            atime.tv_usec > 999999)
1.1       deraadt   998:                                SCREWUP("atime.usec not delimited");
1.107     deraadt   999:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt  1000:                        continue;
                   1001:                }
                   1002:                if (*cp != 'C' && *cp != 'D') {
                   1003:                        /*
                   1004:                         * Check for the case "rcp remote:foo\* local:bar".
                   1005:                         * In this case, the line "No match." can be returned
                   1006:                         * by the shell before the rcp command on the remote is
                   1007:                         * executed so the ^Aerror_message convention isn't
                   1008:                         * followed.
                   1009:                         */
                   1010:                        if (first) {
                   1011:                                run_err("%s", cp);
                   1012:                                exit(1);
                   1013:                        }
                   1014:                        SCREWUP("expected control record");
                   1015:                }
                   1016:                mode = 0;
                   1017:                for (++cp; cp < buf + 5; cp++) {
                   1018:                        if (*cp < '0' || *cp > '7')
                   1019:                                SCREWUP("bad mode");
                   1020:                        mode = (mode << 3) | (*cp - '0');
                   1021:                }
                   1022:                if (*cp++ != ' ')
                   1023:                        SCREWUP("mode not delimited");
                   1024:
1.179     deraadt  1025:                for (size = 0; isdigit((unsigned char)*cp);)
1.1       deraadt  1026:                        size = size * 10 + (*cp++ - '0');
                   1027:                if (*cp++ != ' ')
                   1028:                        SCREWUP("size not delimited");
1.114     markus   1029:                if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
                   1030:                        run_err("error: unexpected filename: %s", cp);
                   1031:                        exit(1);
                   1032:                }
1.1       deraadt  1033:                if (targisdir) {
                   1034:                        static char *namebuf;
1.124     djm      1035:                        static size_t cursize;
1.1       deraadt  1036:                        size_t need;
                   1037:
                   1038:                        need = strlen(targ) + strlen(cp) + 250;
1.55      deraadt  1039:                        if (need > cursize) {
1.173     djm      1040:                                free(namebuf);
1.18      markus   1041:                                namebuf = xmalloc(need);
1.55      deraadt  1042:                                cursize = need;
                   1043:                        }
                   1044:                        (void) snprintf(namebuf, need, "%s%s%s", targ,
1.88      mouring  1045:                            strcmp(targ, "/") ? "/" : "", cp);
1.1       deraadt  1046:                        np = namebuf;
                   1047:                } else
                   1048:                        np = targ;
1.12      aaron    1049:                curfile = cp;
1.1       deraadt  1050:                exists = stat(np, &stb) == 0;
                   1051:                if (buf[0] == 'D') {
                   1052:                        int mod_flag = pflag;
1.114     markus   1053:                        if (!iamrecursive)
                   1054:                                SCREWUP("received directory without -r");
1.1       deraadt  1055:                        if (exists) {
                   1056:                                if (!S_ISDIR(stb.st_mode)) {
                   1057:                                        errno = ENOTDIR;
                   1058:                                        goto bad;
                   1059:                                }
                   1060:                                if (pflag)
1.18      markus   1061:                                        (void) chmod(np, mode);
1.1       deraadt  1062:                        } else {
1.18      markus   1063:                                /* Handle copying from a read-only
                   1064:                                   directory */
1.1       deraadt  1065:                                mod_flag = 1;
                   1066:                                if (mkdir(np, mode | S_IRWXU) < 0)
                   1067:                                        goto bad;
                   1068:                        }
1.58      danh     1069:                        vect[0] = xstrdup(np);
1.1       deraadt  1070:                        sink(1, vect);
                   1071:                        if (setimes) {
                   1072:                                setimes = 0;
1.59      deraadt  1073:                                if (utimes(vect[0], tv) < 0)
1.18      markus   1074:                                        run_err("%s: set times: %s",
1.59      deraadt  1075:                                            vect[0], strerror(errno));
1.1       deraadt  1076:                        }
                   1077:                        if (mod_flag)
1.59      deraadt  1078:                                (void) chmod(vect[0], mode);
1.173     djm      1079:                        free(vect[0]);
1.1       deraadt  1080:                        continue;
                   1081:                }
                   1082:                omode = mode;
1.174     dtucker  1083:                mode |= S_IWUSR;
1.71      markus   1084:                if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1.1       deraadt  1085: bad:                   run_err("%s: %s", np, strerror(errno));
                   1086:                        continue;
                   1087:                }
1.107     deraadt  1088:                (void) atomicio(vwrite, remout, "", 1);
1.161     djm      1089:                if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1.18      markus   1090:                        (void) close(ofd);
1.1       deraadt  1091:                        continue;
                   1092:                }
                   1093:                cp = bp->buf;
                   1094:                wrerr = NO;
1.7       deraadt  1095:
1.12      aaron    1096:                statbytes = 0;
1.97      fgsch    1097:                if (showprogress)
                   1098:                        start_progress_meter(curfile, size, &statbytes);
1.161     djm      1099:                set_nonblock(remin);
                   1100:                for (count = i = 0; i < size; i += bp->cnt) {
                   1101:                        amt = bp->cnt;
1.1       deraadt  1102:                        if (i + amt > size)
                   1103:                                amt = size - i;
                   1104:                        count += amt;
                   1105:                        do {
1.167     djm      1106:                                j = atomicio6(read, remin, cp, amt,
                   1107:                                    scpio, &statbytes);
1.122     avsm     1108:                                if (j == 0) {
1.161     djm      1109:                                        run_err("%s", j != EPIPE ?
                   1110:                                            strerror(errno) :
1.63      stevesk  1111:                                            "dropped connection");
1.1       deraadt  1112:                                        exit(1);
                   1113:                                }
                   1114:                                amt -= j;
                   1115:                                cp += j;
                   1116:                        } while (amt > 0);
1.112     djm      1117:
1.1       deraadt  1118:                        if (count == bp->cnt) {
                   1119:                                /* Keep reading so we stay sync'd up. */
                   1120:                                if (wrerr == NO) {
1.122     avsm     1121:                                        if (atomicio(vwrite, ofd, bp->buf,
                   1122:                                            count) != count) {
1.1       deraadt  1123:                                                wrerr = YES;
1.122     avsm     1124:                                                wrerrno = errno;
1.1       deraadt  1125:                                        }
                   1126:                                }
                   1127:                                count = 0;
                   1128:                                cp = bp->buf;
                   1129:                        }
                   1130:                }
1.161     djm      1131:                unset_nonblock(remin);
1.1       deraadt  1132:                if (count != 0 && wrerr == NO &&
1.122     avsm     1133:                    atomicio(vwrite, ofd, bp->buf, count) != count) {
1.1       deraadt  1134:                        wrerr = YES;
1.122     avsm     1135:                        wrerrno = errno;
1.1       deraadt  1136:                }
1.159     djm      1137:                if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
                   1138:                    ftruncate(ofd, size) != 0) {
1.1       deraadt  1139:                        run_err("%s: truncate: %s", np, strerror(errno));
                   1140:                        wrerr = DISPLAYED;
                   1141:                }
                   1142:                if (pflag) {
                   1143:                        if (exists || omode != mode)
1.116     dtucker  1144:                                if (fchmod(ofd, omode)) {
1.1       deraadt  1145:                                        run_err("%s: set mode: %s",
1.63      stevesk  1146:                                            np, strerror(errno));
1.116     dtucker  1147:                                        wrerr = DISPLAYED;
                   1148:                                }
1.1       deraadt  1149:                } else {
                   1150:                        if (!exists && omode != mode)
1.116     dtucker  1151:                                if (fchmod(ofd, omode & ~mask)) {
1.1       deraadt  1152:                                        run_err("%s: set mode: %s",
1.63      stevesk  1153:                                            np, strerror(errno));
1.116     dtucker  1154:                                        wrerr = DISPLAYED;
                   1155:                                }
1.1       deraadt  1156:                }
1.33      provos   1157:                if (close(ofd) == -1) {
                   1158:                        wrerr = YES;
                   1159:                        wrerrno = errno;
                   1160:                }
1.18      markus   1161:                (void) response();
1.185     dtucker  1162:                if (showprogress)
                   1163:                        stop_progress_meter();
1.1       deraadt  1164:                if (setimes && wrerr == NO) {
                   1165:                        setimes = 0;
1.40      markus   1166:                        if (utimes(np, tv) < 0) {
1.1       deraadt  1167:                                run_err("%s: set times: %s",
1.63      stevesk  1168:                                    np, strerror(errno));
1.1       deraadt  1169:                                wrerr = DISPLAYED;
                   1170:                        }
                   1171:                }
1.18      markus   1172:                switch (wrerr) {
1.1       deraadt  1173:                case YES:
                   1174:                        run_err("%s: %s", np, strerror(wrerrno));
                   1175:                        break;
                   1176:                case NO:
1.107     deraadt  1177:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt  1178:                        break;
                   1179:                case DISPLAYED:
                   1180:                        break;
                   1181:                }
                   1182:        }
                   1183: screwup:
                   1184:        run_err("protocol error: %s", why);
                   1185:        exit(1);
                   1186: }
                   1187:
                   1188: int
1.86      itojun   1189: response(void)
1.1       deraadt  1190: {
1.186     schwarze 1191:        char ch, *cp, resp, rbuf[2048], visbuf[2048];
1.1       deraadt  1192:
1.30      deraadt  1193:        if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1.1       deraadt  1194:                lostconn(0);
                   1195:
                   1196:        cp = rbuf;
1.18      markus   1197:        switch (resp) {
                   1198:        case 0:         /* ok */
1.1       deraadt  1199:                return (0);
                   1200:        default:
                   1201:                *cp++ = resp;
                   1202:                /* FALLTHROUGH */
1.18      markus   1203:        case 1:         /* error, followed by error msg */
                   1204:        case 2:         /* fatal error, "" */
1.1       deraadt  1205:                do {
1.30      deraadt  1206:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt  1207:                                lostconn(0);
                   1208:                        *cp++ = ch;
                   1209:                } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
                   1210:
1.186     schwarze 1211:                if (!iamremote) {
                   1212:                        cp[-1] = '\0';
                   1213:                        (void) snmprintf(visbuf, sizeof(visbuf),
                   1214:                            NULL, "%s\n", rbuf);
                   1215:                        (void) atomicio(vwrite, STDERR_FILENO,
                   1216:                            visbuf, strlen(visbuf));
                   1217:                }
1.1       deraadt  1218:                ++errs;
                   1219:                if (resp == 1)
                   1220:                        return (-1);
                   1221:                exit(1);
                   1222:        }
                   1223:        /* NOTREACHED */
                   1224: }
                   1225:
                   1226: void
1.86      itojun   1227: usage(void)
1.1       deraadt  1228: {
1.83      stevesk  1229:        (void) fprintf(stderr,
1.170     jmc      1230:            "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1.110     jmc      1231:            "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1.160     sobrado  1232:            "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1.1       deraadt  1233:        exit(1);
                   1234: }
                   1235:
                   1236: void
1.18      markus   1237: run_err(const char *fmt,...)
1.1       deraadt  1238: {
                   1239:        static FILE *fp;
                   1240:        va_list ap;
                   1241:
                   1242:        ++errs;
1.136     biorn    1243:        if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
                   1244:                (void) fprintf(fp, "%c", 0x01);
                   1245:                (void) fprintf(fp, "scp: ");
                   1246:                va_start(ap, fmt);
                   1247:                (void) vfprintf(fp, fmt, ap);
                   1248:                va_end(ap);
                   1249:                (void) fprintf(fp, "\n");
                   1250:                (void) fflush(fp);
                   1251:        }
1.18      markus   1252:
                   1253:        if (!iamremote) {
1.73      markus   1254:                va_start(ap, fmt);
1.186     schwarze 1255:                vfmprintf(stderr, fmt, ap);
1.73      markus   1256:                va_end(ap);
1.18      markus   1257:                fprintf(stderr, "\n");
                   1258:        }
1.1       deraadt  1259: }
                   1260:
                   1261: void
1.104     djm      1262: verifydir(char *cp)
1.1       deraadt  1263: {
                   1264:        struct stat stb;
                   1265:
                   1266:        if (!stat(cp, &stb)) {
                   1267:                if (S_ISDIR(stb.st_mode))
                   1268:                        return;
                   1269:                errno = ENOTDIR;
                   1270:        }
                   1271:        run_err("%s: %s", cp, strerror(errno));
1.123     avsm     1272:        killchild(0);
1.1       deraadt  1273: }
                   1274:
                   1275: int
1.104     djm      1276: okname(char *cp0)
1.1       deraadt  1277: {
                   1278:        int c;
                   1279:        char *cp;
                   1280:
                   1281:        cp = cp0;
                   1282:        do {
1.75      deraadt  1283:                c = (int)*cp;
1.1       deraadt  1284:                if (c & 0200)
                   1285:                        goto bad;
1.179     deraadt  1286:                if (!isalpha(c) && !isdigit((unsigned char)c)) {
1.101     markus   1287:                        switch (c) {
                   1288:                        case '\'':
                   1289:                        case '"':
                   1290:                        case '`':
                   1291:                        case ' ':
                   1292:                        case '#':
                   1293:                                goto bad;
                   1294:                        default:
                   1295:                                break;
                   1296:                        }
                   1297:                }
1.1       deraadt  1298:        } while (*++cp);
                   1299:        return (1);
                   1300:
1.186     schwarze 1301: bad:   fmprintf(stderr, "%s: invalid user name\n", cp0);
1.1       deraadt  1302:        return (0);
                   1303: }
                   1304:
                   1305: BUF *
1.104     djm      1306: allocbuf(BUF *bp, int fd, int blksize)
1.1       deraadt  1307: {
                   1308:        size_t size;
                   1309:        struct stat stb;
                   1310:
                   1311:        if (fstat(fd, &stb) < 0) {
                   1312:                run_err("fstat: %s", strerror(errno));
                   1313:                return (0);
                   1314:        }
1.187   ! deraadt  1315:        size = ROUNDUP(stb.st_blksize, blksize);
1.95      markus   1316:        if (size == 0)
1.18      markus   1317:                size = blksize;
1.1       deraadt  1318:        if (bp->cnt >= size)
                   1319:                return (bp);
1.18      markus   1320:        if (bp->buf == NULL)
                   1321:                bp->buf = xmalloc(size);
                   1322:        else
1.182     deraadt  1323:                bp->buf = xreallocarray(bp->buf, 1, size);
1.81      markus   1324:        memset(bp->buf, 0, size);
1.1       deraadt  1325:        bp->cnt = size;
                   1326:        return (bp);
                   1327: }
                   1328:
                   1329: void
1.104     djm      1330: lostconn(int signo)
1.1       deraadt  1331: {
                   1332:        if (!iamremote)
1.172     dtucker  1333:                (void)write(STDERR_FILENO, "lost connection\n", 16);
1.74      markus   1334:        if (signo)
                   1335:                _exit(1);
                   1336:        else
                   1337:                exit(1);
1.4       aaron    1338: }