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

1.195   ! djm         1: /* $OpenBSD: scp.c,v 1.194 2017/12/18 17:28:54 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.195   ! djm       401:        addargs(&args, "-oRemoteCommand=none");
        !           402:        addargs(&args, "-oRequestTTY=no");
1.41      markus    403:
1.1       deraadt   404:        fflag = tflag = 0;
1.169     markus    405:        while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
1.18      markus    406:                switch (ch) {
                    407:                /* User-visible flags. */
1.100     markus    408:                case '1':
1.190     djm       409:                        fatal("SSH protocol v.1 is no longer supported");
                    410:                        break;
1.100     markus    411:                case '2':
1.190     djm       412:                        /* Ignored */
                    413:                        break;
1.23      markus    414:                case '4':
1.41      markus    415:                case '6':
                    416:                case 'C':
1.70      mouring   417:                        addargs(&args, "-%c", ch);
1.168     djm       418:                        addargs(&remote_remote_args, "-%c", ch);
1.41      markus    419:                        break;
1.169     markus    420:                case '3':
                    421:                        throughlocal = 1;
                    422:                        break;
1.41      markus    423:                case 'o':
                    424:                case 'c':
                    425:                case 'i':
1.83      stevesk   426:                case 'F':
1.168     djm       427:                        addargs(&remote_remote_args, "-%c", ch);
                    428:                        addargs(&remote_remote_args, "%s", optarg);
1.165     guenther  429:                        addargs(&args, "-%c", ch);
                    430:                        addargs(&args, "%s", optarg);
1.23      markus    431:                        break;
1.41      markus    432:                case 'P':
1.193     millert   433:                        sshport = a2port(optarg);
                    434:                        if (sshport <= 0)
                    435:                                fatal("bad port \"%s\"\n", optarg);
1.41      markus    436:                        break;
                    437:                case 'B':
1.168     djm       438:                        addargs(&remote_remote_args, "-oBatchmode=yes");
                    439:                        addargs(&args, "-oBatchmode=yes");
1.23      markus    440:                        break;
1.99      markus    441:                case 'l':
1.167     djm       442:                        limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
                    443:                            &errstr);
                    444:                        if (errstr != NULL)
1.99      markus    445:                                usage();
1.167     djm       446:                        limit_kbps *= 1024; /* kbps */
                    447:                        bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
1.99      markus    448:                        break;
1.1       deraadt   449:                case 'p':
                    450:                        pflag = 1;
                    451:                        break;
                    452:                case 'r':
                    453:                        iamrecursive = 1;
                    454:                        break;
1.34      deraadt   455:                case 'S':
1.41      markus    456:                        ssh_program = xstrdup(optarg);
                    457:                        break;
                    458:                case 'v':
1.72      markus    459:                        addargs(&args, "-v");
1.168     djm       460:                        addargs(&remote_remote_args, "-v");
1.41      markus    461:                        verbose_mode = 1;
                    462:                        break;
                    463:                case 'q':
1.111     dtucker   464:                        addargs(&args, "-q");
1.168     djm       465:                        addargs(&remote_remote_args, "-q");
1.41      markus    466:                        showprogress = 0;
1.34      deraadt   467:                        break;
                    468:
1.18      markus    469:                /* Server options. */
1.1       deraadt   470:                case 'd':
                    471:                        targetshouldbedirectory = 1;
                    472:                        break;
1.18      markus    473:                case 'f':       /* "from" */
1.1       deraadt   474:                        iamremote = 1;
                    475:                        fflag = 1;
                    476:                        break;
1.18      markus    477:                case 't':       /* "to" */
1.1       deraadt   478:                        iamremote = 1;
                    479:                        tflag = 1;
                    480:                        break;
                    481:                default:
                    482:                        usage();
                    483:                }
                    484:        argc -= optind;
                    485:        argv += optind;
                    486:
                    487:        if ((pwd = getpwuid(userid = getuid())) == NULL)
1.108     deraadt   488:                fatal("unknown user %u", (u_int) userid);
1.1       deraadt   489:
1.156     djm       490:        if (!isatty(STDOUT_FILENO))
1.7       deraadt   491:                showprogress = 0;
1.184     deraadt   492:
                    493:        if (pflag) {
                    494:                /* Cannot pledge: -p allows setuid/setgid files... */
                    495:        } else {
                    496:                if (pledge("stdio rpath wpath cpath fattr tty proc exec",
                    497:                    NULL) == -1) {
                    498:                        perror("pledge");
                    499:                        exit(1);
                    500:                }
                    501:        }
1.7       deraadt   502:
1.1       deraadt   503:        remin = STDIN_FILENO;
                    504:        remout = STDOUT_FILENO;
                    505:
1.52      stevesk   506:        if (fflag) {
1.18      markus    507:                /* Follow "protocol", send data. */
                    508:                (void) response();
1.1       deraadt   509:                source(argc, argv);
                    510:                exit(errs != 0);
                    511:        }
1.18      markus    512:        if (tflag) {
                    513:                /* Receive data. */
1.1       deraadt   514:                sink(argc, argv);
                    515:                exit(errs != 0);
                    516:        }
                    517:        if (argc < 2)
                    518:                usage();
                    519:        if (argc > 2)
                    520:                targetshouldbedirectory = 1;
                    521:
                    522:        remin = remout = -1;
1.92      markus    523:        do_cmd_pid = -1;
1.1       deraadt   524:        /* Command to be executed on remote system using "ssh". */
1.55      deraadt   525:        (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
                    526:            verbose_mode ? " -v" : "",
1.35      deraadt   527:            iamrecursive ? " -r" : "", pflag ? " -p" : "",
                    528:            targetshouldbedirectory ? " -d" : "");
