[BACK]Return to scp.c CVS log [TXT][DIR] Up to [cvs.NetBSD.org] / src / crypto / external / bsd / openssh / dist

Annotation of src/crypto/external/bsd/openssh/dist/scp.c, Revision 1.1.1.26

1.1.1.26! christos    1: /* $OpenBSD: scp.c,v 1.248 2022/05/13 06:31:50 djm Exp $ */
1.1       christos    2: /*
                      3:  * scp - secure remote copy.  This is basically patched BSD rcp which
                      4:  * uses ssh to do the data transfer (instead of using rcmd).
                      5:  *
                      6:  * NOTE: This version should NOT be suid root.  (This uses ssh to
                      7:  * do the transfer and ssh has the necessary privileges.)
                      8:  *
                      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".
                     16:  */
                     17: /*
                     18:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     19:  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
                     20:  *
                     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.
                     29:  *
                     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:  */
                     41:
                     42: /*
                     43:  * Parts from:
                     44:  *
                     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.
                     56:  * 3. Neither the name of the University nor the names of its contributors
                     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:
                     74: #include <sys/types.h>
                     75: #include <sys/poll.h>
                     76: #include <sys/wait.h>
                     77: #include <sys/stat.h>
                     78: #include <sys/time.h>
                     79: #include <sys/uio.h>
                     80:
                     81: #include <ctype.h>
                     82: #include <dirent.h>
                     83: #include <errno.h>
                     84: #include <fcntl.h>
1.1.1.15  christos   85: #include <fnmatch.h>
1.1.1.22  christos   86: #include <glob.h>
                     87: #include <libgen.h>
1.1.1.10  christos   88: #include <locale.h>
1.1       christos   89: #include <pwd.h>
                     90: #include <signal.h>
                     91: #include <stdarg.h>
1.1.1.12  christos   92: #include <stdint.h>
1.1       christos   93: #include <stdio.h>
                     94: #include <stdlib.h>
                     95: #include <string.h>
                     96: #include <time.h>
                     97: #include <unistd.h>
1.1.1.7   christos   98: #include <limits.h>
1.1       christos   99: #include <vis.h>
                    100:
                    101: #include "xmalloc.h"
1.1.1.13  christos  102: #include "ssh.h"
1.1       christos  103: #include "atomicio.h"
                    104: #include "pathnames.h"
                    105: #include "log.h"
                    106: #include "misc.h"
                    107: #include "progressmeter.h"
1.1.1.10  christos  108: #include "utf8.h"
1.1.1.24  christos  109: #include "sftp.h"
1.1       christos  110:
1.1.1.22  christos  111: #include "sftp-common.h"
                    112: #include "sftp-client.h"
                    113:
1.1       christos  114: #define COPY_BUFLEN    16384
                    115:
1.1.1.22  christos  116: int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
                    117: int do_cmd2(char *, char *, int, char *, int, int);
1.1       christos  118:
                    119: /* Struct for addargs */
                    120: arglist args;
1.1.1.3   christos  121: arglist remote_remote_args;
1.1       christos  122:
                    123: /* Bandwidth limit */
1.1.1.3   christos  124: long long limit_kbps = 0;
                    125: struct bwlimit bwlimit;
1.1       christos  126:
                    127: /* Name of current file being transferred. */
                    128: char *curfile;
                    129:
                    130: /* This is set to non-zero to enable verbose mode. */
                    131: int verbose_mode = 0;
1.1.1.22  christos  132: LogLevel log_level = SYSLOG_LEVEL_INFO;
1.1       christos  133:
                    134: /* This is set to zero if the progressmeter is not desired. */
                    135: int showprogress = 1;
                    136:
1.1.1.3   christos  137: /*
                    138:  * This is set to non-zero if remote-remote copy should be piped
                    139:  * through this process.
                    140:  */
1.1.1.22  christos  141: int throughlocal = 1;
1.1.1.3   christos  142:
1.1.1.13  christos  143: /* Non-standard port to use for the ssh connection or -1. */
                    144: int sshport = -1;
                    145:
1.1       christos  146: /* This is the program to execute for the secured connection. ("ssh" or -S) */
                    147: char *ssh_program = _PATH_SSH_PROGRAM;
                    148:
                    149: /* This is used to store the pid of ssh_program */
                    150: pid_t do_cmd_pid = -1;
1.1.1.22  christos  151: pid_t do_cmd_pid2 = -1;
                    152:
                    153: /* Needed for sftp */
                    154: volatile sig_atomic_t interrupted = 0;
                    155:
                    156: int remote_glob(struct sftp_conn *, const char *, int,
                    157:     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
1.1       christos  158:
                    159: static void
                    160: killchild(int signo)
                    161: {
                    162:        if (do_cmd_pid > 1) {
                    163:                kill(do_cmd_pid, signo ? signo : SIGTERM);
                    164:                waitpid(do_cmd_pid, NULL, 0);
                    165:        }
1.1.1.22  christos  166:        if (do_cmd_pid2 > 1) {
                    167:                kill(do_cmd_pid2, signo ? signo : SIGTERM);
                    168:                waitpid(do_cmd_pid2, NULL, 0);
                    169:        }
1.1       christos  170:
                    171:        if (signo)
                    172:                _exit(1);
                    173:        exit(1);
                    174: }
                    175:
1.1.1.2   adam      176: static void
1.1.1.22  christos  177: suspone(int pid, int signo)
1.1.1.2   adam      178: {
                    179:        int status;
                    180:
1.1.1.22  christos  181:        if (pid > 1) {
                    182:                kill(pid, signo);
                    183:                while (waitpid(pid, &status, WUNTRACED) == -1 &&
1.1.1.2   adam      184:                    errno == EINTR)
                    185:                        ;
                    186:        }
                    187: }
                    188:
1.1.1.22  christos  189: static void
                    190: suspchild(int signo)
                    191: {
                    192:        suspone(do_cmd_pid, signo);
                    193:        suspone(do_cmd_pid2, signo);
                    194:        kill(getpid(), SIGSTOP);
                    195: }
                    196:
1.1       christos  197: static int
                    198: do_local_cmd(arglist *a)
                    199: {
                    200:        u_int i;
                    201:        int status;
                    202:        pid_t pid;
                    203:
                    204:        if (a->num == 0)
                    205:                fatal("do_local_cmd: no arguments");
                    206:
                    207:        if (verbose_mode) {
                    208:                fprintf(stderr, "Executing:");
                    209:                for (i = 0; i < a->num; i++)
1.1.1.10  christos  210:                        fmprintf(stderr, " %s", a->list[i]);
1.1       christos  211:                fprintf(stderr, "\n");
                    212:        }
                    213:        if ((pid = fork()) == -1)
                    214:                fatal("do_local_cmd: fork: %s", strerror(errno));
                    215:
                    216:        if (pid == 0) {
                    217:                execvp(a->list[0], a->list);
                    218:                perror(a->list[0]);
                    219:                exit(1);
                    220:        }
                    221:
                    222:        do_cmd_pid = pid;
1.1.1.17  christos  223:        ssh_signal(SIGTERM, killchild);
                    224:        ssh_signal(SIGINT, killchild);
                    225:        ssh_signal(SIGHUP, killchild);
1.1       christos  226:
                    227:        while (waitpid(pid, &status, 0) == -1)
                    228:                if (errno != EINTR)
                    229:                        fatal("do_local_cmd: waitpid: %s", strerror(errno));
                    230:
                    231:        do_cmd_pid = -1;
                    232:
                    233:        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
                    234:                return (-1);
                    235:
                    236:        return (0);
                    237: }
                    238:
                    239: /*
                    240:  * This function executes the given command as the specified user on the
                    241:  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
                    242:  * assigns the input and output file descriptors on success.
                    243:  */
                    244:
                    245: int
1.1.1.22  christos  246: do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
                    247:     char *cmd, int *fdin, int *fdout, pid_t *pid)
1.1       christos  248: {
                    249:        int pin[2], pout[2], reserved[2];
                    250:
                    251:        if (verbose_mode)
1.1.1.10  christos  252:                fmprintf(stderr,
1.1       christos  253:                    "Executing: program %s host %s, user %s, command %s\n",
1.1.1.22  christos  254:                    program, host,
1.1       christos  255:                    remuser ? remuser : "(unspecified)", cmd);
                    256:
1.1.1.13  christos  257:        if (port == -1)
                    258:                port = sshport;
                    259:
1.1       christos  260:        /*
                    261:         * Reserve two descriptors so that the real pipes won't get
                    262:         * descriptors 0 and 1 because that will screw up dup2 below.
                    263:         */
1.1.1.16  christos  264:        if (pipe(reserved) == -1)
1.1       christos  265:                fatal("pipe: %s", strerror(errno));
                    266:
                    267:        /* Create a socket pair for communicating with ssh. */
1.1.1.16  christos  268:        if (pipe(pin) == -1)
1.1       christos  269:                fatal("pipe: %s", strerror(errno));
1.1.1.16  christos  270:        if (pipe(pout) == -1)
1.1       christos  271:                fatal("pipe: %s", strerror(errno));
                    272:
                    273:        /* Free the reserved descriptors. */
                    274:        close(reserved[0]);
                    275:        close(reserved[1]);
                    276:
1.1.1.17  christos  277:        ssh_signal(SIGTSTP, suspchild);
                    278:        ssh_signal(SIGTTIN, suspchild);
                    279:        ssh_signal(SIGTTOU, suspchild);
1.1.1.2   adam      280:
1.1       christos  281:        /* Fork a child to execute the command on the remote host using ssh. */
1.1.1.22  christos  282:        *pid = fork();
                    283:        if (*pid == 0) {
1.1       christos  284:                /* Child. */
                    285:                close(pin[1]);
                    286:                close(pout[0]);
                    287:                dup2(pin[0], 0);
                    288:                dup2(pout[1], 1);
                    289:                close(pin[0]);
                    290:                close(pout[1]);
                    291:
1.1.1.22  christos  292:                replacearg(&args, 0, "%s", program);
1.1.1.13  christos  293:                if (port != -1) {
                    294:                        addargs(&args, "-p");
                    295:                        addargs(&args, "%d", port);
                    296:                }
1.1.1.2   adam      297:                if (remuser != NULL) {
                    298:                        addargs(&args, "-l");
                    299:                        addargs(&args, "%s", remuser);
                    300:                }
1.1.1.22  christos  301:                if (subsystem)
                    302:                        addargs(&args, "-s");
1.1.1.2   adam      303:                addargs(&args, "--");
1.1       christos  304:                addargs(&args, "%s", host);
                    305:                addargs(&args, "%s", cmd);
                    306:
1.1.1.22  christos  307:                execvp(program, args.list);
                    308:                perror(program);
1.1       christos  309:                exit(1);
1.1.1.22  christos  310:        } else if (*pid == -1) {
1.1       christos  311:                fatal("fork: %s", strerror(errno));
                    312:        }
                    313:        /* Parent.  Close the other side, and return the local side. */
                    314:        close(pin[0]);
                    315:        *fdout = pin[1];
                    316:        close(pout[1]);
                    317:        *fdin = pout[0];
1.1.1.17  christos  318:        ssh_signal(SIGTERM, killchild);
                    319:        ssh_signal(SIGINT, killchild);
                    320:        ssh_signal(SIGHUP, killchild);
1.1       christos  321:        return 0;
                    322: }
                    323:
1.1.1.3   christos  324: /*
1.1.1.14  christos  325:  * This function executes a command similar to do_cmd(), but expects the
1.1.1.3   christos  326:  * input and output descriptors to be setup by a previous call to do_cmd().
                    327:  * This way the input and output of two commands can be connected.
                    328:  */
                    329: int
1.1.1.22  christos  330: do_cmd2(char *host, char *remuser, int port, char *cmd,
                    331:     int fdin, int fdout)
1.1.1.3   christos  332: {
                    333:        int status;
1.1.1.22  christos  334:        pid_t pid;
1.1.1.3   christos  335:
                    336:        if (verbose_mode)
1.1.1.10  christos  337:                fmprintf(stderr,
1.1.1.3   christos  338:                    "Executing: 2nd program %s host %s, user %s, command %s\n",
                    339:                    ssh_program, host,
                    340:                    remuser ? remuser : "(unspecified)", cmd);
                    341:
1.1.1.13  christos  342:        if (port == -1)
                    343:                port = sshport;
                    344:
1.1.1.3   christos  345:        /* Fork a child to execute the command on the remote host using ssh. */
                    346:        pid = fork();
                    347:        if (pid == 0) {
                    348:                dup2(fdin, 0);
                    349:                dup2(fdout, 1);
                    350:
                    351:                replacearg(&args, 0, "%s", ssh_program);
1.1.1.13  christos  352:                if (port != -1) {
                    353:                        addargs(&args, "-p");
                    354:                        addargs(&args, "%d", port);
                    355:                }
1.1.1.3   christos  356:                if (remuser != NULL) {
                    357:                        addargs(&args, "-l");
                    358:                        addargs(&args, "%s", remuser);
                    359:                }
1.1.1.18  christos  360:                addargs(&args, "-oBatchMode=yes");
1.1.1.3   christos  361:                addargs(&args, "--");
                    362:                addargs(&args, "%s", host);
                    363:                addargs(&args, "%s", cmd);
                    364:
                    365:                execvp(ssh_program, args.list);
                    366:                perror(ssh_program);
                    367:                exit(1);
                    368:        } else if (pid == -1) {
                    369:                fatal("fork: %s", strerror(errno));
                    370:        }
                    371:        while (waitpid(pid, &status, 0) == -1)
                    372:                if (errno != EINTR)
                    373:                        fatal("do_cmd2: waitpid: %s", strerror(errno));
                    374:        return 0;
                    375: }
                    376:
1.1       christos  377: typedef struct {
                    378:        size_t cnt;
                    379:        char *buf;
                    380: } BUF;
                    381:
                    382: BUF *allocbuf(BUF *, int, int);
                    383: void lostconn(int);
                    384: int okname(char *);
1.1.1.19  christos  385: void run_err(const char *,...)
                    386:     __attribute__((__format__ (printf, 1, 2)))
                    387:     __attribute__((__nonnull__ (1)));
                    388: int note_err(const char *,...)
                    389:     __attribute__((__format__ (printf, 1, 2)));
1.1       christos  390: void verifydir(char *);
                    391:
                    392: struct passwd *pwd;
                    393: uid_t userid;
1.1.1.22  christos  394: int errs, remin, remout, remin2, remout2;
1.1.1.15  christos  395: int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
1.1       christos  396:
                    397: #define        CMDNEEDS        64
                    398: char cmd[CMDNEEDS];            /* must hold "rcp -r -p -d\0" */
                    399:
1.1.1.22  christos  400: enum scp_mode_e {
                    401:        MODE_SCP,
                    402:        MODE_SFTP
                    403: };
                    404:
1.1       christos  405: int response(void);
                    406: void rsource(char *, struct stat *);
1.1.1.15  christos  407: void sink(int, char *[], const char *);
1.1       christos  408: void source(int, char *[]);
1.1.1.22  christos  409: void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
                    410: void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
1.1       christos  411: void usage(void);
                    412:
1.1.1.22  christos  413: void source_sftp(int, char *, char *, struct sftp_conn *);
                    414: void sink_sftp(int, char *, const char *, struct sftp_conn *);
                    415: void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
                    416:     char *, char *);
                    417:
1.1       christos  418: int
                    419: main(int argc, char **argv)
                    420: {
                    421:        int ch, fflag, tflag, status, n;
1.1.1.22  christos  422:        char **newargv, *argv0;
1.1.1.3   christos  423:        const char *errstr;
1.1       christos  424:        extern char *optarg;
                    425:        extern int optind;
1.1.1.25  christos  426:        enum scp_mode_e mode = MODE_SFTP;
1.1.1.22  christos  427:        char *sftp_direct = NULL;
1.1       christos  428:
                    429:        /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
                    430:        sanitise_stdfd();
                    431:
1.1.1.10  christos  432:        setlocale(LC_CTYPE, "");
                    433:
1.1       christos  434:        /* Copy argv, because we modify it */
1.1.1.22  christos  435:        argv0 = argv[0];
1.1.1.11  christos  436:        newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
1.1       christos  437:        for (n = 0; n < argc; n++)
                    438:                newargv[n] = xstrdup(argv[n]);
                    439:        argv = newargv;
                    440:
1.1.1.23  christos  441:        log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
1.1.1.22  christos  442:
1.1       christos  443:        memset(&args, '\0', sizeof(args));
1.1.1.3   christos  444:        memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
                    445:        args.list = remote_remote_args.list = NULL;
1.1       christos  446:        addargs(&args, "%s", ssh_program);
                    447:        addargs(&args, "-x");
1.1.1.3   christos  448:        addargs(&args, "-oPermitLocalCommand=no");
                    449:        addargs(&args, "-oClearAllForwardings=yes");
1.1.1.13  christos  450:        addargs(&args, "-oRemoteCommand=none");
                    451:        addargs(&args, "-oRequestTTY=no");
1.1       christos  452:
1.1.1.15  christos  453:        fflag = Tflag = tflag = 0;
                    454:        while ((ch = getopt(argc, argv,
1.1.1.22  christos  455:            "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:")) != -1) {
1.1       christos  456:                switch (ch) {
                    457:                /* User-visible flags. */
                    458:                case '1':
1.1.1.12  christos  459:                        fatal("SSH protocol v.1 is no longer supported");
                    460:                        break;
1.1       christos  461:                case '2':
1.1.1.12  christos  462:                        /* Ignored */
                    463:                        break;
1.1.1.19  christos  464:                case 'A':
1.1       christos  465:                case '4':
                    466:                case '6':
                    467:                case 'C':
                    468:                        addargs(&args, "-%c", ch);
1.1.1.3   christos  469:                        addargs(&remote_remote_args, "-%c", ch);
                    470:                        break;
1.1.1.22  christos  471:                case 'D':
                    472:                        sftp_direct = optarg;
                    473:                        break;
1.1.1.3   christos  474:                case '3':
                    475:                        throughlocal = 1;
1.1       christos  476:                        break;
1.1.1.22  christos  477:                case 'R':
                    478:                        throughlocal = 0;
                    479:                        break;
1.1       christos  480:                case 'o':
                    481:                case 'c':
                    482:                case 'i':
                    483:                case 'F':
1.1.1.15  christos  484:                case 'J':
1.1.1.3   christos  485:                        addargs(&remote_remote_args, "-%c", ch);
                    486:                        addargs(&remote_remote_args, "%s", optarg);
1.1.1.2   adam      487:                        addargs(&args, "-%c", ch);
                    488:                        addargs(&args, "%s", optarg);
1.1       christos  489:                        break;
1.1.1.22  christos  490:                case 'O':
                    491:                        mode = MODE_SCP;
                    492:                        break;
                    493:                case 's':
                    494:                        mode = MODE_SFTP;
                    495:                        break;
1.1       christos  496:                case 'P':
1.1.1.13  christos  497:                        sshport = a2port(optarg);
                    498:                        if (sshport <= 0)
                    499:                                fatal("bad port \"%s\"\n", optarg);
1.1       christos  500:                        break;
                    501:                case 'B':
1.1.1.3   christos  502:                        addargs(&remote_remote_args, "-oBatchmode=yes");
                    503:                        addargs(&args, "-oBatchmode=yes");
1.1       christos  504:                        break;
                    505:                case 'l':
1.1.1.3   christos  506:                        limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
                    507:                            &errstr);
                    508:                        if (errstr != NULL)
1.1       christos  509:                                usage();
1.1.1.3   christos  510:                        limit_kbps *= 1024; /* kbps */
                    511:                        bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
1.1       christos  512:                        break;
                    513:                case 'p':
                    514:                        pflag = 1;
                    515:                        break;
                    516:                case 'r':
                    517:                        iamrecursive = 1;
                    518:                        break;
                    519:                case 'S':
                    520:                        ssh_program = xstrdup(optarg);
                    521:                        break;
                    522:                case 'v':
                    523:                        addargs(&args, "-v");
1.1.1.3   christos  524:                        addargs(&remote_remote_args, "-v");
1.1.1.22  christos  525:                        if (verbose_mode == 0)
                    526:                                log_level = SYSLOG_LEVEL_DEBUG1;
                    527:                        else if (log_level < SYSLOG_LEVEL_DEBUG3)
                    528:                                log_level++;
1.1       christos  529:                        verbose_mode = 1;
                    530:                        break;
                    531:                case 'q':
                    532:                        addargs(&args, "-q");
1.1.1.3   christos  533:                        addargs(&remote_remote_args, "-q");
1.1       christos  534:                        showprogress = 0;
                    535:                        break;
                    536:
                    537:                /* Server options. */
                    538:                case 'd':
                    539:                        targetshouldbedirectory = 1;
                    540:                        break;
                    541:                case 'f':       /* "from" */
                    542:                        iamremote = 1;
                    543:                        fflag = 1;
                    544:                        break;
                    545:                case 't':       /* "to" */
                    546:                        iamremote = 1;
                    547:                        tflag = 1;
                    548:                        break;
1.1.1.15  christos  549:                case 'T':
                    550:                        Tflag = 1;
                    551:                        break;
1.1       christos  552:                default:
                    553:                        usage();
                    554:                }
1.1.1.15  christos  555:        }
1.1       christos  556:        argc -= optind;
                    557:        argv += optind;
                    558:
1.1.1.23  christos  559:        log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
1.1.1.22  christos  560:
1.1.1.19  christos  561:        /* Do this last because we want the user to be able to override it */
                    562:        addargs(&args, "-oForwardAgent=no");
                    563:
1.1.1.22  christos  564:        if (iamremote)
                    565:                mode = MODE_SCP;
                    566:
1.1       christos  567:        if ((pwd = getpwuid(userid = getuid())) == NULL)
                    568:                fatal("unknown user %u", (u_int) userid);
                    569:
                    570:        if (!isatty(STDOUT_FILENO))
                    571:                showprogress = 0;
                    572:
1.1.1.9   christos  573:        if (pflag) {
                    574:                /* Cannot pledge: -p allows setuid/setgid files... */
                    575:        } else {
                    576:                if (pledge("stdio rpath wpath cpath fattr tty proc exec",
                    577:                    NULL) == -1) {
                    578:                        perror("pledge");
                    579:                        exit(1);
                    580:                }
                    581:        }
                    582:
1.1       christos  583:        remin = STDIN_FILENO;
                    584:        remout = STDOUT_FILENO;
                    585:
                    586:        if (fflag) {
                    587:                /* Follow "protocol", send data. */
                    588:                (void) response();
                    589:                source(argc, argv);
                    590:                exit(errs != 0);
                    591:        }
                    592:        if (tflag) {
                    593:                /* Receive data. */
1.1.1.15  christos  594:                sink(argc, argv, NULL);
1.1       christos  595:                exit(errs != 0);
                    596:        }
                    597:        if (argc < 2)
                    598:                usage();
                    599:        if (argc > 2)
                    600:                targetshouldbedirectory = 1;
                    601:
                    602:        remin = remout = -1;
                    603:        do_cmd_pid = -1;
                    604:        /* Command to be executed on remote system using "ssh". */
                    605:        (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
                    606:            verbose_mode ? " -v" : "",
                    607:            iamrecursive ? " -r" : "", pflag ? " -p" : "",
                    608:            targetshouldbedirectory ? " -d" : "");
                    609:
1.1.1.17  christos  610:        (void) ssh_signal(SIGPIPE, lostconn);
1.1       christos  611:
1.1.1.13  christos  612:        if (colon(argv[argc - 1]))      /* Dest is remote host. */
1.1.1.22  christos  613:                toremote(argc, argv, mode, sftp_direct);
1.1       christos  614:        else {
                    615:                if (targetshouldbedirectory)
                    616:                        verifydir(argv[argc - 1]);
1.1.1.22  christos  617:                tolocal(argc, argv, mode, sftp_direct); /* Dest is local host. */
1.1       christos  618:        }
                    619:        /*
                    620:         * Finally check the exit status of the ssh process, if one was forked
                    621:         * and no error has occurred yet
                    622:         */
1.1.1.23  christos  623:        if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
1.1       christos  624:                if (remin != -1)
                    625:                    (void) close(remin);
                    626:                if (remout != -1)
                    627:                    (void) close(remout);
                    628:                if (waitpid(do_cmd_pid, &status, 0) == -1)
                    629:                        errs = 1;
                    630:                else {
                    631:                        if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
                    632:                                errs = 1;
                    633:                }
                    634:        }
                    635:        exit(errs != 0);
                    636: }
                    637:
1.1.1.3   christos  638: /* Callback from atomicio6 to update progress meter and limit bandwidth */
                    639: static int
                    640: scpio(void *_cnt, size_t s)
1.1       christos  641: {
1.1.1.3   christos  642:        off_t *cnt = (off_t *)_cnt;
                    643:
                    644:        *cnt += s;
1.1.1.15  christos  645:        refresh_progress_meter(0);
1.1.1.3   christos  646:        if (limit_kbps > 0)
                    647:                bandwidth_limit(&bwlimit, s);
                    648:        return 0;
1.1       christos  649: }
                    650:
1.1.1.5   christos  651: static int
                    652: do_times(int fd, int verb, const struct stat *sb)
                    653: {
                    654:        /* strlen(2^64) == 20; strlen(10^6) == 7 */
                    655:        char buf[(20 + 7 + 2) * 2 + 2];
                    656:
                    657:        (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
                    658:            (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
                    659:            (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
                    660:        if (verb) {
                    661:                fprintf(stderr, "File mtime %lld atime %lld\n",
                    662:                    (long long)sb->st_mtime, (long long)sb->st_atime);
                    663:                fprintf(stderr, "Sending file timestamps: %s", buf);
                    664:        }
                    665:        (void) atomicio(vwrite, fd, buf, strlen(buf));
                    666:        return (response());
                    667: }
                    668:
1.1.1.13  christos  669: static int
                    670: parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
1.1.1.21  christos  671:     char **pathp)
1.1.1.13  christos  672: {
                    673:        int r;
                    674:
                    675:        r = parse_uri("scp", uri, userp, hostp, portp, pathp);
                    676:        if (r == 0 && *pathp == NULL)
                    677:                *pathp = xstrdup(".");
                    678:        return r;
                    679: }
                    680:
1.1.1.15  christos  681: /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
                    682: static int
                    683: append(char *cp, char ***ap, size_t *np)
                    684: {
                    685:        char **tmp;
                    686:
                    687:        if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
                    688:                return -1;
                    689:        tmp[(*np)] = cp;
                    690:        (*np)++;
                    691:        *ap = tmp;
                    692:        return 0;
                    693: }
                    694:
                    695: /*
                    696:  * Finds the start and end of the first brace pair in the pattern.
                    697:  * returns 0 on success or -1 for invalid patterns.
                    698:  */
                    699: static int
                    700: find_brace(const char *pattern, int *startp, int *endp)
                    701: {
                    702:        int i;
                    703:        int in_bracket, brace_level;
                    704:
                    705:        *startp = *endp = -1;
                    706:        in_bracket = brace_level = 0;
                    707:        for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
                    708:                switch (pattern[i]) {
                    709:                case '\\':
                    710:                        /* skip next character */
                    711:                        if (pattern[i + 1] != '\0')
                    712:                                i++;
                    713:                        break;
                    714:                case '[':
                    715:                        in_bracket = 1;
                    716:                        break;
                    717:                case ']':
                    718:                        in_bracket = 0;
                    719:                        break;
                    720:                case '{':
                    721:                        if (in_bracket)
                    722:                                break;
                    723:                        if (pattern[i + 1] == '}') {
                    724:                                /* Protect a single {}, for find(1), like csh */
                    725:                                i++; /* skip */
                    726:                                break;
                    727:                        }
                    728:                        if (*startp == -1)
                    729:                                *startp = i;
                    730:                        brace_level++;
                    731:                        break;
                    732:                case '}':
                    733:                        if (in_bracket)
                    734:                                break;
                    735:                        if (*startp < 0) {
                    736:                                /* Unbalanced brace */
                    737:                                return -1;
                    738:                        }
                    739:                        if (--brace_level <= 0)
                    740:                                *endp = i;
                    741:                        break;
                    742:                }
                    743:        }
                    744:        /* unbalanced brackets/braces */
                    745:        if (*endp < 0 && (*startp >= 0 || in_bracket))
                    746:                return -1;
                    747:        return 0;
                    748: }
                    749:
                    750: /*
                    751:  * Assembles and records a successfully-expanded pattern, returns -1 on
                    752:  * alloc failure.
                    753:  */
                    754: static int
                    755: emit_expansion(const char *pattern, int brace_start, int brace_end,
                    756:     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
                    757: {
                    758:        char *cp;
                    759:        int o = 0, tail_len = strlen(pattern + brace_end + 1);
                    760:
                    761:        if ((cp = malloc(brace_start + (sel_end - sel_start) +
                    762:            tail_len + 1)) == NULL)
                    763:                return -1;
                    764:
                    765:        /* Pattern before initial brace */
                    766:        if (brace_start > 0) {
                    767:                memcpy(cp, pattern, brace_start);
                    768:                o = brace_start;
                    769:        }
                    770:        /* Current braced selection */
                    771:        if (sel_end - sel_start > 0) {
                    772:                memcpy(cp + o, pattern + sel_start,
                    773:                    sel_end - sel_start);
                    774:                o += sel_end - sel_start;
                    775:        }
                    776:        /* Remainder of pattern after closing brace */
                    777:        if (tail_len > 0) {
                    778:                memcpy(cp + o, pattern + brace_end + 1, tail_len);
                    779:                o += tail_len;
                    780:        }
                    781:        cp[o] = '\0';
                    782:        if (append(cp, patternsp, npatternsp) != 0) {
                    783:                free(cp);
                    784:                return -1;
                    785:        }
                    786:        return 0;
                    787: }
                    788:
                    789: /*
                    790:  * Expand the first encountered brace in pattern, appending the expanded
                    791:  * patterns it yielded to the *patternsp array.
                    792:  *
                    793:  * Returns 0 on success or -1 on allocation failure.
                    794:  *
                    795:  * Signals whether expansion was performed via *expanded and whether
                    796:  * pattern was invalid via *invalid.
                    797:  */
                    798: static int
                    799: brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
                    800:     int *expanded, int *invalid)
                    801: {
                    802:        int i;
                    803:        int in_bracket, brace_start, brace_end, brace_level;
                    804:        int sel_start, sel_end;
                    805:
                    806:        *invalid = *expanded = 0;
                    807:
                    808:        if (find_brace(pattern, &brace_start, &brace_end) != 0) {
                    809:                *invalid = 1;
                    810:                return 0;
                    811:        } else if (brace_start == -1)
                    812:                return 0;
                    813:
                    814:        in_bracket = brace_level = 0;
                    815:        for (i = sel_start = brace_start + 1; i < brace_end; i++) {
                    816:                switch (pattern[i]) {
                    817:                case '{':
                    818:                        if (in_bracket)
                    819:                                break;
                    820:                        brace_level++;
                    821:                        break;
                    822:                case '}':
                    823:                        if (in_bracket)
                    824:                                break;
                    825:                        brace_level--;
                    826:                        break;
                    827:                case '[':
                    828:                        in_bracket = 1;
                    829:                        break;
                    830:                case ']':
                    831:                        in_bracket = 0;
                    832:                        break;
                    833:                case '\\':
                    834:                        if (i < brace_end - 1)
                    835:                                i++; /* skip */
                    836:                        break;
                    837:                }
                    838:                if (pattern[i] == ',' || i == brace_end - 1) {
                    839:                        if (in_bracket || brace_level > 0)
                    840:                                continue;
                    841:                        /* End of a selection, emit an expanded pattern */
                    842:
                    843:                        /* Adjust end index for last selection */
                    844:                        sel_end = (i == brace_end - 1) ? brace_end : i;
                    845:                        if (emit_expansion(pattern, brace_start, brace_end,
                    846:                            sel_start, sel_end, patternsp, npatternsp) != 0)
                    847:                                return -1;
                    848:                        /* move on to the next selection */
                    849:                        sel_start = i + 1;
                    850:                        continue;
                    851:                }
                    852:        }
                    853:        if (in_bracket || brace_level > 0) {
                    854:                *invalid = 1;
                    855:                return 0;
                    856:        }
                    857:        /* success */
                    858:        *expanded = 1;
                    859:        return 0;
                    860: }
                    861:
                    862: /* Expand braces from pattern. Returns 0 on success, -1 on failure */
                    863: static int
                    864: brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
                    865: {
                    866:        char *cp, *cp2, **active = NULL, **done = NULL;
                    867:        size_t i, nactive = 0, ndone = 0;
                    868:        int ret = -1, invalid = 0, expanded = 0;
                    869:
                    870:        *patternsp = NULL;
                    871:        *npatternsp = 0;
                    872:
                    873:        /* Start the worklist with the original pattern */
                    874:        if ((cp = strdup(pattern)) == NULL)
                    875:                return -1;
                    876:        if (append(cp, &active, &nactive) != 0) {
                    877:                free(cp);
                    878:                return -1;
                    879:        }
                    880:        while (nactive > 0) {
                    881:                cp = active[nactive - 1];
                    882:                nactive--;
                    883:                if (brace_expand_one(cp, &active, &nactive,
                    884:                    &expanded, &invalid) == -1) {
                    885:                        free(cp);
                    886:                        goto fail;
                    887:                }
                    888:                if (invalid)
1.1.1.20  christos  889:                        fatal_f("invalid brace pattern \"%s\"", cp);
1.1.1.15  christos  890:                if (expanded) {
                    891:                        /*
                    892:                         * Current entry expanded to new entries on the
                    893:                         * active list; discard the progenitor pattern.
                    894:                         */
                    895:                        free(cp);
                    896:                        continue;
                    897:                }
                    898:                /*
                    899:                 * Pattern did not expand; append the finename component to
                    900:                 * the completed list
                    901:                 */
                    902:                if ((cp2 = strrchr(cp, '/')) != NULL)
                    903:                        *cp2++ = '\0';
                    904:                else
                    905:                        cp2 = cp;
                    906:                if (append(xstrdup(cp2), &done, &ndone) != 0) {
                    907:                        free(cp);
                    908:                        goto fail;
                    909:                }
                    910:                free(cp);
                    911:        }
                    912:        /* success */
                    913:        *patternsp = done;
                    914:        *npatternsp = ndone;
                    915:        done = NULL;
                    916:        ndone = 0;
                    917:        ret = 0;
                    918:  fail:
                    919:        for (i = 0; i < nactive; i++)
                    920:                free(active[i]);
                    921:        free(active);
                    922:        for (i = 0; i < ndone; i++)
                    923:                free(done[i]);
                    924:        free(done);
                    925:        return ret;
                    926: }
                    927:
1.1.1.22  christos  928: static struct sftp_conn *
                    929: do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
                    930:    int *reminp, int *remoutp, int *pidp)
                    931: {
                    932:        if (sftp_direct == NULL) {
                    933:                if (do_cmd(ssh_program, host, user, port, 1, "sftp",
                    934:                    reminp, remoutp, pidp) < 0)
                    935:                        return NULL;
                    936:
                    937:        } else {
1.1.1.25  christos  938:                freeargs(&args);
1.1.1.22  christos  939:                addargs(&args, "sftp-server");
                    940:                if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
                    941:                    reminp, remoutp, pidp) < 0)
                    942:                        return NULL;
                    943:        }
                    944:        return do_init(*reminp, *remoutp, 32768, 64, limit_kbps);
                    945: }
                    946:
1.1       christos  947: void
1.1.1.22  christos  948: toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1.1       christos  949: {
1.1.1.13  christos  950:        char *suser = NULL, *host = NULL, *src = NULL;
                    951:        char *bp, *tuser, *thost, *targ;
                    952:        int sport = -1, tport = -1;
1.1.1.22  christos  953:        struct sftp_conn *conn = NULL, *conn2 = NULL;
1.1       christos  954:        arglist alist;
1.1.1.22  christos  955:        int i, r, status;
1.1.1.3   christos  956:        u_int j;
1.1       christos  957:
                    958:        memset(&alist, '\0', sizeof(alist));
                    959:        alist.list = NULL;
                    960:
1.1.1.13  christos  961:        /* Parse target */
                    962:        r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
                    963:        if (r == -1) {
                    964:                fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
                    965:                ++errs;
                    966:                goto out;
                    967:        }
                    968:        if (r != 0) {
                    969:                if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
                    970:                    &targ) == -1) {
                    971:                        fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
                    972:                        ++errs;
                    973:                        goto out;
                    974:                }
1.1       christos  975:        }
                    976:
1.1.1.13  christos  977:        /* Parse source files */
1.1       christos  978:        for (i = 0; i < argc - 1; i++) {
1.1.1.13  christos  979:                free(suser);
                    980:                free(host);
                    981:                free(src);
                    982:                r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
                    983:                if (r == -1) {
                    984:                        fmprintf(stderr, "%s: invalid uri\n", argv[i]);
                    985:                        ++errs;
                    986:                        continue;
                    987:                }
                    988:                if (r != 0) {
                    989:                        parse_user_host_path(argv[i], &suser, &host, &src);
                    990:                }
                    991:                if (suser != NULL && !okname(suser)) {
                    992:                        ++errs;
                    993:                        continue;
                    994:                }
                    995:                if (host && throughlocal) {     /* extended remote to remote */
1.1.1.22  christos  996:                        if (mode == MODE_SFTP) {
                    997:                                if (remin == -1) {
                    998:                                        /* Connect to dest now */
                    999:                                        conn = do_sftp_connect(thost, tuser,
                   1000:                                            tport, sftp_direct,
                   1001:                                            &remin, &remout, &do_cmd_pid);
                   1002:                                        if (conn == NULL) {
                   1003:                                                fatal("Unable to open "
                   1004:                                                    "destination connection");
                   1005:                                        }
                   1006:                                        debug3_f("origin in %d out %d pid %ld",
                   1007:                                            remin, remout, (long)do_cmd_pid);
                   1008:                                }
                   1009:                                /*
                   1010:                                 * XXX remember suser/host/sport and only
                   1011:                                 * reconnect if they change between arguments.
                   1012:                                 * would save reconnections for cases like
                   1013:                                 * scp -3 hosta:/foo hosta:/bar hostb:
                   1014:                                 */
                   1015:                                /* Connect to origin now */
                   1016:                                conn2 = do_sftp_connect(host, suser,
                   1017:                                    sport, sftp_direct,
                   1018:                                    &remin2, &remout2, &do_cmd_pid2);
                   1019:                                if (conn2 == NULL) {
                   1020:                                        fatal("Unable to open "
                   1021:                                            "source connection");
                   1022:                                }
                   1023:                                debug3_f("destination in %d out %d pid %ld",
                   1024:                                    remin2, remout2, (long)do_cmd_pid2);
                   1025:                                throughlocal_sftp(conn2, conn, src, targ);
                   1026:                                (void) close(remin2);
                   1027:                                (void) close(remout2);
                   1028:                                remin2 = remout2 = -1;
                   1029:                                if (waitpid(do_cmd_pid2, &status, 0) == -1)
                   1030:                                        ++errs;
                   1031:                                else if (!WIFEXITED(status) ||
                   1032:                                    WEXITSTATUS(status) != 0)
                   1033:                                        ++errs;
                   1034:                                do_cmd_pid2 = -1;
                   1035:                                continue;
                   1036:                        } else {
                   1037:                                xasprintf(&bp, "%s -f %s%s", cmd,
                   1038:                                    *src == '-' ? "-- " : "", src);
                   1039:                                if (do_cmd(ssh_program, host, suser, sport, 0,
                   1040:                                    bp, &remin, &remout, &do_cmd_pid) < 0)
                   1041:                                        exit(1);
                   1042:                                free(bp);
                   1043:                                xasprintf(&bp, "%s -t %s%s", cmd,
                   1044:                                    *targ == '-' ? "-- " : "", targ);
                   1045:                                if (do_cmd2(thost, tuser, tport, bp,
                   1046:                                    remin, remout) < 0)
                   1047:                                        exit(1);
                   1048:                                free(bp);
                   1049:                                (void) close(remin);
                   1050:                                (void) close(remout);
                   1051:                                remin = remout = -1;
                   1052:                        }
1.1.1.13  christos 1053:                } else if (host) {      /* standard remote to remote */
1.1.1.22  christos 1054:                        /*
                   1055:                         * Second remote user is passed to first remote side
                   1056:                         * via scp command-line. Ensure it contains no obvious
                   1057:                         * shell characters.
                   1058:                         */
                   1059:                        if (tuser != NULL && !okname(tuser)) {
                   1060:                                ++errs;
                   1061:                                continue;
                   1062:                        }
1.1.1.13  christos 1063:                        if (tport != -1 && tport != SSH_DEFAULT_PORT) {
                   1064:                                /* This would require the remote support URIs */
                   1065:                                fatal("target port not supported with two "
1.1.1.22  christos 1066:                                    "remote hosts and the -R option");
1.1.1.13  christos 1067:                        }
                   1068:
1.1       christos 1069:                        freeargs(&alist);
                   1070:                        addargs(&alist, "%s", ssh_program);
                   1071:                        addargs(&alist, "-x");
1.1.1.3   christos 1072:                        addargs(&alist, "-oClearAllForwardings=yes");
1.1       christos 1073:                        addargs(&alist, "-n");
1.1.1.3   christos 1074:                        for (j = 0; j < remote_remote_args.num; j++) {
                   1075:                                addargs(&alist, "%s",
                   1076:                                    remote_remote_args.list[j]);
                   1077:                        }
1.1.1.13  christos 1078:
                   1079:                        if (sport != -1) {
                   1080:                                addargs(&alist, "-p");
                   1081:                                addargs(&alist, "%d", sport);
                   1082:                        }
                   1083:                        if (suser) {
1.1       christos 1084:                                addargs(&alist, "-l");
                   1085:                                addargs(&alist, "%s", suser);
                   1086:                        }
1.1.1.2   adam     1087:                        addargs(&alist, "--");
1.1       christos 1088:                        addargs(&alist, "%s", host);
                   1089:                        addargs(&alist, "%s", cmd);
                   1090:                        addargs(&alist, "%s", src);
                   1091:                        addargs(&alist, "%s%s%s:%s",
                   1092:                            tuser ? tuser : "", tuser ? "@" : "",
                   1093:                            thost, targ);
                   1094:                        if (do_local_cmd(&alist) != 0)
                   1095:                                errs = 1;
                   1096:                } else {        /* local to remote */
1.1.1.22  christos 1097:                        if (mode == MODE_SFTP) {
                   1098:                                if (remin == -1) {
                   1099:                                        /* Connect to remote now */
                   1100:                                        conn = do_sftp_connect(thost, tuser,
                   1101:                                            tport, sftp_direct,
                   1102:                                            &remin, &remout, &do_cmd_pid);
                   1103:                                        if (conn == NULL) {
                   1104:                                                fatal("Unable to open sftp "
                   1105:                                                    "connection");
                   1106:                                        }
                   1107:                                }
                   1108:
                   1109:                                /* The protocol */
                   1110:                                source_sftp(1, argv[i], targ, conn);
                   1111:                                continue;
                   1112:                        }
                   1113:                        /* SCP */
1.1       christos 1114:                        if (remin == -1) {
1.1.1.4   christos 1115:                                xasprintf(&bp, "%s -t %s%s", cmd,
                   1116:                                    *targ == '-' ? "-- " : "", targ);
1.1.1.22  christos 1117:                                if (do_cmd(ssh_program, thost, tuser, tport, 0,
                   1118:                                    bp, &remin, &remout, &do_cmd_pid) < 0)
1.1       christos 1119:                                        exit(1);
                   1120:                                if (response() < 0)
                   1121:                                        exit(1);
1.1.1.5   christos 1122:                                free(bp);
1.1       christos 1123:                        }
                   1124:                        source(1, argv + i);
                   1125:                }
                   1126:        }
