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

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