1.1       deraadt   529:
1.18      markus    530:        (void) signal(SIGPIPE, lostconn);
1.1       deraadt   531:
1.193     millert   532:        if (colon(argv[argc - 1]))      /* Dest is remote host. */
                    533:                toremote(argc, argv);
1.1       deraadt   534:        else {
                    535:                if (targetshouldbedirectory)
                    536:                        verifydir(argv[argc - 1]);
1.130     djm       537:                tolocal(argc, argv);    /* Dest is local host. */
1.92      markus    538:        }
                    539:        /*
                    540:         * Finally check the exit status of the ssh process, if one was forked
1.164     stevesk   541:         * and no error has occurred yet
1.92      markus    542:         */
                    543:        if (do_cmd_pid != -1 && errs == 0) {
                    544:                if (remin != -1)
                    545:                    (void) close(remin);
                    546:                if (remout != -1)
                    547:                    (void) close(remout);
                    548:                if (waitpid(do_cmd_pid, &status, 0) == -1)
                    549:                        errs = 1;
                    550:                else {
                    551:                        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
                    552:                                errs = 1;
                    553:                }
1.1       deraadt   554:        }
                    555:        exit(errs != 0);
                    556: }
                    557:
1.167     djm       558: /* Callback from atomicio6 to update progress meter and limit bandwidth */
                    559: static int
                    560: scpio(void *_cnt, size_t s)
1.161     djm       561: {
1.167     djm       562:        off_t *cnt = (off_t *)_cnt;
                    563:
                    564:        *cnt += s;
                    565:        if (limit_kbps > 0)
                    566:                bandwidth_limit(&bwlimit, s);
                    567:        return 0;
1.161     djm       568: }
                    569:
1.176     guenther  570: static int
                    571: do_times(int fd, int verb, const struct stat *sb)
                    572: {
                    573:        /* strlen(2^64) == 20; strlen(10^6) == 7 */
                    574:        char buf[(20 + 7 + 2) * 2 + 2];
                    575:
                    576:        (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
                    577:            (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
                    578:            (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
                    579:        if (verb) {
                    580:                fprintf(stderr, "File mtime %lld atime %lld\n",
                    581:                    (long long)sb->st_mtime, (long long)sb->st_atime);
                    582:                fprintf(stderr, "Sending file timestamps: %s", buf);
                    583:        }
                    584:        (void) atomicio(vwrite, fd, buf, strlen(buf));
                    585:        return (response());
                    586: }
                    587:
1.194     millert   588: static int
                    589: parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
                    590:      char **pathp)
                    591: {
                    592:        int r;
                    593:
                    594:        r = parse_uri("scp", uri, userp, hostp, portp, pathp);
                    595:        if (r == 0 && *pathp == NULL)
                    596:                *pathp = xstrdup(".");
                    597:        return r;
                    598: }
                    599:
1.1       deraadt   600: void
1.193     millert   601: toremote(int argc, char **argv)
1.1       deraadt   602: {
1.193     millert   603:        char *suser = NULL, *host = NULL, *src = NULL;
                    604:        char *bp, *tuser, *thost, *targ;
                    605:        int sport = -1, tport = -1;
1.129     djm       606:        arglist alist;
1.193     millert   607:        int i, r;
1.168     djm       608:        u_int j;
1.129     djm       609:
                    610:        memset(&alist, '\0', sizeof(alist));
                    611:        alist.list = NULL;
1.1       deraadt   612:
1.193     millert   613:        /* Parse target */
1.194     millert   614:        r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
                    615:        if (r == -1) {
                    616:                fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
                    617:                ++errs;
                    618:                goto out;
                    619:        }
1.193     millert   620:        if (r != 0) {
                    621:                if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1.194     millert   622:                    &targ) == -1) {
                    623:                        fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
                    624:                        ++errs;
1.193     millert   625:                        goto out;
1.194     millert   626:                }
1.129     djm       627:        }
1.194     millert   628:        if (tuser != NULL && !okname(tuser)) {
                    629:                ++errs;
1.193     millert   630:                goto out;
1.194     millert   631:        }
1.129     djm       632:
1.193     millert   633:        /* Parse source files */
1.1       deraadt   634:        for (i = 0; i < argc - 1; i++) {
1.193     millert   635:                free(suser);
                    636:                free(host);
                    637:                free(src);
1.194     millert   638:                r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
                    639:                if (r == -1) {
                    640:                        fmprintf(stderr, "%s: invalid uri\n", argv[i]);
                    641:                        ++errs;
                    642:                        continue;
                    643:                }
                    644:                if (r != 0) {
1.193     millert   645:                        parse_user_host_path(argv[i], &suser, &host, &src);
1.194     millert   646:                }
1.193     millert   647:                if (suser != NULL && !okname(suser)) {
                    648:                        ++errs;
                    649:                        continue;
                    650:                }
                    651:                if (host && throughlocal) {     /* extended remote to remote */
1.171     djm       652:                        xasprintf(&bp, "%s -f %s%s", cmd,
                    653:                            *src == '-' ? "-- " : "", src);
1.193     millert   654:                        if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
1.169     markus    655:                                exit(1);
1.173     djm       656:                        free(bp);
1.171     djm       657:                        xasprintf(&bp, "%s -t %s%s", cmd,
                    658:                            *targ == '-' ? "-- " : "", targ);
1.193     millert   659:                        if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
1.169     markus    660:                                exit(1);
1.173     djm       661:                        free(bp);
1.169     markus    662:                        (void) close(remin);
                    663:                        (void) close(remout);
                    664:                        remin = remout = -1;
1.193     millert   665:                } else if (host) {      /* standard remote to remote */
                    666:                        if (tport != -1 && tport != SSH_DEFAULT_PORT) {
                    667:                                /* This would require the remote support URIs */
                    668:                                fatal("target port not supported with two "
                    669:                                    "remote hosts without the -3 option");
                    670:                        }
                    671:
1.129     djm       672:                        freeargs(&alist);
                    673:                        addargs(&alist, "%s", ssh_program);
                    674:                        addargs(&alist, "-x");
1.168     djm       675:                        addargs(&alist, "-oClearAllForwardings=yes");
1.129     djm       676:                        addargs(&alist, "-n");
1.168     djm       677:                        for (j = 0; j < remote_remote_args.num; j++) {
                    678:                                addargs(&alist, "%s",
                    679:                                    remote_remote_args.list[j]);
                    680:                        }
1.193     millert   681:
                    682:                        if (sport != -1) {
                    683:                                addargs(&alist, "-p");
                    684:                                addargs(&alist, "%d", sport);
                    685:                        }
                    686:                        if (suser) {
1.129     djm       687:                                addargs(&alist, "-l");
                    688:                                addargs(&alist, "%s", suser);
1.23      markus    689:                        }
1.165     guenther  690:                        addargs(&alist, "--");
1.129     djm       691:                        addargs(&alist, "%s", host);
                    692:                        addargs(&alist, "%s", cmd);
                    693:                        addargs(&alist, "%s", src);
                    694:                        addargs(&alist, "%s%s%s:%s",
                    695:                            tuser ? tuser : "", tuser ? "@" : "",
                    696:                            thost, targ);
                    697:                        if (do_local_cmd(&alist) != 0)
1.109     markus    698:                                errs = 1;
1.18      markus    699:                } else {        /* local to remote */
1.1       deraadt   700:                        if (remin == -1) {
1.171     djm       701:                                xasprintf(&bp, "%s -t %s%s", cmd,
                    702:                                    *targ == '-' ? "-- " : "", targ);
1.193     millert   703:                                if (do_cmd(thost, tuser, tport, bp, &remin,
1.140     deraadt   704:                                    &remout) < 0)
1.18      markus    705:                                        exit(1);
1.1       deraadt   706:                                if (response() < 0)
                    707:                                        exit(1);
1.173     djm       708:                                free(bp);
1.1       deraadt   709:                        }
1.18      markus    710:                        source(1, argv + i);
1.1       deraadt   711:                }
                    712:        }
1.193     millert   713: out:
                    714:        free(tuser);
                    715:        free(thost);
                    716:        free(targ);
                    717:        free(suser);
                    718:        free(host);
                    719:        free(src);
1.1       deraadt   720: }
                    721:
                    722: void
