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

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