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

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