1.104     djm       723: tolocal(int argc, char **argv)
1.1       deraadt   724: {
1.193     millert   725:        char *bp, *host = NULL, *src = NULL, *suser = NULL;
1.129     djm       726:        arglist alist;
1.193     millert   727:        int i, r, sport = -1;
1.129     djm       728:
                    729:        memset(&alist, '\0', sizeof(alist));
                    730:        alist.list = NULL;
1.1       deraadt   731:
                    732:        for (i = 0; i < argc - 1; i++) {
1.193     millert   733:                free(suser);
                    734:                free(host);
                    735:                free(src);
1.194     millert   736:                r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1.193     millert   737:                if (r == -1) {
1.194     millert   738:                        fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1.193     millert   739:                        ++errs;
                    740:                        continue;
                    741:                }
                    742:                if (r != 0)
                    743:                        parse_user_host_path(argv[i], &suser, &host, &src);
                    744:                if (suser != NULL && !okname(suser)) {
                    745:                        ++errs;
                    746:                        continue;
                    747:                }
                    748:                if (!host) {    /* Local to local. */
1.129     djm       749:                        freeargs(&alist);
                    750:                        addargs(&alist, "%s", _PATH_CP);
                    751:                        if (iamrecursive)
                    752:                                addargs(&alist, "-r");
                    753:                        if (pflag)
                    754:                                addargs(&alist, "-p");
1.165     guenther  755:                        addargs(&alist, "--");
1.129     djm       756:                        addargs(&alist, "%s", argv[i]);
                    757:                        addargs(&alist, "%s", argv[argc-1]);
                    758:                        if (do_local_cmd(&alist))
1.1       deraadt   759:                                ++errs;
                    760:                        continue;
                    761:                }
1.193     millert   762:                /* Remote to local. */
1.171     djm       763:                xasprintf(&bp, "%s -f %s%s",
                    764:                    cmd, *src == '-' ? "-- " : "", src);
1.193     millert   765:                if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1.173     djm       766:                        free(bp);
1.18      markus    767:                        ++errs;
                    768:                        continue;
1.1       deraadt   769:                }
1.173     djm       770:                free(bp);
1.1       deraadt   771:                sink(1, argv + argc - 1);
1.18      markus    772:                (void) close(remin);
1.1       deraadt   773:                remin = remout = -1;
                    774:        }
1.193     millert   775:        free(suser);
                    776:        free(host);
                    777:        free(src);
1.1       deraadt   778: }
                    779:
                    780: void