1.1.1.13  christos 1127: out:
1.1.1.22  christos 1128:        if (mode == MODE_SFTP)
                   1129:                free(conn);
1.1.1.13  christos 1130:        free(tuser);
                   1131:        free(thost);
                   1132:        free(targ);
                   1133:        free(suser);
                   1134:        free(host);
                   1135:        free(src);
1.1       christos 1136: }
                   1137:
                   1138: void
1.1.1.22  christos 1139: tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1.1       christos 1140: {
1.1.1.13  christos 1141:        char *bp, *host = NULL, *src = NULL, *suser = NULL;
1.1       christos 1142:        arglist alist;
1.1.1.22  christos 1143:        struct sftp_conn *conn = NULL;
1.1.1.13  christos 1144:        int i, r, sport = -1;
1.1       christos 1145:
                   1146:        memset(&alist, '\0', sizeof(alist));
                   1147:        alist.list = NULL;
                   1148:
                   1149:        for (i = 0; i < argc - 1; i++) {
1.1.1.13  christos 1150:                free(suser);
                   1151:                free(host);
                   1152:                free(src);
                   1153:                r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
                   1154:                if (r == -1) {
                   1155:                        fmprintf(stderr, "%s: invalid uri\n", argv[i]);
                   1156:                        ++errs;
                   1157:                        continue;
                   1158:                }
                   1159:                if (r != 0)
                   1160:                        parse_user_host_path(argv[i], &suser, &host, &src);
                   1161:                if (suser != NULL && !okname(suser)) {
                   1162:                        ++errs;
                   1163:                        continue;
                   1164:                }
                   1165:                if (!host) {    /* Local to local. */
1.1       christos 1166:                        freeargs(&alist);
                   1167:                        addargs(&alist, "%s", _PATH_CP);
                   1168:                        if (iamrecursive)
                   1169:                                addargs(&alist, "-r");
                   1170:                        if (pflag)
                   1171:                                addargs(&alist, "-p");
1.1.1.2   adam     1172:                        addargs(&alist, "--");
1.1       christos 1173:                        addargs(&alist, "%s", argv[i]);
                   1174:                        addargs(&alist, "%s", argv[argc-1]);
                   1175:                        if (do_local_cmd(&alist))
                   1176:                                ++errs;
                   1177:                        continue;
                   1178:                }
1.1.1.13  christos 1179:                /* Remote to local. */
1.1.1.22  christos 1180:                if (mode == MODE_SFTP) {
                   1181:                        conn = do_sftp_connect(host, suser, sport,
                   1182:                            sftp_direct, &remin, &remout, &do_cmd_pid);
                   1183:                        if (conn == NULL) {
1.1.1.23  christos 1184:                                error("sftp connection failed");
1.1.1.22  christos 1185:                                ++errs;
                   1186:                                continue;
                   1187:                        }
                   1188:
                   1189:                        /* The protocol */
                   1190:                        sink_sftp(1, argv[argc - 1], src, conn);
                   1191:
                   1192:                        free(conn);
                   1193:                        (void) close(remin);
                   1194:                        (void) close(remout);
                   1195:                        remin = remout = -1;
                   1196:                        continue;
                   1197:                }
                   1198:                /* SCP */
1.1.1.4   christos 1199:                xasprintf(&bp, "%s -f %s%s",
                   1200:                    cmd, *src == '-' ? "-- " : "", src);
1.1.1.22  christos 1201:                if (do_cmd(ssh_program, host, suser, sport, 0, bp,
                   1202:                    &remin, &remout, &do_cmd_pid) < 0) {
1.1.1.5   christos 1203:                        free(bp);
1.1       christos 1204:                        ++errs;
                   1205:                        continue;
                   1206:                }
1.1.1.5   christos 1207:                free(bp);
1.1.1.15  christos 1208:                sink(1, argv + argc - 1, src);
1.1       christos 1209:                (void) close(remin);
                   1210:                remin = remout = -1;
                   1211:        }
1.1.1.13  christos 1212:        free(suser);
                   1213:        free(host);
                   1214:        free(src);
1.1       christos 1215: }
                   1216:
1.1.1.22  christos 1217: /* Prepare remote path, handling ~ by assuming cwd is the homedir */
                   1218: static char *
                   1219: prepare_remote_path(struct sftp_conn *conn, const char *path)
                   1220: {
1.1.1.24  christos 1221:        size_t nslash;
                   1222:
1.1.1.22  christos 1223:        /* Handle ~ prefixed paths */
                   1224:        if (*path == '\0' || strcmp(path, "~") == 0)
                   1225:                return xstrdup(".");
1.1.1.24  christos 1226:        if (*path != '~')
                   1227:                return xstrdup(path);
                   1228:        if (strncmp(path, "~/", 2) == 0) {
                   1229:                if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
                   1230:                        return xstrdup(".");
                   1231:                return xstrdup(path + 2 + nslash);
                   1232:        }
1.1.1.22  christos 1233:        if (can_expand_path(conn))
                   1234:                return do_expand_path(conn, path);
                   1235:        /* No protocol extension */
1.1.1.23  christos 1236:        error("server expand-path extension is required "
                   1237:            "for ~user paths in SFTP mode");
1.1.1.22  christos 1238:        return NULL;
                   1239: }
                   1240:
                   1241: void
                   1242: source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
                   1243: {
                   1244:        char *target = NULL, *filename = NULL, *abs_dst = NULL;
1.1.1.24  christos 1245:        int src_is_dir, target_is_dir;
                   1246:        Attrib a;
                   1247:        struct stat st;
                   1248:
                   1249:        memset(&a, '\0', sizeof(a));
                   1250:        if (stat(src, &st) != 0)
                   1251:                fatal("stat local \"%s\": %s", src, strerror(errno));
                   1252:        src_is_dir = S_ISDIR(st.st_mode);
1.1.1.22  christos 1253:        if ((filename = basename(src)) == NULL)
1.1.1.24  christos 1254:                fatal("basename \"%s\": %s", src, strerror(errno));
1.1.1.22  christos 1255:
                   1256:        /*
                   1257:         * No need to glob here - the local shell already took care of
                   1258:         * the expansions
                   1259:         */
                   1260:        if ((target = prepare_remote_path(conn, targ)) == NULL)
                   1261:                cleanup_exit(255);
                   1262:        target_is_dir = remote_is_dir(conn, target);
                   1263:        if (targetshouldbedirectory && !target_is_dir) {
1.1.1.24  christos 1264:                debug("target directory \"%s\" does not exist", target);
                   1265:                a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
                   1266:                a.perm = st.st_mode | 0700; /* ensure writable */
                   1267:                if (do_mkdir(conn, target, &a, 1) != 0)
                   1268:                        cleanup_exit(255); /* error already logged */
                   1269:                target_is_dir = 1;
1.1.1.22  christos 1270:        }
                   1271:        if (target_is_dir)
                   1272:                abs_dst = path_append(target, filename);
                   1273:        else {
                   1274:                abs_dst = target;
                   1275:                target = NULL;
                   1276:        }
                   1277:        debug3_f("copying local %s to remote %s", src, abs_dst);
                   1278:
1.1.1.24  christos 1279:        if (src_is_dir && iamrecursive) {
1.1.1.22  christos 1280:                if (upload_dir(conn, src, abs_dst, pflag,
1.1.1.26! christos 1281:                    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1.1.1.24  christos 1282:                        error("failed to upload directory %s to %s", src, targ);
1.1.1.23  christos 1283:                        errs = 1;
1.1.1.22  christos 1284:                }
1.1.1.26! christos 1285:        } else if (do_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1.1.1.24  christos 1286:                error("failed to upload file %s to %s", src, targ);
1.1.1.23  christos 1287:                errs = 1;
                   1288:        }
1.1.1.22  christos 1289:
                   1290:        free(abs_dst);
                   1291:        free(target);
                   1292: }
                   1293:
1.1       christos 1294: void
                   1295: source(int argc, char **argv)
                   1296: {
                   1297:        struct stat stb;
                   1298:        static BUF buffer;
                   1299:        BUF *bp;
                   1300:        off_t i, statbytes;
1.1.1.6   christos 1301:        size_t amt, nr;
1.1       christos 1302:        int fd = -1, haderr, indx;
1.1.1.16  christos 1303:        char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1.1       christos 1304:        int len;
                   1305:
                   1306:        for (indx = 0; indx < argc; ++indx) {
                   1307:                name = argv[indx];
                   1308:                statbytes = 0;
                   1309:                len = strlen(name);
                   1310:                while (len > 1 && name[len-1] == '/')
                   1311:                        name[--len] = '\0';
1.1.1.24  christos 1312:                if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1.1       christos 1313:                        goto syserr;
                   1314:                if (strchr(name, '\n') != NULL) {
                   1315:                        strnvis(encname, name, sizeof(encname), VIS_NL);
                   1316:                        name = encname;
                   1317:                }
1.1.1.16  christos 1318:                if (fstat(fd, &stb) == -1) {
1.1       christos 1319: syserr:                        run_err("%s: %s", name, strerror(errno));
                   1320:                        goto next;
                   1321:                }
                   1322:                if (stb.st_size < 0) {
                   1323:                        run_err("%s: %s", name, "Negative file size");
                   1324:                        goto next;
                   1325:                }
                   1326:                unset_nonblock(fd);
                   1327:                switch (stb.st_mode & S_IFMT) {
                   1328:                case S_IFREG:
                   1329:                        break;
                   1330:                case S_IFDIR:
                   1331:                        if (iamrecursive) {
                   1332:                                rsource(name, &stb);
                   1333:                                goto next;
                   1334:                        }
                   1335:                        /* FALLTHROUGH */
                   1336:                default:
                   1337:                        run_err("%s: not a regular file", name);
                   1338:                        goto next;
                   1339:                }
                   1340:                if ((last = strrchr(name, '/')) == NULL)
                   1341:                        last = name;
                   1342:                else
                   1343:                        ++last;
                   1344:                curfile = last;
                   1345:                if (pflag) {
1.1.1.5   christos 1346:                        if (do_times(remout, verbose_mode, &stb) < 0)
1.1       christos 1347:                                goto next;
                   1348:                }
                   1349: #define        FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
                   1350:                snprintf(buf, sizeof buf, "C%04o %lld %s\n",
                   1351:                    (u_int) (stb.st_mode & FILEMODEMASK),
                   1352:                    (long long)stb.st_size, last);
1.1.1.10  christos 1353:                if (verbose_mode)
                   1354:                        fmprintf(stderr, "Sending file modes: %s", buf);
1.1       christos 1355:                (void) atomicio(vwrite, remout, buf, strlen(buf));
                   1356:                if (response() < 0)
                   1357:                        goto next;
                   1358:                if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
                   1359: next:                  if (fd != -1) {
                   1360:                                (void) close(fd);
                   1361:                                fd = -1;
                   1362:                        }
                   1363:                        continue;
                   1364:                }
                   1365:                if (showprogress)
                   1366:                        start_progress_meter(curfile, stb.st_size, &statbytes);
                   1367:                set_nonblock(remout);
                   1368:                for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
                   1369:                        amt = bp->cnt;
                   1370:                        if (i + (off_t)amt > stb.st_size)
                   1371:                                amt = stb.st_size - i;
                   1372:                        if (!haderr) {
1.1.1.6   christos 1373:                                if ((nr = atomicio(read, fd,
                   1374:                                    bp->buf, amt)) != amt) {
1.1       christos 1375:                                        haderr = errno;
1.1.1.6   christos 1376:                                        memset(bp->buf + nr, 0, amt - nr);
                   1377:                                }
1.1       christos 1378:                        }
                   1379:                        /* Keep writing after error to retain sync */
                   1380:                        if (haderr) {
                   1381:                                (void)atomicio(vwrite, remout, bp->buf, amt);
1.1.1.6   christos 1382:                                memset(bp->buf, 0, amt);
1.1       christos 1383:                                continue;
                   1384:                        }
1.1.1.3   christos 1385:                        if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1.1       christos 1386:                            &statbytes) != amt)
                   1387:                                haderr = errno;
                   1388:                }
                   1389:                unset_nonblock(remout);
                   1390:
                   1391:                if (fd != -1) {
1.1.1.16  christos 1392:                        if (close(fd) == -1 && !haderr)
1.1       christos 1393:                                haderr = errno;
                   1394:                        fd = -1;
                   1395:                }
                   1396:                if (!haderr)
                   1397:                        (void) atomicio(vwrite, remout, "", 1);
                   1398:                else
                   1399:                        run_err("%s: %s", name, strerror(haderr));
                   1400:                (void) response();