1.104     djm       781: source(int argc, char **argv)
1.1       deraadt   782: {
                    783:        struct stat stb;
                    784:        static BUF buffer;
                    785:        BUF *bp;
1.163     dtucker   786:        off_t i, statbytes;
1.180     djm       787:        size_t amt, nr;
1.125     dtucker   788:        int fd = -1, haderr, indx;
1.181     deraadt   789:        char *last, *name, buf[2048], encname[PATH_MAX];
1.65      deraadt   790:        int len;
1.1       deraadt   791:
                    792:        for (indx = 0; indx < argc; ++indx) {
1.18      markus    793:                name = argv[indx];
1.11      aaron     794:                statbytes = 0;
1.65      deraadt   795:                len = strlen(name);
                    796:                while (len > 1 && name[len-1] == '/')
                    797:                        name[--len] = '\0';
1.158     dtucker   798:                if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
                    799:                        goto syserr;
1.85      markus    800:                if (strchr(name, '\n') != NULL) {
1.158     dtucker   801:                        strnvis(encname, name, sizeof(encname), VIS_NL);
                    802:                        name = encname;
1.85      markus    803:                }
1.1       deraadt   804:                if (fstat(fd, &stb) < 0) {
                    805: syserr:                        run_err("%s: %s", name, strerror(errno));
                    806:                        goto next;
                    807:                }
1.163     dtucker   808:                if (stb.st_size < 0) {
                    809:                        run_err("%s: %s", name, "Negative file size");
                    810:                        goto next;
                    811:                }
1.157     djm       812:                unset_nonblock(fd);
1.1       deraadt   813:                switch (stb.st_mode & S_IFMT) {
                    814:                case S_IFREG:
                    815:                        break;
                    816:                case S_IFDIR:
                    817:                        if (iamrecursive) {
                    818:                                rsource(name, &stb);
                    819:                                goto next;
                    820:                        }
                    821:                        /* FALLTHROUGH */
                    822:                default:
                    823:                        run_err("%s: not a regular file", name);
                    824:                        goto next;
                    825:                }
                    826:                if ((last = strrchr(name, '/')) == NULL)
                    827:                        last = name;
                    828:                else
                    829:                        ++last;
1.11      aaron     830:                curfile = last;
1.1       deraadt   831:                if (pflag) {
1.176     guenther  832:                        if (do_times(remout, verbose_mode, &stb) < 0)
1.1       deraadt   833:                                goto next;
                    834:                }
                    835: #define        FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1.61      markus    836:                snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1.47      markus    837:                    (u_int) (stb.st_mode & FILEMODEMASK),
1.62      markus    838:                    (long long)stb.st_size, last);
1.186     schwarze  839:                if (verbose_mode)
                    840:                        fmprintf(stderr, "Sending file modes: %s", buf);
1.107     deraadt   841:                (void) atomicio(vwrite, remout, buf, strlen(buf));
1.1       deraadt   842:                if (response() < 0)
                    843:                        goto next;
1.161     djm       844:                if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1.127     deraadt   845: next:                  if (fd != -1) {
                    846:                                (void) close(fd);
                    847:                                fd = -1;
                    848:                        }
1.1       deraadt   849:                        continue;
                    850:                }
1.97      fgsch     851:                if (showprogress)
                    852:                        start_progress_meter(curfile, stb.st_size, &statbytes);
1.161     djm       853:                set_nonblock(remout);
1.1       deraadt   854:                for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
                    855:                        amt = bp->cnt;
1.163     dtucker   856:                        if (i + (off_t)amt > stb.st_size)
1.1       deraadt   857:                                amt = stb.st_size - i;
                    858:                        if (!haderr) {
1.180     djm       859:                                if ((nr = atomicio(read, fd,
                    860:                                    bp->buf, amt)) != amt) {
1.122     avsm      861:                                        haderr = errno;
1.180     djm       862:                                        memset(bp->buf + nr, 0, amt - nr);
                    863:                                }
1.1       deraadt   864:                        }
1.161     djm       865:                        /* Keep writing after error to retain sync */
                    866:                        if (haderr) {
                    867:                                (void)atomicio(vwrite, remout, bp->buf, amt);
1.180     djm       868:                                memset(bp->buf, 0, amt);
1.161     djm       869:                                continue;
1.1       deraadt   870:                        }
1.167     djm       871:                        if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1.161     djm       872:                            &statbytes) != amt)
                    873:                                haderr = errno;
1.1       deraadt   874:                }
1.161     djm       875:                unset_nonblock(remout);
1.4       aaron     876:
1.127     deraadt   877:                if (fd != -1) {
                    878:                        if (close(fd) < 0 && !haderr)
                    879:                                haderr = errno;
                    880:                        fd = -1;
                    881:                }
1.1       deraadt   882:                if (!haderr)
1.107     deraadt   883:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt   884:                else
                    885:                        run_err("%s: %s", name, strerror(haderr));
1.18      markus    886:                (void) response();
1.185     dtucker   887:                if (showprogress)
                    888:                        stop_progress_meter();
1.1       deraadt   889:        }
                    890: }
                    891:
                    892: void
1.104     djm       893: rsource(char *name, struct stat *statp)
1.1       deraadt   894: {
                    895:        DIR *dirp;
                    896:        struct dirent *dp;
1.181     deraadt   897:        char *last, *vect[1], path[PATH_MAX];
1.1       deraadt   898:
                    899:        if (!(dirp = opendir(name))) {
                    900:                run_err("%s: %s", name, strerror(errno));
                    901:                return;
                    902:        }
                    903:        last = strrchr(name, '/');
1.183     mmcc      904:        if (last == NULL)
1.1       deraadt   905:                last = name;
                    906:        else
                    907:                last++;
                    908:        if (pflag) {
1.176     guenther  909:                if (do_times(remout, verbose_mode, statp) < 0) {
1.1       deraadt   910:                        closedir(dirp);
                    911:                        return;
                    912:                }
                    913:        }
1.55      deraadt   914:        (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1.47      markus    915:            (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1.18      markus    916:        if (verbose_mode)
1.186     schwarze  917:                fmprintf(stderr, "Entering directory: %s", path);
1.107     deraadt   918:        (void) atomicio(vwrite, remout, path, strlen(path));
1.1       deraadt   919:        if (response() < 0) {
                    920:                closedir(dirp);
                    921:                return;
                    922:        }
1.63      stevesk   923:        while ((dp = readdir(dirp)) != NULL) {
1.1       deraadt   924:                if (dp->d_ino == 0)
                    925:                        continue;
                    926:                if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
                    927:                        continue;
                    928:                if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
                    929:                        run_err("%s/%s: name too long", name, dp->d_name);
                    930:                        continue;
                    931:                }
1.55      deraadt   932:                (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1.1       deraadt   933:                vect[0] = path;
                    934:                source(1, vect);
                    935:        }
1.18      markus    936:        (void) closedir(dirp);
1.107     deraadt   937:        (void) atomicio(vwrite, remout, "E\n", 2);
1.18      markus    938:        (void) response();
1.1       deraadt   939: }
                    940:
1.189     millert   941: #define TYPE_OVERFLOW(type, val) \
                    942:        ((sizeof(type) == 4 && (val) > INT32_MAX) || \
                    943:         (sizeof(type) == 8 && (val) > INT64_MAX) || \
                    944:         (sizeof(type) != 4 && sizeof(type) != 8))
                    945:
1.1       deraadt   946: void
1.104     djm       947: sink(int argc, char **argv)
1.1       deraadt   948: {
                    949:        static BUF buffer;
                    950:        struct stat stb;
1.18      markus    951:        enum {
                    952:                YES, NO, DISPLAYED
                    953:        } wrerr;
1.1       deraadt   954:        BUF *bp;
1.122     avsm      955:        off_t i;
1.124     djm       956:        size_t j, count;
1.140     deraadt   957:        int amt, exists, first, ofd;
                    958:        mode_t mode, omode, mask;
1.97      fgsch     959:        off_t size, statbytes;
1.176     guenther  960:        unsigned long long ull;
1.36      deraadt   961:        int setimes, targisdir, wrerrno = 0;
1.186     schwarze  962:        char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1.40      markus    963:        struct timeval tv[2];
1.1       deraadt   964:
1.66      stevesk   965: #define        atime   tv[0]
                    966: #define        mtime   tv[1]
1.118     deraadt   967: #define        SCREWUP(str)    { why = str; goto screwup; }
1.1       deraadt   968:
1.189     millert   969:        if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
                    970:                SCREWUP("Unexpected off_t/time_t size");
                    971:
1.1       deraadt   972:        setimes = targisdir = 0;
                    973:        mask = umask(0);
                    974:        if (!pflag)
1.18      markus    975:                (void) umask(mask);
1.1       deraadt   976:        if (argc != 1) {
                    977:                run_err("ambiguous target");
                    978:                exit(1);
                    979:        }
                    980:        targ = *argv;
                    981:        if (targetshouldbedirectory)
                    982:                verifydir(targ);
1.18      markus    983:
1.107     deraadt   984:        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt   985:        if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
                    986:                targisdir = 1;
                    987:        for (first = 1;; first = 0) {
                    988:                cp = buf;
1.122     avsm      989:                if (atomicio(read, remin, cp, 1) != 1)
1.1       deraadt   990:                        return;
                    991:                if (*cp++ == '\n')
                    992:                        SCREWUP("unexpected <newline>");
                    993:                do {
1.30      deraadt   994:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt   995:                                SCREWUP("lost connection");
                    996:                        *cp++ = ch;
                    997:                } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
                    998:                *cp = 0;
1.114     markus    999:                if (verbose_mode)
1.186     schwarze 1000:                        fmprintf(stderr, "Sink: %s", buf);
1.1       deraadt  1001:
                   1002:                if (buf[0] == '\01' || buf[0] == '\02') {
1.186     schwarze 1003:                        if (iamremote == 0) {
                   1004:                                (void) snmprintf(visbuf, sizeof(visbuf),
                   1005:                                    NULL, "%s", buf + 1);
1.107     deraadt  1006:                                (void) atomicio(vwrite, STDERR_FILENO,
1.186     schwarze 1007:                                    visbuf, strlen(visbuf));
                   1008:                        }
1.1       deraadt  1009:                        if (buf[0] == '\02')
                   1010:                                exit(1);
                   1011:                        ++errs;
                   1012:                        continue;
                   1013:                }
                   1014:                if (buf[0] == 'E') {
1.107     deraadt  1015:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt  1016:                        return;
                   1017:                }
                   1018:                if (ch == '\n')
                   1019:                        *--cp = 0;
                   1020:
                   1021:                cp = buf;
                   1022:                if (*cp == 'T') {
                   1023:                        setimes++;
                   1024:                        cp++;
1.176     guenther 1025:                        if (!isdigit((unsigned char)*cp))
                   1026:                                SCREWUP("mtime.sec not present");
                   1027:                        ull = strtoull(cp, &cp, 10);
1.66      stevesk  1028:                        if (!cp || *cp++ != ' ')
1.1       deraadt  1029:                                SCREWUP("mtime.sec not delimited");
1.189     millert  1030:                        if (TYPE_OVERFLOW(time_t, ull))
1.176     guenther 1031:                                setimes = 0;    /* out of range */
                   1032:                        mtime.tv_sec = ull;
1.66      stevesk  1033:                        mtime.tv_usec = strtol(cp, &cp, 10);
1.176     guenther 1034:                        if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
                   1035:                            mtime.tv_usec > 999999)
1.1       deraadt  1036:                                SCREWUP("mtime.usec not delimited");
1.176     guenther 1037:                        if (!isdigit((unsigned char)*cp))
                   1038:                                SCREWUP("atime.sec not present");
                   1039:                        ull = strtoull(cp, &cp, 10);
1.66      stevesk  1040:                        if (!cp || *cp++ != ' ')
1.1       deraadt  1041:                                SCREWUP("atime.sec not delimited");
1.189     millert  1042:                        if (TYPE_OVERFLOW(time_t, ull))
1.176     guenther 1043:                                setimes = 0;    /* out of range */
                   1044:                        atime.tv_sec = ull;
1.66      stevesk  1045:                        atime.tv_usec = strtol(cp, &cp, 10);
1.176     guenther 1046:                        if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
                   1047:                            atime.tv_usec > 999999)
1.1       deraadt  1048:                                SCREWUP("atime.usec not delimited");
1.107     deraadt  1049:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt  1050:                        continue;
                   1051:                }
                   1052:                if (*cp != 'C' && *cp != 'D') {
                   1053:                        /*
                   1054:                         * Check for the case "rcp remote:foo\* local:bar".
                   1055:                         * In this case, the line "No match." can be returned
                   1056:                         * by the shell before the rcp command on the remote is
                   1057:                         * executed so the ^Aerror_message convention isn't
                   1058:                         * followed.
                   1059:                         */
                   1060:                        if (first) {
                   1061:                                run_err("%s", cp);
                   1062:                                exit(1);
                   1063:                        }
                   1064:                        SCREWUP("expected control record");
                   1065:                }
                   1066:                mode = 0;
                   1067:                for (++cp; cp < buf + 5; cp++) {
                   1068:                        if (*cp < '0' || *cp > '7')
                   1069:                                SCREWUP("bad mode");
                   1070:                        mode = (mode << 3) | (*cp - '0');
                   1071:                }
                   1072:                if (*cp++ != ' ')
                   1073:                        SCREWUP("mode not delimited");
                   1074:
1.188     millert  1075:                if (!isdigit((unsigned char)*cp))
                   1076:                        SCREWUP("size not present");
                   1077:                ull = strtoull(cp, &cp, 10);
                   1078:                if (!cp || *cp++ != ' ')
1.1       deraadt  1079:                        SCREWUP("size not delimited");
1.189     millert  1080:                if (TYPE_OVERFLOW(off_t, ull))
1.188     millert  1081:                        SCREWUP("size out of range");
                   1082:                size = (off_t)ull;
                   1083:
1.114     markus   1084:                if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
                   1085:                        run_err("error: unexpected filename: %s", cp);
                   1086:                        exit(1);
                   1087:                }
1.1       deraadt  1088:                if (targisdir) {
                   1089:                        static char *namebuf;
1.124     djm      1090:                        static size_t cursize;
1.1       deraadt  1091:                        size_t need;
                   1092:
                   1093:                        need = strlen(targ) + strlen(cp) + 250;
1.55      deraadt  1094:                        if (need > cursize) {
1.173     djm      1095:                                free(namebuf);
1.18      markus   1096:                                namebuf = xmalloc(need);
1.55      deraadt  1097:                                cursize = need;
                   1098:                        }
                   1099:                        (void) snprintf(namebuf, need, "%s%s%s", targ,
1.88      mouring  1100:                            strcmp(targ, "/") ? "/" : "", cp);
1.1       deraadt  1101:                        np = namebuf;
                   1102:                } else
                   1103:                        np = targ;
1.12      aaron    1104:                curfile = cp;
1.1       deraadt  1105:                exists = stat(np, &stb) == 0;
                   1106:                if (buf[0] == 'D') {
                   1107:                        int mod_flag = pflag;
1.114     markus   1108:                        if (!iamrecursive)
                   1109:                                SCREWUP("received directory without -r");
1.1       deraadt  1110:                        if (exists) {
                   1111:                                if (!S_ISDIR(stb.st_mode)) {
                   1112:                                        errno = ENOTDIR;
                   1113:                                        goto bad;
                   1114:                                }
                   1115:                                if (pflag)
1.18      markus   1116:                                        (void) chmod(np, mode);
1.1       deraadt  1117:                        } else {
1.18      markus   1118:                                /* Handle copying from a read-only
                   1119:                                   directory */
1.1       deraadt  1120:                                mod_flag = 1;
                   1121:                                if (mkdir(np, mode | S_IRWXU) < 0)
                   1122:                                        goto bad;
                   1123:                        }
1.58      danh     1124:                        vect[0] = xstrdup(np);
1.1       deraadt  1125:                        sink(1, vect);
                   1126:                        if (setimes) {
                   1127:                                setimes = 0;
1.59      deraadt  1128:                                if (utimes(vect[0], tv) < 0)
1.18      markus   1129:                                        run_err("%s: set times: %s",
1.59      deraadt  1130:                                            vect[0], strerror(errno));
1.1       deraadt  1131:                        }
                   1132:                        if (mod_flag)
1.59      deraadt  1133:                                (void) chmod(vect[0], mode);
1.173     djm      1134:                        free(vect[0]);
1.1       deraadt  1135:                        continue;
                   1136:                }
                   1137:                omode = mode;
1.174     dtucker  1138:                mode |= S_IWUSR;
1.71      markus   1139:                if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1.1       deraadt  1140: bad:                   run_err("%s: %s", np, strerror(errno));
                   1141:                        continue;
                   1142:                }