1.1.1.10  christos 1401:                if (showprogress)
                   1402:                        stop_progress_meter();
1.1       christos 1403:        }
                   1404: }
                   1405:
                   1406: void
                   1407: rsource(char *name, struct stat *statp)
                   1408: {
                   1409:        DIR *dirp;
                   1410:        struct dirent *dp;
1.1.1.7   christos 1411:        char *last, *vect[1], path[PATH_MAX];
1.1       christos 1412:
                   1413:        if (!(dirp = opendir(name))) {
                   1414:                run_err("%s: %s", name, strerror(errno));
                   1415:                return;
                   1416:        }
                   1417:        last = strrchr(name, '/');
1.1.1.9   christos 1418:        if (last == NULL)
1.1       christos 1419:                last = name;
                   1420:        else
                   1421:                last++;
                   1422:        if (pflag) {
1.1.1.5   christos 1423:                if (do_times(remout, verbose_mode, statp) < 0) {
1.1       christos 1424:                        closedir(dirp);
                   1425:                        return;
                   1426:                }
                   1427:        }
                   1428:        (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
                   1429:            (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
                   1430:        if (verbose_mode)
1.1.1.10  christos 1431:                fmprintf(stderr, "Entering directory: %s", path);
1.1       christos 1432:        (void) atomicio(vwrite, remout, path, strlen(path));
                   1433:        if (response() < 0) {
                   1434:                closedir(dirp);
                   1435:                return;
                   1436:        }
                   1437:        while ((dp = readdir(dirp)) != NULL) {
                   1438:                if (dp->d_ino == 0)
                   1439:                        continue;
                   1440:                if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
                   1441:                        continue;
                   1442:                if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
                   1443:                        run_err("%s/%s: name too long", name, dp->d_name);
                   1444:                        continue;
                   1445:                }
                   1446:                (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
                   1447:                vect[0] = path;
                   1448:                source(1, vect);
                   1449:        }
                   1450:        (void) closedir(dirp);
                   1451:        (void) atomicio(vwrite, remout, "E\n", 2);
                   1452:        (void) response();
                   1453: }
                   1454:
1.1.1.22  christos 1455: void
                   1456: sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
                   1457: {
                   1458:        char *abs_src = NULL;
                   1459:        char *abs_dst = NULL;
                   1460:        glob_t g;
                   1461:        char *filename, *tmp = NULL;
1.1.1.24  christos 1462:        int i, r, err = 0, dst_is_dir;
                   1463:        struct stat st;
1.1.1.22  christos 1464:
                   1465:        memset(&g, 0, sizeof(g));
1.1.1.24  christos 1466:
1.1.1.22  christos 1467:        /*
                   1468:         * Here, we need remote glob as SFTP can not depend on remote shell
                   1469:         * expansions
                   1470:         */
                   1471:        if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
                   1472:                err = -1;
                   1473:                goto out;
                   1474:        }
                   1475:
                   1476:        debug3_f("copying remote %s to local %s", abs_src, dst);
                   1477:        if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) {
                   1478:                if (r == GLOB_NOSPACE)
1.1.1.24  christos 1479:                        error("%s: too many glob matches", src);
1.1.1.22  christos 1480:                else
1.1.1.24  christos 1481:                        error("%s: %s", src, strerror(ENOENT));
1.1.1.22  christos 1482:                err = -1;
                   1483:                goto out;
                   1484:        }
                   1485:
1.1.1.24  christos 1486:        if ((r = stat(dst, &st)) != 0)
                   1487:                debug2_f("stat local \"%s\": %s", dst, strerror(errno));
                   1488:        dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
                   1489:
                   1490:        if (g.gl_matchc > 1 && !dst_is_dir) {
                   1491:                if (r == 0) {
                   1492:                        error("Multiple files match pattern, but destination "
                   1493:                            "\"%s\" is not a directory", dst);
                   1494:                        err = -1;
                   1495:                        goto out;
                   1496:                }
                   1497:                debug2_f("creating destination \"%s\"", dst);
                   1498:                if (mkdir(dst, 0777) != 0) {
                   1499:                        error("local mkdir \"%s\": %s", dst, strerror(errno));
                   1500:                        err = -1;
                   1501:                        goto out;
                   1502:                }
                   1503:                dst_is_dir = 1;
1.1.1.22  christos 1504:        }
                   1505:
                   1506:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
                   1507:                tmp = xstrdup(g.gl_pathv[i]);
                   1508:                if ((filename = basename(tmp)) == NULL) {
                   1509:                        error("basename %s: %s", tmp, strerror(errno));
                   1510:                        err = -1;
                   1511:                        goto out;
                   1512:                }
                   1513:
1.1.1.24  christos 1514:                if (dst_is_dir)
1.1.1.22  christos 1515:                        abs_dst = path_append(dst, filename);
                   1516:                else
                   1517:                        abs_dst = xstrdup(dst);
                   1518:
                   1519:                debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
                   1520:                if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
                   1521:                        if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
1.1.1.26! christos 1522:                            pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1.1.1.22  christos 1523:                                err = -1;
                   1524:                } else {
                   1525:                        if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
1.1.1.26! christos 1526:                            pflag, 0, 0, 1) == -1)
1.1.1.22  christos 1527:                                err = -1;
                   1528:                }
                   1529:                free(abs_dst);
                   1530:                abs_dst = NULL;
                   1531:                free(tmp);
                   1532:                tmp = NULL;
                   1533:        }
                   1534:
                   1535: out:
                   1536:        free(abs_src);
                   1537:        free(tmp);
                   1538:        globfree(&g);
1.1.1.23  christos 1539:        if (err == -1)
                   1540:                errs = 1;
1.1.1.22  christos 1541: }
                   1542:
                   1543:
1.1.1.12  christos 1544: #define TYPE_OVERFLOW(type, val) \
                   1545:        ((sizeof(type) == 4 && (val) > INT32_MAX) || \
                   1546:         (sizeof(type) == 8 && (val) > INT64_MAX) || \
                   1547:         (sizeof(type) != 4 && sizeof(type) != 8))
                   1548:
1.1       christos 1549: void
1.1.1.15  christos 1550: sink(int argc, char **argv, const char *src)
1.1       christos 1551: {
                   1552:        static BUF buffer;
                   1553:        struct stat stb;
                   1554:        BUF *bp;
                   1555:        off_t i;
                   1556:        size_t j, count;
                   1557:        int amt, exists, first, ofd;
                   1558:        mode_t mode, omode, mask;
                   1559:        off_t size, statbytes;
1.1.1.5   christos 1560:        unsigned long long ull;
1.1.1.18  christos 1561:        int setimes, targisdir, wrerr;
1.1.1.10  christos 1562:        char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1.1.1.15  christos 1563:        char **patterns = NULL;
                   1564:        size_t n, npatterns = 0;
1.1       christos 1565:        struct timeval tv[2];
                   1566:
                   1567: #define        atime   tv[0]
                   1568: #define        mtime   tv[1]
                   1569: #define        SCREWUP(str)    { why = str; goto screwup; }
                   1570:
1.1.1.12  christos 1571:        if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
                   1572:                SCREWUP("Unexpected off_t/time_t size");
                   1573:
1.1       christos 1574:        setimes = targisdir = 0;
                   1575:        mask = umask(0);
                   1576:        if (!pflag)
                   1577:                (void) umask(mask);
                   1578:        if (argc != 1) {
                   1579:                run_err("ambiguous target");
                   1580:                exit(1);
                   1581:        }
                   1582:        targ = *argv;
                   1583:        if (targetshouldbedirectory)
                   1584:                verifydir(targ);
                   1585:
                   1586:        (void) atomicio(vwrite, remout, "", 1);
                   1587:        if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
                   1588:                targisdir = 1;
1.1.1.15  christos 1589:        if (src != NULL && !iamrecursive && !Tflag) {
                   1590:                /*
                   1591:                 * Prepare to try to restrict incoming filenames to match
                   1592:                 * the requested destination file glob.
                   1593:                 */
                   1594:                if (brace_expand(src, &patterns, &npatterns) != 0)
1.1.1.20  christos 1595:                        fatal_f("could not expand pattern");
1.1.1.15  christos 1596:        }
1.1       christos 1597:        for (first = 1;; first = 0) {
                   1598:                cp = buf;
                   1599:                if (atomicio(read, remin, cp, 1) != 1)
1.1.1.15  christos 1600:                        goto done;
1.1       christos 1601:                if (*cp++ == '\n')
                   1602:                        SCREWUP("unexpected <newline>");
                   1603:                do {
                   1604:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
                   1605:                                SCREWUP("lost connection");
                   1606:                        *cp++ = ch;
                   1607:                } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
                   1608:                *cp = 0;
                   1609:                if (verbose_mode)
1.1.1.10  christos 1610:                        fmprintf(stderr, "Sink: %s", buf);
1.1       christos 1611:
                   1612:                if (buf[0] == '\01' || buf[0] == '\02') {
1.1.1.10  christos 1613:                        if (iamremote == 0) {
                   1614:                                (void) snmprintf(visbuf, sizeof(visbuf),
                   1615:                                    NULL, "%s", buf + 1);
1.1       christos 1616:                                (void) atomicio(vwrite, STDERR_FILENO,
1.1.1.10  christos 1617:                                    visbuf, strlen(visbuf));
                   1618:                        }
1.1       christos 1619:                        if (buf[0] == '\02')
                   1620:                                exit(1);
                   1621:                        ++errs;
                   1622:                        continue;
                   1623:                }
                   1624:                if (buf[0] == 'E') {
                   1625:                        (void) atomicio(vwrite, remout, "", 1);
1.1.1.15  christos 1626:                        goto done;
1.1       christos 1627:                }
                   1628:                if (ch == '\n')
                   1629:                        *--cp = 0;
                   1630:
                   1631:                cp = buf;
                   1632:                if (*cp == 'T') {
                   1633:                        setimes++;
                   1634:                        cp++;
1.1.1.5   christos 1635:                        if (!isdigit((unsigned char)*cp))
                   1636:                                SCREWUP("mtime.sec not present");
                   1637:                        ull = strtoull(cp, &cp, 10);
1.1       christos 1638:                        if (!cp || *cp++ != ' ')
                   1639:                                SCREWUP("mtime.sec not delimited");
1.1.1.12  christos 1640:                        if (TYPE_OVERFLOW(time_t, ull))
1.1.1.5   christos 1641:                                setimes = 0;    /* out of range */
                   1642:                        mtime.tv_sec = ull;
1.1       christos 1643:                        mtime.tv_usec = strtol(cp, &cp, 10);
1.1.1.5   christos 1644:                        if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
                   1645:                            mtime.tv_usec > 999999)
1.1       christos 1646:                                SCREWUP("mtime.usec not delimited");
1.1.1.5   christos 1647:                        if (!isdigit((unsigned char)*cp))
                   1648:                                SCREWUP("atime.sec not present");
                   1649:                        ull = strtoull(cp, &cp, 10);
1.1       christos 1650:                        if (!cp || *cp++ != ' ')
                   1651:                                SCREWUP("atime.sec not delimited");
1.1.1.12  christos 1652:                        if (TYPE_OVERFLOW(time_t, ull))
1.1.1.5   christos 1653:                                setimes = 0;    /* out of range */
                   1654:                        atime.tv_sec = ull;
1.1       christos 1655:                        atime.tv_usec = strtol(cp, &cp, 10);
1.1.1.5   christos 1656:                        if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
                   1657:                            atime.tv_usec > 999999)
1.1       christos 1658:                                SCREWUP("atime.usec not delimited");
                   1659:                        (void) atomicio(vwrite, remout, "", 1);
                   1660:                        continue;
                   1661:                }
                   1662:                if (*cp != 'C' && *cp != 'D') {
                   1663:                        /*
                   1664:                         * Check for the case "rcp remote:foo\* local:bar".
                   1665:                         * In this case, the line "No match." can be returned
                   1666:                         * by the shell before the rcp command on the remote is
                   1667:                         * executed so the ^Aerror_message convention isn't
                   1668:                         * followed.
                   1669:                         */
                   1670:                        if (first) {
                   1671:                                run_err("%s", cp);
                   1672:                                exit(1);
                   1673:                        }
                   1674:                        SCREWUP("expected control record");
                   1675:                }
                   1676:                mode = 0;
                   1677:                for (++cp; cp < buf + 5; cp++) {
                   1678:                        if (*cp < '0' || *cp > '7')
                   1679:                                SCREWUP("bad mode");
                   1680:                        mode = (mode << 3) | (*cp - '0');
                   1681:                }
1.1.1.14  christos 1682:                if (!pflag)
                   1683:                        mode &= ~mask;
1.1       christos 1684:                if (*cp++ != ' ')
                   1685:                        SCREWUP("mode not delimited");
                   1686:
1.1.1.12  christos 1687:                if (!isdigit((unsigned char)*cp))
                   1688:                        SCREWUP("size not present");
                   1689:                ull = strtoull(cp, &cp, 10);
                   1690:                if (!cp || *cp++ != ' ')
1.1       christos 1691:                        SCREWUP("size not delimited");
1.1.1.12  christos 1692:                if (TYPE_OVERFLOW(off_t, ull))
                   1693:                        SCREWUP("size out of range");
                   1694:                size = (off_t)ull;
                   1695:
1.1.1.15  christos 1696:                if (*cp == '\0' || strchr(cp, '/') != NULL ||
                   1697:                    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1.1       christos 1698:                        run_err("error: unexpected filename: %s", cp);
                   1699:                        exit(1);
                   1700:                }
1.1.1.15  christos 1701:                if (npatterns > 0) {
                   1702:                        for (n = 0; n < npatterns; n++) {
                   1703:                                if (fnmatch(patterns[n], cp, 0) == 0)
                   1704:                                        break;
                   1705:                        }
                   1706:                        if (n >= npatterns)
                   1707:                                SCREWUP("filename does not match request");
                   1708:                }
1.1       christos 1709:                if (targisdir) {
                   1710:                        static char *namebuf;
                   1711:                        static size_t cursize;
                   1712:                        size_t need;
                   1713:
                   1714:                        need = strlen(targ) + strlen(cp) + 250;
                   1715:                        if (need > cursize) {
1.1.1.5   christos 1716:                                free(namebuf);
1.1       christos 1717:                                namebuf = xmalloc(need);
                   1718:                                cursize = need;
                   1719:                        }
                   1720:                        (void) snprintf(namebuf, need, "%s%s%s", targ,
                   1721:                            strcmp(targ, "/") ? "/" : "", cp);
                   1722:                        np = namebuf;
                   1723:                } else
                   1724:                        np = targ;
                   1725:                curfile = cp;
                   1726:                exists = stat(np, &stb) == 0;
                   1727:                if (buf[0] == 'D') {
                   1728:                        int mod_flag = pflag;
                   1729:                        if (!iamrecursive)
                   1730:                                SCREWUP("received directory without -r");
                   1731:                        if (exists) {
                   1732:                                if (!S_ISDIR(stb.st_mode)) {
                   1733:                                        errno = ENOTDIR;
                   1734:                                        goto bad;
                   1735:                                }
                   1736:                                if (pflag)
                   1737:                                        (void) chmod(np, mode);
                   1738:                        } else {
1.1.1.21  christos 1739:                                /* Handle copying from a read-only directory */
1.1       christos 1740:                                mod_flag = 1;
1.1.1.16  christos 1741:                                if (mkdir(np, mode | S_IRWXU) == -1)
1.1       christos 1742:                                        goto bad;
                   1743:                        }
                   1744:                        vect[0] = xstrdup(np);
1.1.1.15  christos 1745:                        sink(1, vect, src);
1.1       christos 1746:                        if (setimes) {
                   1747:                                setimes = 0;
1.1.1.18  christos 1748:                                (void) utimes(vect[0], tv);
1.1       christos 1749:                        }
                   1750:                        if (mod_flag)
                   1751:                                (void) chmod(vect[0], mode);
1.1.1.5   christos 1752:                        free(vect[0]);
1.1       christos 1753:                        continue;
                   1754:                }
                   1755:                omode = mode;
1.1.1.5   christos 1756:                mode |= S_IWUSR;
1.1.1.16  christos 1757:                if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1.1       christos 1758: bad:                   run_err("%s: %s", np, strerror(errno));
                   1759:                        continue;
                   1760:                }
                   1761:                (void) atomicio(vwrite, remout, "", 1);
                   1762:                if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
                   1763:                        (void) close(ofd);
                   1764:                        continue;
                   1765:                }
                   1766:                cp = bp->buf;
1.1.1.18  christos 1767:                wrerr = 0;
1.1       christos 1768:
1.1.1.18  christos 1769:                /*
                   1770:                 * NB. do not use run_err() unless immediately followed by
                   1771:                 * exit() below as it may send a spurious reply that might
                   1772:                 * desyncronise us from the peer. Use note_err() instead.
                   1773:                 */
1.1       christos 1774:                statbytes = 0;
                   1775:                if (showprogress)
                   1776:                        start_progress_meter(curfile, size, &statbytes);
                   1777:                set_nonblock(remin);
                   1778:                for (count = i = 0; i < size; i += bp->cnt) {
                   1779:                        amt = bp->cnt;
                   1780:                        if (i + amt > size)
                   1781:                                amt = size - i;
                   1782:                        count += amt;
                   1783:                        do {
1.1.1.3   christos 1784:                                j = atomicio6(read, remin, cp, amt,
                   1785:                                    scpio, &statbytes);
1.1       christos 1786:                                if (j == 0) {
                   1787:                                        run_err("%s", j != EPIPE ?
                   1788:                                            strerror(errno) :
                   1789:                                            "dropped connection");
                   1790:                                        exit(1);
                   1791:                                }
                   1792:                                amt -= j;
                   1793:                                cp += j;
                   1794:                        } while (amt > 0);
                   1795:
                   1796:                        if (count == bp->cnt) {
                   1797:                                /* Keep reading so we stay sync'd up. */
1.1.1.18  christos 1798:                                if (!wrerr) {
1.1       christos 1799:                                        if (atomicio(vwrite, ofd, bp->buf,
                   1800:                                            count) != count) {
1.1.1.18  christos 1801:                                                note_err("%s: %s", np,
                   1802:                                                    strerror(errno));
                   1803:                                                wrerr = 1;
1.1       christos 1804:                                        }
                   1805:                                }
                   1806:                                count = 0;
                   1807:                                cp = bp->buf;
                   1808:                        }
                   1809:                }
                   1810:                unset_nonblock(remin);
1.1.1.18  christos 1811:                if (count != 0 && !wrerr &&
1.1       christos 1812:                    atomicio(vwrite, ofd, bp->buf, count) != count) {
1.1.1.18  christos 1813:                        note_err("%s: %s", np, strerror(errno));
                   1814:                        wrerr = 1;
1.1       christos 1815:                }
1.1.1.18  christos 1816:                if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
                   1817:                    ftruncate(ofd, size) != 0)
                   1818:                        note_err("%s: truncate: %s", np, strerror(errno));
1.1       christos 1819:                if (pflag) {
                   1820:                        if (exists || omode != mode)
                   1821:                                if (fchmod(ofd, omode)) {
1.1.1.18  christos 1822:                                        note_err("%s: set mode: %s",
1.1       christos 1823:                                            np, strerror(errno));
                   1824:                                }
                   1825:                } else {
                   1826:                        if (!exists && omode != mode)
                   1827:                                if (fchmod(ofd, omode & ~mask)) {
1.1.1.18  christos 1828:                                        note_err("%s: set mode: %s",
1.1       christos 1829:                                            np, strerror(errno));
                   1830:                                }
                   1831:                }
1.1.1.18  christos 1832:                if (close(ofd) == -1)
1.1.1.19  christos 1833:                        note_err("%s: close: %s", np, strerror(errno));
1.1       christos 1834:                (void) response();
1.1.1.10  christos 1835:                if (showprogress)
                   1836:                        stop_progress_meter();
1.1.1.18  christos 1837:                if (setimes && !wrerr) {
1.1       christos 1838:                        setimes = 0;
1.1.1.16  christos 1839:                        if (utimes(np, tv) == -1) {
1.1.1.18  christos 1840:                                note_err("%s: set times: %s",
1.1       christos 1841:                                    np, strerror(errno));
                   1842:                        }
                   1843:                }