1.107     deraadt  1143:                (void) atomicio(vwrite, remout, "", 1);
1.161     djm      1144:                if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1.18      markus   1145:                        (void) close(ofd);
1.1       deraadt  1146:                        continue;
                   1147:                }
                   1148:                cp = bp->buf;
                   1149:                wrerr = NO;
1.7       deraadt  1150:
1.12      aaron    1151:                statbytes = 0;
1.97      fgsch    1152:                if (showprogress)
                   1153:                        start_progress_meter(curfile, size, &statbytes);
1.161     djm      1154:                set_nonblock(remin);
                   1155:                for (count = i = 0; i < size; i += bp->cnt) {
                   1156:                        amt = bp->cnt;
1.1       deraadt  1157:                        if (i + amt > size)
                   1158:                                amt = size - i;
                   1159:                        count += amt;
                   1160:                        do {
1.167     djm      1161:                                j = atomicio6(read, remin, cp, amt,
                   1162:                                    scpio, &statbytes);
1.122     avsm     1163:                                if (j == 0) {
1.161     djm      1164:                                        run_err("%s", j != EPIPE ?
                   1165:                                            strerror(errno) :
1.63      stevesk  1166:                                            "dropped connection");
1.1       deraadt  1167:                                        exit(1);
                   1168:                                }
                   1169:                                amt -= j;
                   1170:                                cp += j;
                   1171:                        } while (amt > 0);
1.112     djm      1172:
1.1       deraadt  1173:                        if (count == bp->cnt) {
                   1174:                                /* Keep reading so we stay sync'd up. */
                   1175:                                if (wrerr == NO) {
1.122     avsm     1176:                                        if (atomicio(vwrite, ofd, bp->buf,
                   1177:                                            count) != count) {
1.1       deraadt  1178:                                                wrerr = YES;
1.122     avsm     1179:                                                wrerrno = errno;
1.1       deraadt  1180:                                        }
                   1181:                                }
                   1182:                                count = 0;
                   1183:                                cp = bp->buf;
                   1184:                        }
                   1185:                }
1.161     djm      1186:                unset_nonblock(remin);
1.1       deraadt  1187:                if (count != 0 && wrerr == NO &&
1.122     avsm     1188:                    atomicio(vwrite, ofd, bp->buf, count) != count) {
1.1       deraadt  1189:                        wrerr = YES;
1.122     avsm     1190:                        wrerrno = errno;
1.1       deraadt  1191:                }
1.159     djm      1192:                if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
                   1193:                    ftruncate(ofd, size) != 0) {
1.1       deraadt  1194:                        run_err("%s: truncate: %s", np, strerror(errno));
                   1195:                        wrerr = DISPLAYED;
                   1196:                }
                   1197:                if (pflag) {
                   1198:                        if (exists || omode != mode)
1.116     dtucker  1199:                                if (fchmod(ofd, omode)) {
1.1       deraadt  1200:                                        run_err("%s: set mode: %s",
1.63      stevesk  1201:                                            np, strerror(errno));
1.116     dtucker  1202:                                        wrerr = DISPLAYED;
                   1203:                                }
1.1       deraadt  1204:                } else {
                   1205:                        if (!exists && omode != mode)
1.116     dtucker  1206:                                if (fchmod(ofd, omode & ~mask)) {
1.1       deraadt  1207:                                        run_err("%s: set mode: %s",
1.63      stevesk  1208:                                            np, strerror(errno));
1.116     dtucker  1209:                                        wrerr = DISPLAYED;
                   1210:                                }
1.1       deraadt  1211:                }
1.33      provos   1212:                if (close(ofd) == -1) {
                   1213:                        wrerr = YES;
                   1214:                        wrerrno = errno;
                   1215:                }
1.18      markus   1216:                (void) response();
1.185     dtucker  1217:                if (showprogress)
                   1218:                        stop_progress_meter();
1.1       deraadt  1219:                if (setimes && wrerr == NO) {
                   1220:                        setimes = 0;
1.40      markus   1221:                        if (utimes(np, tv) < 0) {
1.1       deraadt  1222:                                run_err("%s: set times: %s",
1.63      stevesk  1223:                                    np, strerror(errno));
1.1       deraadt  1224:                                wrerr = DISPLAYED;
                   1225:                        }
                   1226:                }
1.18      markus   1227:                switch (wrerr) {
1.1       deraadt  1228:                case YES:
                   1229:                        run_err("%s: %s", np, strerror(wrerrno));
                   1230:                        break;
                   1231:                case NO:
1.107     deraadt  1232:                        (void) atomicio(vwrite, remout, "", 1);
1.1       deraadt  1233:                        break;
                   1234:                case DISPLAYED:
                   1235:                        break;
                   1236:                }
                   1237:        }
                   1238: screwup:
                   1239:        run_err("protocol error: %s", why);
                   1240:        exit(1);
                   1241: }
                   1242:
                   1243: int