1.1.1.18  christos 1844:                /* If no error was noted then signal success for this file */
                   1845:                if (note_err(NULL) == 0)
1.1       christos 1846:                        (void) atomicio(vwrite, remout, "", 1);
                   1847:        }
1.1.1.15  christos 1848: done:
                   1849:        for (n = 0; n < npatterns; n++)
                   1850:                free(patterns[n]);
                   1851:        free(patterns);
                   1852:        return;
1.1       christos 1853: screwup:
1.1.1.15  christos 1854:        for (n = 0; n < npatterns; n++)
                   1855:                free(patterns[n]);
                   1856:        free(patterns);
1.1       christos 1857:        run_err("protocol error: %s", why);
                   1858:        exit(1);
                   1859: }
                   1860:
1.1.1.22  christos 1861: void
                   1862: throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
                   1863:     char *src, char *targ)
                   1864: {
                   1865:        char *target = NULL, *filename = NULL, *abs_dst = NULL;
                   1866:        char *abs_src = NULL, *tmp = NULL;
                   1867:        glob_t g;
                   1868:        int i, r, targetisdir, err = 0;
                   1869:
                   1870:        if ((filename = basename(src)) == NULL)
                   1871:                fatal("basename %s: %s", src, strerror(errno));
                   1872:
                   1873:        if ((abs_src = prepare_remote_path(from, src)) == NULL ||
                   1874:            (target = prepare_remote_path(to, targ)) == NULL)
                   1875:                cleanup_exit(255);
                   1876:        memset(&g, 0, sizeof(g));
                   1877:
                   1878:        targetisdir = remote_is_dir(to, target);
                   1879:        if (!targetisdir && targetshouldbedirectory) {
1.1.1.24  christos 1880:                error("%s: destination is not a directory", targ);
1.1.1.22  christos 1881:                err = -1;
                   1882:                goto out;
                   1883:        }
                   1884:
                   1885:        debug3_f("copying remote %s to remote %s", abs_src, target);
                   1886:        if ((r = remote_glob(from, abs_src, GLOB_MARK, NULL, &g)) != 0) {
                   1887:                if (r == GLOB_NOSPACE)
1.1.1.24  christos 1888:                        error("%s: too many glob matches", src);
1.1.1.22  christos 1889:                else
1.1.1.24  christos 1890:                        error("%s: %s", src, strerror(ENOENT));
1.1.1.22  christos 1891:                err = -1;
                   1892:                goto out;
                   1893:        }
                   1894:
                   1895:        for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
                   1896:                tmp = xstrdup(g.gl_pathv[i]);
                   1897:                if ((filename = basename(tmp)) == NULL) {
                   1898:                        error("basename %s: %s", tmp, strerror(errno));
                   1899:                        err = -1;
                   1900:                        goto out;
                   1901:                }
                   1902:
                   1903:                if (targetisdir)
                   1904:                        abs_dst = path_append(target, filename);
                   1905:                else
                   1906:                        abs_dst = xstrdup(target);
                   1907:
                   1908:                debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
                   1909:                if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
                   1910:                        if (crossload_dir(from, to, g.gl_pathv[i], abs_dst,
                   1911:                            NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
                   1912:                                err = -1;
                   1913:                } else {
                   1914:                        if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL,
                   1915:                            pflag) == -1)
                   1916:                                err = -1;
                   1917:                }
                   1918:                free(abs_dst);
                   1919:                abs_dst = NULL;
                   1920:                free(tmp);
                   1921:                tmp = NULL;
                   1922:        }
                   1923:
                   1924: out:
                   1925:        free(abs_src);
                   1926:        free(abs_dst);
                   1927:        free(target);
                   1928:        free(tmp);
                   1929:        globfree(&g);
                   1930:        if (err == -1)
1.1.1.23  christos 1931:                errs = 1;
1.1.1.22  christos 1932: }
                   1933:
1.1       christos 1934: int
                   1935: response(void)
                   1936: {
1.1.1.10  christos 1937:        char ch, *cp, resp, rbuf[2048], visbuf[2048];
1.1       christos 1938:
                   1939:        if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
                   1940:                lostconn(0);
                   1941:
                   1942:        cp = rbuf;
                   1943:        switch (resp) {
                   1944:        case 0:         /* ok */
                   1945:                return (0);
                   1946:        default:
                   1947:                *cp++ = resp;
                   1948:                /* FALLTHROUGH */
                   1949:        case 1:         /* error, followed by error msg */
                   1950:        case 2:         /* fatal error, "" */
                   1951:                do {
                   1952:                        if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
                   1953:                                lostconn(0);
                   1954:                        *cp++ = ch;
                   1955:                } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
                   1956:
1.1.1.10  christos 1957:                if (!iamremote) {
                   1958:                        cp[-1] = '\0';
                   1959:                        (void) snmprintf(visbuf, sizeof(visbuf),
                   1960:                            NULL, "%s\n", rbuf);
                   1961:                        (void) atomicio(vwrite, STDERR_FILENO,
                   1962:                            visbuf, strlen(visbuf));
                   1963:                }
1.1       christos 1964:                ++errs;
                   1965:                if (resp == 1)
                   1966:                        return (-1);
                   1967:                exit(1);
                   1968:        }
                   1969:        /* NOTREACHED */
                   1970: }
                   1971:
                   1972: void
                   1973: usage(void)
                   1974: {
                   1975:        (void) fprintf(stderr,
1.1.1.22  christos 1976:            "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
                   1977:            "           [-i identity_file] [-J destination] [-l limit]\n"
                   1978:            "           [-o ssh_option] [-P port] [-S program] source ... target\n");
1.1       christos 1979:        exit(1);
                   1980: }
                   1981:
                   1982: void
                   1983: run_err(const char *fmt,...)
                   1984: {
                   1985:        static FILE *fp;
                   1986:        va_list ap;
                   1987:
                   1988:        ++errs;
                   1989:        if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
                   1990:                (void) fprintf(fp, "%c", 0x01);
                   1991:                (void) fprintf(fp, "scp: ");
                   1992:                va_start(ap, fmt);
                   1993:                (void) vfprintf(fp, fmt, ap);
                   1994:                va_end(ap);
                   1995:                (void) fprintf(fp, "\n");
                   1996:                (void) fflush(fp);
                   1997:        }
                   1998:
                   1999:        if (!iamremote) {
                   2000:                va_start(ap, fmt);
1.1.1.10  christos 2001:                vfmprintf(stderr, fmt, ap);
1.1       christos 2002:                va_end(ap);
                   2003:                fprintf(stderr, "\n");
                   2004:        }
                   2005: }
                   2006:
1.1.1.18  christos 2007: /*
                   2008:  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
                   2009:  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
                   2010:  * any active error at the end of the transfer.
                   2011:  */
                   2012: int
                   2013: note_err(const char *fmt, ...)
                   2014: {
                   2015:        static char *emsg;
                   2016:        va_list ap;
                   2017:
                   2018:        /* Replay any previously-noted error */
                   2019:        if (fmt == NULL) {
                   2020:                if (emsg == NULL)
                   2021:                        return 0;
                   2022:                run_err("%s", emsg);
                   2023:                free(emsg);
                   2024:                emsg = NULL;
                   2025:                return -1;
                   2026:        }
                   2027:
                   2028:        errs++;
                   2029:        /* Prefer first-noted error */
                   2030:        if (emsg != NULL)
                   2031:                return -1;
                   2032:
                   2033:        va_start(ap, fmt);
                   2034:        vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
                   2035:        va_end(ap);
                   2036:        return -1;
                   2037: }
                   2038:
1.1       christos 2039: void
                   2040: verifydir(char *cp)
                   2041: {
                   2042:        struct stat stb;
                   2043:
                   2044:        if (!stat(cp, &stb)) {
                   2045:                if (S_ISDIR(stb.st_mode))
                   2046:                        return;
                   2047:                errno = ENOTDIR;
                   2048:        }
                   2049:        run_err("%s: %s", cp, strerror(errno));
                   2050:        killchild(0);
                   2051: }
                   2052:
                   2053: int
                   2054: okname(char *cp0)
                   2055: {
                   2056:        int c;
                   2057:        char *cp;
                   2058:
                   2059:        cp = cp0;
                   2060:        do {
                   2061:                c = (int)*cp;
                   2062:                if (c & 0200)
                   2063:                        goto bad;
1.1.1.6   christos 2064:                if (!isalpha(c) && !isdigit((unsigned char)c)) {
1.1       christos 2065:                        switch (c) {
                   2066:                        case '\'':
                   2067:                        case '"':
                   2068:                        case '`':
                   2069:                        case ' ':
                   2070:                        case '#':
                   2071:                                goto bad;
                   2072:                        default:
                   2073:                                break;
                   2074:                        }
                   2075:                }
                   2076:        } while (*++cp);
                   2077:        return (1);
                   2078:
1.1.1.10  christos 2079: bad:   fmprintf(stderr, "%s: invalid user name\n", cp0);
1.1       christos 2080:        return (0);
                   2081: }
                   2082:
                   2083: BUF *
                   2084: allocbuf(BUF *bp, int fd, int blksize)
                   2085: {
                   2086:        size_t size;
                   2087:        struct stat stb;
                   2088:
1.1.1.16  christos 2089:        if (fstat(fd, &stb) == -1) {
1.1       christos 2090:                run_err("fstat: %s", strerror(errno));
                   2091:                return (0);
                   2092:        }
1.1.1.11  christos 2093:        size = ROUNDUP(stb.st_blksize, blksize);
1.1       christos 2094:        if (size == 0)
                   2095:                size = blksize;
                   2096:        if (bp->cnt >= size)
                   2097:                return (bp);
1.1.1.12  christos 2098:        bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1.1       christos 2099:        bp->cnt = size;
                   2100:        return (bp);
                   2101: }
                   2102:
                   2103: void
                   2104: lostconn(int signo)
                   2105: {
                   2106:        if (!iamremote)
1.1.1.5   christos 2107:                (void)write(STDERR_FILENO, "lost connection\n", 16);
1.1       christos 2108:        if (signo)
                   2109:                _exit(1);
                   2110:        else
                   2111:                exit(1);
                   2112: }
1.1.1.22  christos 2113:
                   2114: void
                   2115: cleanup_exit(int i)
                   2116: {
                   2117:        if (remin > 0)
                   2118:                close(remin);
                   2119:        if (remout > 0)
                   2120:                close(remout);
                   2121:        if (remin2 > 0)
                   2122:                close(remin2);
                   2123:        if (remout2 > 0)
                   2124:                close(remout2);
                   2125:        if (do_cmd_pid > 0)
                   2126:                waitpid(do_cmd_pid, NULL, 0);
                   2127:        if (do_cmd_pid2 > 0)
                   2128:                waitpid(do_cmd_pid2, NULL, 0);
                   2129:        exit(i);
                   2130: }

CVSweb <webmaster@jp.NetBSD.org>