1.86      itojun   1244: response(void)
1.1       deraadt  1245: {
1.186     schwarze 1246:        char ch, *cp, resp, rbuf[2048], visbuf[2048];
1.1       deraadt  1247:
1.30      deraadt  1248:        if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1.1       deraadt  1249:                lostconn(0);
                   1250:
                   1251:        cp = rbuf;
1.18      markus   1252:        switch (resp) {
                   1253:        case 0:         /* ok */
1.1       deraadt  1254:                return (0);
                   1255:        default:
                   1256:                *cp++ = resp;
                   1257:                /* FALLTHROUGH */
1.18      markus   1258:        case 1:         /* error, followed by error msg */
                   1259:        case 2:         /* fatal error, "" */
1.1       deraadt  1260:                do {
1.30      deraadt  1261:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1.1       deraadt  1262:                                lostconn(0);
                   1263:                        *cp++ = ch;
                   1264:                } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
                   1265:
1.186     schwarze 1266:                if (!iamremote) {
                   1267:                        cp[-1] = '\0';
                   1268:                        (void) snmprintf(visbuf, sizeof(visbuf),
                   1269:                            NULL, "%s\n", rbuf);
                   1270:                        (void) atomicio(vwrite, STDERR_FILENO,
                   1271:                            visbuf, strlen(visbuf));
                   1272:                }
1.1       deraadt  1273:                ++errs;
                   1274:                if (resp == 1)
                   1275:                        return (-1);
                   1276:                exit(1);
                   1277:        }
                   1278:        /* NOTREACHED */
                   1279: }
                   1280:
                   1281: void
1.86      itojun   1282: usage(void)
1.1       deraadt  1283: {
1.83      stevesk  1284:        (void) fprintf(stderr,
1.191     jmc      1285:            "usage: scp [-346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1.193     millert  1286:            "           [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
1.1       deraadt  1287:        exit(1);
                   1288: }
                   1289:
                   1290: void
1.18      markus   1291: run_err(const char *fmt,...)
1.1       deraadt  1292: {
                   1293:        static FILE *fp;
                   1294:        va_list ap;
                   1295:
                   1296:        ++errs;
1.136     biorn    1297:        if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
                   1298:                (void) fprintf(fp, "%c", 0x01);
                   1299:                (void) fprintf(fp, "scp: ");
                   1300:                va_start(ap, fmt);
                   1301:                (void) vfprintf(fp, fmt, ap);
                   1302:                va_end(ap);
                   1303:                (void) fprintf(fp, "\n");
                   1304:                (void) fflush(fp);
                   1305:        }
1.18      markus   1306:
                   1307:        if (!iamremote) {
1.73      markus   1308:                va_start(ap, fmt);
1.186     schwarze 1309:                vfmprintf(stderr, fmt, ap);
1.73      markus   1310:                va_end(ap);
1.18      markus   1311:                fprintf(stderr, "\n");
                   1312:        }
1.1       deraadt  1313: }
                   1314:
                   1315: void
1.104     djm      1316: verifydir(char *cp)
1.1       deraadt  1317: {
                   1318:        struct stat stb;
                   1319:
                   1320:        if (!stat(cp, &stb)) {
                   1321:                if (S_ISDIR(stb.st_mode))
                   1322:                        return;
                   1323:                errno = ENOTDIR;
                   1324:        }
                   1325:        run_err("%s: %s", cp, strerror(errno));
1.123     avsm     1326:        killchild(0);
1.1       deraadt  1327: }
                   1328:
                   1329: int
1.104     djm      1330: okname(char *cp0)
1.1       deraadt  1331: {
                   1332:        int c;
                   1333:        char *cp;
                   1334:
                   1335:        cp = cp0;
                   1336:        do {
1.75      deraadt  1337:                c = (int)*cp;
1.1       deraadt  1338:                if (c & 0200)
                   1339:                        goto bad;
1.179     deraadt  1340:                if (!isalpha(c) && !isdigit((unsigned char)c)) {
1.101     markus   1341:                        switch (c) {
                   1342:                        case '\'':
                   1343:                        case '"':
                   1344:                        case '`':
                   1345:                        case ' ':
                   1346:                        case '#':
                   1347:                                goto bad;
                   1348:                        default:
                   1349:                                break;
                   1350:                        }
                   1351:                }
1.1       deraadt  1352:        } while (*++cp);
                   1353:        return (1);
                   1354:
1.186     schwarze 1355: bad:   fmprintf(stderr, "%s: invalid user name\n", cp0);
1.1       deraadt  1356:        return (0);
                   1357: }
                   1358:
                   1359: BUF *
1.104     djm      1360: allocbuf(BUF *bp, int fd, int blksize)
1.1       deraadt  1361: {
                   1362:        size_t size;
                   1363:        struct stat stb;
                   1364:
                   1365:        if (fstat(fd, &stb) < 0) {
                   1366:                run_err("fstat: %s", strerror(errno));
                   1367:                return (0);
                   1368:        }
1.187     deraadt  1369:        size = ROUNDUP(stb.st_blksize, blksize);
1.95      markus   1370:        if (size == 0)
1.18      markus   1371:                size = blksize;
1.1       deraadt  1372:        if (bp->cnt >= size)
                   1373:                return (bp);
1.192     deraadt  1374:        bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1.1       deraadt  1375:        bp->cnt = size;
                   1376:        return (bp);
                   1377: }
                   1378:
                   1379: void
1.104     djm      1380: lostconn(int signo)
1.1       deraadt  1381: {
                   1382:        if (!iamremote)
1.172     dtucker  1383:                (void)write(STDERR_FILENO, "lost connection\n", 16);
1.74      markus   1384:        if (signo)
                   1385:                _exit(1);
                   1386:        else
                   1387:                exit(1);
1.4       aaron    1388: }