[BACK]Return to clientloop.c CVS log [TXT][DIR] Up to [local] / src / usr.bin / ssh

Annotation of src/usr.bin/ssh/clientloop.c, Revision 1.102

1.1       deraadt     1: /*
1.12      deraadt     2:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      3:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      4:  *                    All rights reserved
1.33      deraadt     5:  * The main loop for the interactive session (client side).
1.20      markus      6:  *
1.33      deraadt     7:  * As far as I am concerned, the code I have written for this software
                      8:  * can be used freely for any purpose.  Any derived versions of this
                      9:  * software must be clearly marked as such, and if the derived work is
                     10:  * incompatible with the protocol description in the RFC file, it must be
                     11:  * called by a name other than "ssh" or "Secure Shell".
                     12:  *
                     13:  *
                     14:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     15:  *
                     16:  * Redistribution and use in source and binary forms, with or without
                     17:  * modification, are permitted provided that the following conditions
                     18:  * are met:
                     19:  * 1. Redistributions of source code must retain the above copyright
                     20:  *    notice, this list of conditions and the following disclaimer.
                     21:  * 2. Redistributions in binary form must reproduce the above copyright
                     22:  *    notice, this list of conditions and the following disclaimer in the
                     23:  *    documentation and/or other materials provided with the distribution.
                     24:  *
                     25:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     26:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     27:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     28:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     29:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     30:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     31:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     32:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     33:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     34:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.20      markus     35:  *
                     36:  *
1.33      deraadt    37:  * SSH2 support added by Markus Friedl.
1.78      markus     38:  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
1.20      markus     39:  *
1.33      deraadt    40:  * Redistribution and use in source and binary forms, with or without
                     41:  * modification, are permitted provided that the following conditions
                     42:  * are met:
                     43:  * 1. Redistributions of source code must retain the above copyright
                     44:  *    notice, this list of conditions and the following disclaimer.
                     45:  * 2. Redistributions in binary form must reproduce the above copyright
                     46:  *    notice, this list of conditions and the following disclaimer in the
                     47:  *    documentation and/or other materials provided with the distribution.
                     48:  *
                     49:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     50:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     51:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     52:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     53:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     54:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     55:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     56:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     57:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     58:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.12      deraadt    59:  */
1.1       deraadt    60:
                     61: #include "includes.h"
1.102   ! markus     62: RCSID("$OpenBSD: clientloop.c,v 1.101 2002/06/09 13:32:01 markus Exp $");
1.1       deraadt    63:
1.45      markus     64: #include "ssh.h"
                     65: #include "ssh1.h"
                     66: #include "ssh2.h"
1.1       deraadt    67: #include "xmalloc.h"
                     68: #include "packet.h"
                     69: #include "buffer.h"
1.15      markus     70: #include "compat.h"
1.74      markus     71: #include "channels.h"
1.15      markus     72: #include "dispatch.h"
1.30      markus     73: #include "buffer.h"
                     74: #include "bufaux.h"
1.40      markus     75: #include "key.h"
1.54      markus     76: #include "kex.h"
1.45      markus     77: #include "log.h"
                     78: #include "readconf.h"
                     79: #include "clientloop.h"
1.40      markus     80: #include "authfd.h"
1.45      markus     81: #include "atomicio.h"
1.62      stevesk    82: #include "sshtty.h"
1.63      markus     83: #include "misc.h"
1.97      jakob      84: #include "readpass.h"
1.39      markus     85:
                     86: /* import options */
                     87: extern Options options;
                     88:
1.1       deraadt    89: /* Flag indicating that stdin should be redirected from /dev/null. */
                     90: extern int stdin_null_flag;
                     91:
1.13      markus     92: /*
                     93:  * Name of the host we are connecting to.  This is the name given on the
                     94:  * command line, or the HostName specified for the user-supplied name in a
                     95:  * configuration file.
                     96:  */
1.1       deraadt    97: extern char *host;
                     98:
1.13      markus     99: /*
                    100:  * Flag to indicate that we have received a window change signal which has
                    101:  * not yet been processed.  This will cause a message indicating the new
                    102:  * window size to be sent to the server a little later.  This is volatile
                    103:  * because this is updated in a signal handler.
                    104:  */
1.88      markus    105: static volatile sig_atomic_t received_window_change_signal = 0;
                    106: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   107:
                    108: /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
                    109: static int in_non_blocking_mode = 0;
                    110:
                    111: /* Common data for the client loop code. */
1.31      markus    112: static int quit_pending;       /* Set to non-zero to quit the client loop. */
                    113: static int escape_char;                /* Escape character. */
1.11      markus    114: static int escape_pending;     /* Last character was the escape character */
                    115: static int last_was_cr;                /* Last character was a newline. */
                    116: static int exit_status;                /* Used to store the exit status of the command. */
                    117: static int stdin_eof;          /* EOF has been encountered on standard error. */
                    118: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                    119: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                    120: static Buffer stderr_buffer;   /* Buffer for stderr data. */
1.42      markus    121: static u_long stdin_bytes, stdout_bytes, stderr_bytes;
                    122: static u_int buffer_high;/* Soft max buffer size. */
1.11      markus    123: static int connection_in;      /* Connection to server (input). */
                    124: static int connection_out;     /* Connection to server (output). */
1.56      markus    125: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.60      markus    126: static int session_closed = 0; /* In SSH2: login session closed. */
1.1       deraadt   127:
1.77      itojun    128: static void client_init_dispatch(void);
1.16      markus    129: int    session_ident = -1;
                    130:
1.54      markus    131: /*XXX*/
                    132: extern Kex *xxx_kex;
                    133:
1.1       deraadt   134: /* Restores stdin to blocking mode. */
                    135:
1.77      itojun    136: static void
1.49      itojun    137: leave_non_blocking(void)
1.1       deraadt   138: {
1.11      markus    139:        if (in_non_blocking_mode) {
                    140:                (void) fcntl(fileno(stdin), F_SETFL, 0);
                    141:                in_non_blocking_mode = 0;
                    142:                fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
                    143:        }
1.1       deraadt   144: }
                    145:
1.11      markus    146: /* Puts stdin terminal in non-blocking mode. */
                    147:
1.77      itojun    148: static void
1.49      itojun    149: enter_non_blocking(void)
1.1       deraadt   150: {
1.11      markus    151:        in_non_blocking_mode = 1;
                    152:        (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
                    153:        fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
1.1       deraadt   154: }
                    155:
1.13      markus    156: /*
                    157:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    158:  * flag indicating that the window has changed.
                    159:  */
1.1       deraadt   160:
1.77      itojun    161: static void
1.11      markus    162: window_change_handler(int sig)
1.1       deraadt   163: {
1.11      markus    164:        received_window_change_signal = 1;
                    165:        signal(SIGWINCH, window_change_handler);
1.1       deraadt   166: }
                    167:
1.13      markus    168: /*
                    169:  * Signal handler for signals that cause the program to terminate.  These
                    170:  * signals must be trapped to restore terminal modes.
                    171:  */
1.1       deraadt   172:
1.77      itojun    173: static void
1.11      markus    174: signal_handler(int sig)
1.1       deraadt   175: {
1.75      markus    176:        received_signal = sig;
                    177:        quit_pending = 1;
1.1       deraadt   178: }
                    179:
1.13      markus    180: /*
                    181:  * Returns current time in seconds from Jan 1, 1970 with the maximum
                    182:  * available resolution.
                    183:  */
1.1       deraadt   184:
1.77      itojun    185: static double
1.49      itojun    186: get_current_time(void)
1.1       deraadt   187: {
1.11      markus    188:        struct timeval tv;
                    189:        gettimeofday(&tv, NULL);
                    190:        return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
1.1       deraadt   191: }
                    192:
1.13      markus    193: /*
                    194:  * This is called when the interactive is entered.  This checks if there is
                    195:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    196:  * not appear to wake up when redirecting from /dev/null.
                    197:  */
1.1       deraadt   198:
1.77      itojun    199: static void
1.49      itojun    200: client_check_initial_eof_on_stdin(void)
1.1       deraadt   201: {
1.11      markus    202:        int len;
                    203:        char buf[1];
1.1       deraadt   204:
1.13      markus    205:        /*
                    206:         * If standard input is to be "redirected from /dev/null", we simply
                    207:         * mark that we have seen an EOF and send an EOF message to the
                    208:         * server. Otherwise, we try to read a single character; it appears
                    209:         * that for some files, such /dev/null, select() never wakes up for
                    210:         * read for this descriptor, which means that we never get EOF.  This
                    211:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    212:         */
1.11      markus    213:        if (stdin_null_flag) {
                    214:                /* Fake EOF on stdin. */
                    215:                debug("Sending eof.");
                    216:                stdin_eof = 1;
                    217:                packet_start(SSH_CMSG_EOF);
                    218:                packet_send();
                    219:        } else {
                    220:                enter_non_blocking();
                    221:
                    222:                /* Check for immediate EOF on stdin. */
                    223:                len = read(fileno(stdin), buf, 1);
                    224:                if (len == 0) {
1.13      markus    225:                        /* EOF.  Record that we have seen it and send EOF to server. */
1.11      markus    226:                        debug("Sending eof.");
                    227:                        stdin_eof = 1;
                    228:                        packet_start(SSH_CMSG_EOF);
                    229:                        packet_send();
                    230:                } else if (len > 0) {
1.13      markus    231:                        /*
                    232:                         * Got data.  We must store the data in the buffer,
                    233:                         * and also process it as an escape character if
                    234:                         * appropriate.
                    235:                         */
1.42      markus    236:                        if ((u_char) buf[0] == escape_char)
1.11      markus    237:                                escape_pending = 1;
1.52      markus    238:                        else
1.11      markus    239:                                buffer_append(&stdin_buffer, buf, 1);
                    240:                }
                    241:                leave_non_blocking();
                    242:        }
1.1       deraadt   243: }
                    244:
                    245:
1.13      markus    246: /*
                    247:  * Make packets from buffered stdin data, and buffer them for sending to the
                    248:  * connection.
                    249:  */
1.1       deraadt   250:
1.77      itojun    251: static void
1.49      itojun    252: client_make_packets_from_stdin_data(void)
1.1       deraadt   253: {
1.42      markus    254:        u_int len;
1.1       deraadt   255:
1.11      markus    256:        /* Send buffered stdin data to the server. */
                    257:        while (buffer_len(&stdin_buffer) > 0 &&
1.90      deraadt   258:            packet_not_very_much_data_to_write()) {
1.11      markus    259:                len = buffer_len(&stdin_buffer);
                    260:                /* Keep the packets at reasonable size. */
                    261:                if (len > packet_get_maxsize())
                    262:                        len = packet_get_maxsize();
                    263:                packet_start(SSH_CMSG_STDIN_DATA);
                    264:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    265:                packet_send();
                    266:                buffer_consume(&stdin_buffer, len);
1.52      markus    267:                stdin_bytes += len;
1.11      markus    268:                /* If we have a pending EOF, send it now. */
                    269:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    270:                        packet_start(SSH_CMSG_EOF);
                    271:                        packet_send();
                    272:                }
1.1       deraadt   273:        }
                    274: }
                    275:
1.13      markus    276: /*
                    277:  * Checks if the client window has changed, and sends a packet about it to
                    278:  * the server if so.  The actual change is detected elsewhere (by a software
                    279:  * interrupt on Unix); this just checks the flag and sends a message if
                    280:  * appropriate.
                    281:  */
1.1       deraadt   282:
1.77      itojun    283: static void
1.49      itojun    284: client_check_window_change(void)
1.1       deraadt   285: {
1.16      markus    286:        struct winsize ws;
                    287:
                    288:        if (! received_window_change_signal)
                    289:                return;
                    290:        /** XXX race */
                    291:        received_window_change_signal = 0;
                    292:
                    293:        if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    294:                return;
                    295:
1.37      markus    296:        debug2("client_check_window_change: changed");
1.16      markus    297:
                    298:        if (compat20) {
                    299:                channel_request_start(session_ident, "window-change", 0);
                    300:                packet_put_int(ws.ws_col);
                    301:                packet_put_int(ws.ws_row);
                    302:                packet_put_int(ws.ws_xpixel);
                    303:                packet_put_int(ws.ws_ypixel);
                    304:                packet_send();
                    305:        } else {
                    306:                packet_start(SSH_CMSG_WINDOW_SIZE);
                    307:                packet_put_int(ws.ws_row);
                    308:                packet_put_int(ws.ws_col);
                    309:                packet_put_int(ws.ws_xpixel);
                    310:                packet_put_int(ws.ws_ypixel);
                    311:                packet_send();
1.1       deraadt   312:        }
                    313: }
                    314:
1.13      markus    315: /*
                    316:  * Waits until the client can do something (some data becomes available on
                    317:  * one of the file descriptors).
                    318:  */
1.1       deraadt   319:
1.77      itojun    320: static void
1.46      markus    321: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.81      markus    322:     int *maxfdp, int *nallocp, int rekeying)
1.11      markus    323: {
1.46      markus    324:        /* Add any selections by the channel mechanism. */
1.81      markus    325:        channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
1.11      markus    326:
1.16      markus    327:        if (!compat20) {
1.17      markus    328:                /* Read from the connection, unless our buffers are full. */
1.16      markus    329:                if (buffer_len(&stdout_buffer) < buffer_high &&
                    330:                    buffer_len(&stderr_buffer) < buffer_high &&
                    331:                    channel_not_very_much_buffered_data())
1.46      markus    332:                        FD_SET(connection_in, *readsetp);
1.17      markus    333:                /*
                    334:                 * Read from stdin, unless we have seen EOF or have very much
                    335:                 * buffered data to send to the server.
                    336:                 */
                    337:                if (!stdin_eof && packet_not_very_much_data_to_write())
1.46      markus    338:                        FD_SET(fileno(stdin), *readsetp);
1.17      markus    339:
                    340:                /* Select stdout/stderr if have data in buffer. */
                    341:                if (buffer_len(&stdout_buffer) > 0)
1.46      markus    342:                        FD_SET(fileno(stdout), *writesetp);
1.17      markus    343:                if (buffer_len(&stderr_buffer) > 0)
1.46      markus    344:                        FD_SET(fileno(stderr), *writesetp);
1.16      markus    345:        } else {
1.71      markus    346:                /* channel_prepare_select could have closed the last channel */
1.84      markus    347:                if (session_closed && !channel_still_open() &&
                    348:                    !packet_have_data_to_write()) {
                    349:                        /* clear mask since we did not call select() */
1.87      markus    350:                        memset(*readsetp, 0, *nallocp);
                    351:                        memset(*writesetp, 0, *nallocp);
1.84      markus    352:                        return;
1.71      markus    353:                } else {
                    354:                        FD_SET(connection_in, *readsetp);
                    355:                }
1.16      markus    356:        }
1.11      markus    357:
                    358:        /* Select server connection if have data to write to the server. */
                    359:        if (packet_have_data_to_write())
1.46      markus    360:                FD_SET(connection_out, *writesetp);
1.11      markus    361:
1.13      markus    362:        /*
                    363:         * Wait for something to happen.  This will suspend the process until
                    364:         * some selected descriptor can be read, written, or has some other
                    365:         * event pending. Note: if you want to implement SSH_MSG_IGNORE
                    366:         * messages to fool traffic analysis, this might be the place to do
                    367:         * it: just have a random timeout for the select, and send a random
                    368:         * SSH_MSG_IGNORE packet when the timeout expires.
                    369:         */
1.11      markus    370:
1.46      markus    371:        if (select((*maxfdp)+1, *readsetp, *writesetp, NULL, NULL) < 0) {
1.11      markus    372:                char buf[100];
1.51      markus    373:
                    374:                /*
                    375:                 * We have to clear the select masks, because we return.
                    376:                 * We have to return, because the mainloop checks for the flags
                    377:                 * set by the signal handlers.
                    378:                 */
1.87      markus    379:                memset(*readsetp, 0, *nallocp);
                    380:                memset(*writesetp, 0, *nallocp);
1.50      deraadt   381:
1.11      markus    382:                if (errno == EINTR)
                    383:                        return;
                    384:                /* Note: we might still have data in the buffers. */
                    385:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    386:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    387:                quit_pending = 1;
                    388:        }
                    389: }
                    390:
1.77      itojun    391: static void
1.31      markus    392: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1       deraadt   393: {
1.11      markus    394:        struct winsize oldws, newws;
                    395:
                    396:        /* Flush stdout and stderr buffers. */
1.31      markus    397:        if (buffer_len(bout) > 0)
                    398:                atomicio(write, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
                    399:        if (buffer_len(berr) > 0)
                    400:                atomicio(write, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
1.11      markus    401:
                    402:        leave_raw_mode();
                    403:
1.13      markus    404:        /*
                    405:         * Free (and clear) the buffer to reduce the amount of data that gets
                    406:         * written to swap.
                    407:         */
1.31      markus    408:        buffer_free(bin);
                    409:        buffer_free(bout);
                    410:        buffer_free(berr);
1.11      markus    411:
                    412:        /* Save old window size. */
                    413:        ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
                    414:
                    415:        /* Send the suspend signal to the program itself. */
                    416:        kill(getpid(), SIGTSTP);
                    417:
                    418:        /* Check if the window size has changed. */
                    419:        if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
                    420:            (oldws.ws_row != newws.ws_row ||
1.90      deraadt   421:            oldws.ws_col != newws.ws_col ||
                    422:            oldws.ws_xpixel != newws.ws_xpixel ||
                    423:            oldws.ws_ypixel != newws.ws_ypixel))
1.11      markus    424:                received_window_change_signal = 1;
                    425:
                    426:        /* OK, we have been continued by the user. Reinitialize buffers. */
1.31      markus    427:        buffer_init(bin);
                    428:        buffer_init(bout);
                    429:        buffer_init(berr);
1.11      markus    430:
                    431:        enter_raw_mode();
                    432: }
                    433:
1.77      itojun    434: static void
1.17      markus    435: client_process_net_input(fd_set * readset)
1.11      markus    436: {
1.17      markus    437:        int len;
                    438:        char buf[8192];
1.11      markus    439:
1.13      markus    440:        /*
                    441:         * Read input from the server, and add any such data to the buffer of
                    442:         * the packet subsystem.
                    443:         */
1.11      markus    444:        if (FD_ISSET(connection_in, readset)) {
                    445:                /* Read as much as possible. */
                    446:                len = read(connection_in, buf, sizeof(buf));
                    447:                if (len == 0) {
                    448:                        /* Received EOF.  The remote host has closed the connection. */
                    449:                        snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
                    450:                                 host);
1.1       deraadt   451:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    452:                        quit_pending = 1;
                    453:                        return;
1.11      markus    454:                }
1.13      markus    455:                /*
                    456:                 * There is a kernel bug on Solaris that causes select to
                    457:                 * sometimes wake up even though there is no data available.
                    458:                 */
1.53      millert   459:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11      markus    460:                        len = 0;
                    461:
                    462:                if (len < 0) {
                    463:                        /* An error has encountered.  Perhaps there is a network problem. */
                    464:                        snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
                    465:                                 host, strerror(errno));
                    466:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    467:                        quit_pending = 1;
                    468:                        return;
                    469:                }
                    470:                packet_process_incoming(buf, len);
                    471:        }
1.17      markus    472: }
1.16      markus    473:
1.97      jakob     474: static void
1.99      markus    475: process_cmdline(void)
1.97      jakob     476: {
                    477:        void (*handler)(int);
                    478:        char *s, *cmd;
                    479:        u_short fwd_port, fwd_host_port;
                    480:        char buf[1024], sfwd_port[6], sfwd_host_port[6];
                    481:        int local = 0;
                    482:
                    483:        leave_raw_mode();
1.101     markus    484:        handler = signal(SIGINT, SIG_IGN);
1.99      markus    485:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     486:        if (s == NULL)
                    487:                goto out;
                    488:        while (*s && isspace(*s))
                    489:                s++;
                    490:        if (*s == 0)
                    491:                goto out;
                    492:        if (strlen(s) < 2 || s[0] != '-' || !(s[1] == 'L' || s[1] == 'R')) {
1.99      markus    493:                log("Invalid command.");
1.97      jakob     494:                goto out;
                    495:        }
                    496:        if (s[1] == 'L')
                    497:                local = 1;
                    498:        if (!local && !compat20) {
1.99      markus    499:                log("Not supported for SSH protocol version 1.");
1.97      jakob     500:                goto out;
                    501:        }
                    502:        s += 2;
                    503:        while (*s && isspace(*s))
                    504:                s++;
                    505:
                    506:        if (sscanf(s, "%5[0-9]:%255[^:]:%5[0-9]",
                    507:            sfwd_port, buf, sfwd_host_port) != 3 &&
                    508:            sscanf(s, "%5[0-9]/%255[^/]/%5[0-9]",
                    509:            sfwd_port, buf, sfwd_host_port) != 3) {
1.99      markus    510:                log("Bad forwarding specification.");
1.97      jakob     511:                goto out;
                    512:        }
                    513:        if ((fwd_port = a2port(sfwd_port)) == 0 ||
                    514:            (fwd_host_port = a2port(sfwd_host_port)) == 0) {
1.99      markus    515:                log("Bad forwarding port(s).");
1.97      jakob     516:                goto out;
                    517:        }
                    518:        if (local) {
1.99      markus    519:                if (channel_setup_local_fwd_listener(fwd_port, buf,
                    520:                    fwd_host_port, options.gateway_ports) < 0) {
                    521:                        log("Port forwarding failed.");
1.97      jakob     522:                        goto out;
                    523:                }
                    524:        } else
                    525:                channel_request_remote_forwarding(fwd_port, buf,
                    526:                    fwd_host_port);
1.99      markus    527:        log("Forwarding port.");
1.97      jakob     528: out:
                    529:        signal(SIGINT, handler);
                    530:        enter_raw_mode();
                    531:        if (cmd)
                    532:                xfree(cmd);
                    533: }
                    534:
1.31      markus    535: /* process the characters one by one */
1.77      itojun    536: static int
1.31      markus    537: process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
                    538: {
1.32      markus    539:        char string[1024];
1.31      markus    540:        pid_t pid;
                    541:        int bytes = 0;
1.42      markus    542:        u_int i;
                    543:        u_char ch;
1.31      markus    544:        char *s;
                    545:
                    546:        for (i = 0; i < len; i++) {
                    547:                /* Get one character at a time. */
                    548:                ch = buf[i];
                    549:
                    550:                if (escape_pending) {
                    551:                        /* We have previously seen an escape character. */
                    552:                        /* Clear the flag now. */
                    553:                        escape_pending = 0;
                    554:
                    555:                        /* Process the escaped character. */
                    556:                        switch (ch) {
                    557:                        case '.':
                    558:                                /* Terminate the connection. */
1.32      markus    559:                                snprintf(string, sizeof string, "%c.\r\n", escape_char);
                    560:                                buffer_append(berr, string, strlen(string));
1.31      markus    561:
                    562:                                quit_pending = 1;
                    563:                                return -1;
                    564:
                    565:                        case 'Z' - 64:
                    566:                                /* Suspend the program. */
                    567:                                /* Print a message to that effect to the user. */
1.32      markus    568:                                snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
                    569:                                buffer_append(berr, string, strlen(string));
1.31      markus    570:
                    571:                                /* Restore terminal modes and suspend. */
                    572:                                client_suspend_self(bin, bout, berr);
                    573:
                    574:                                /* We have been continued. */
                    575:                                continue;
                    576:
1.54      markus    577:                        case 'R':
1.59      markus    578:                                if (compat20) {
                    579:                                        if (datafellows & SSH_BUG_NOREKEY)
                    580:                                                log("Server does not support re-keying");
                    581:                                        else
                    582:                                                need_rekeying = 1;
                    583:                                }
1.54      markus    584:                                continue;
                    585:
1.31      markus    586:                        case '&':
                    587:                                /*
                    588:                                 * Detach the program (continue to serve connections,
                    589:                                 * but put in background and no more new connections).
                    590:                                 */
                    591:                                /* Restore tty modes. */
                    592:                                leave_raw_mode();
                    593:
                    594:                                /* Stop listening for new connections. */
1.86      markus    595:                                channel_stop_listening();
1.31      markus    596:
1.86      markus    597:                                snprintf(string, sizeof string,
                    598:                                    "%c& [backgrounded]\n", escape_char);
                    599:                                buffer_append(berr, string, strlen(string));
1.31      markus    600:
                    601:                                /* Fork into background. */
                    602:                                pid = fork();
                    603:                                if (pid < 0) {
                    604:                                        error("fork: %.100s", strerror(errno));
                    605:                                        continue;
                    606:                                }
                    607:                                if (pid != 0) { /* This is the parent. */
                    608:                                        /* The parent just exits. */
                    609:                                        exit(0);
                    610:                                }
                    611:                                /* The child continues serving connections. */
1.86      markus    612:                                if (compat20) {
                    613:                                        buffer_append(bin, "\004", 1);
                    614:                                        /* fake EOF on stdin */
                    615:                                        return -1;
                    616:                                } else if (!stdin_eof) {
                    617:                                        /*
                    618:                                         * Sending SSH_CMSG_EOF alone does not always appear
                    619:                                         * to be enough.  So we try to send an EOF character
                    620:                                         * first.
                    621:                                         */
                    622:                                        packet_start(SSH_CMSG_STDIN_DATA);
                    623:                                        packet_put_string("\004", 1);
                    624:                                        packet_send();
                    625:                                        /* Close stdin. */
                    626:                                        stdin_eof = 1;
                    627:                                        if (buffer_len(bin) == 0) {
                    628:                                                packet_start(SSH_CMSG_EOF);
                    629:                                                packet_send();
                    630:                                        }
                    631:                                }
                    632:                                continue;
1.31      markus    633:
                    634:                        case '?':
1.32      markus    635:                                snprintf(string, sizeof string,
1.31      markus    636: "%c?\r\n\
                    637: Supported escape sequences:\r\n\
                    638: ~.  - terminate connection\r\n\
1.97      jakob     639: ~C  - open a command line\r\n\
1.72      stevesk   640: ~R  - Request rekey (SSH protocol 2 only)\r\n\
1.31      markus    641: ~^Z - suspend ssh\r\n\
                    642: ~#  - list forwarded connections\r\n\
                    643: ~&  - background ssh (when waiting for connections to terminate)\r\n\
                    644: ~?  - this message\r\n\
                    645: ~~  - send the escape character by typing it twice\r\n\
                    646: (Note that escapes are only recognized immediately after newline.)\r\n",
                    647:                                         escape_char);
1.32      markus    648:                                buffer_append(berr, string, strlen(string));
1.31      markus    649:                                continue;
                    650:
                    651:                        case '#':
1.32      markus    652:                                snprintf(string, sizeof string, "%c#\r\n", escape_char);
                    653:                                buffer_append(berr, string, strlen(string));
1.31      markus    654:                                s = channel_open_message();
                    655:                                buffer_append(berr, s, strlen(s));
                    656:                                xfree(s);
1.97      jakob     657:                                continue;
                    658:
                    659:                        case 'C':
1.99      markus    660:                                process_cmdline();
1.31      markus    661:                                continue;
                    662:
                    663:                        default:
                    664:                                if (ch != escape_char) {
                    665:                                        buffer_put_char(bin, escape_char);
                    666:                                        bytes++;
                    667:                                }
                    668:                                /* Escaped characters fall through here */
                    669:                                break;
                    670:                        }
                    671:                } else {
                    672:                        /*
                    673:                         * The previous character was not an escape char. Check if this
                    674:                         * is an escape.
                    675:                         */
                    676:                        if (last_was_cr && ch == escape_char) {
                    677:                                /* It is. Set the flag and continue to next character. */
                    678:                                escape_pending = 1;
                    679:                                continue;
                    680:                        }
                    681:                }
                    682:
                    683:                /*
                    684:                 * Normal character.  Record whether it was a newline,
                    685:                 * and append it to the buffer.
                    686:                 */
                    687:                last_was_cr = (ch == '\r' || ch == '\n');
                    688:                buffer_put_char(bin, ch);
                    689:                bytes++;
                    690:        }
                    691:        return bytes;
                    692: }
                    693:
1.77      itojun    694: static void
1.17      markus    695: client_process_input(fd_set * readset)
                    696: {
1.21      deraadt   697:        int len;
1.31      markus    698:        char buf[8192];
1.16      markus    699:
1.11      markus    700:        /* Read input from stdin. */
                    701:        if (FD_ISSET(fileno(stdin), readset)) {
                    702:                /* Read as much as possible. */
                    703:                len = read(fileno(stdin), buf, sizeof(buf));
1.64      markus    704:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
                    705:                        return;         /* we'll try again later */
1.11      markus    706:                if (len <= 0) {
1.13      markus    707:                        /*
                    708:                         * Received EOF or error.  They are treated
                    709:                         * similarly, except that an error message is printed
                    710:                         * if it was an error condition.
                    711:                         */
1.11      markus    712:                        if (len < 0) {
                    713:                                snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
                    714:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    715:                        }
                    716:                        /* Mark that we have seen EOF. */
                    717:                        stdin_eof = 1;
1.13      markus    718:                        /*
                    719:                         * Send an EOF message to the server unless there is
                    720:                         * data in the buffer.  If there is data in the
                    721:                         * buffer, no message will be sent now.  Code
                    722:                         * elsewhere will send the EOF when the buffer
                    723:                         * becomes empty if stdin_eof is set.
                    724:                         */
1.11      markus    725:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt   726:                                packet_start(SSH_CMSG_EOF);
                    727:                                packet_send();
1.11      markus    728:                        }
1.72      stevesk   729:                } else if (escape_char == SSH_ESCAPECHAR_NONE) {
1.13      markus    730:                        /*
                    731:                         * Normal successful read, and no escape character.
                    732:                         * Just append the data to buffer.
                    733:                         */
1.11      markus    734:                        buffer_append(&stdin_buffer, buf, len);
                    735:                } else {
1.13      markus    736:                        /*
                    737:                         * Normal, successful read.  But we have an escape character
                    738:                         * and have to process the characters one by one.
                    739:                         */
1.52      markus    740:                        if (process_escapes(&stdin_buffer, &stdout_buffer,
                    741:                            &stderr_buffer, buf, len) == -1)
1.31      markus    742:                                return;
1.11      markus    743:                }
                    744:        }
                    745: }
                    746:
1.77      itojun    747: static void
1.11      markus    748: client_process_output(fd_set * writeset)
                    749: {
                    750:        int len;
                    751:        char buf[100];
1.1       deraadt   752:
1.11      markus    753:        /* Write buffered output to stdout. */
                    754:        if (FD_ISSET(fileno(stdout), writeset)) {
                    755:                /* Write as much data as possible. */
                    756:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt   757:                    buffer_len(&stdout_buffer));
1.11      markus    758:                if (len <= 0) {
1.64      markus    759:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus    760:                                len = 0;
                    761:                        else {
1.13      markus    762:                                /*
                    763:                                 * An error or EOF was encountered.  Put an
                    764:                                 * error message to stderr buffer.
                    765:                                 */
1.11      markus    766:                                snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
                    767:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    768:                                quit_pending = 1;
                    769:                                return;
                    770:                        }
                    771:                }
                    772:                /* Consume printed data from the buffer. */
                    773:                buffer_consume(&stdout_buffer, len);
1.57      markus    774:                stdout_bytes += len;
1.11      markus    775:        }
                    776:        /* Write buffered output to stderr. */
                    777:        if (FD_ISSET(fileno(stderr), writeset)) {
                    778:                /* Write as much data as possible. */
                    779:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt   780:                    buffer_len(&stderr_buffer));
1.11      markus    781:                if (len <= 0) {
1.64      markus    782:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus    783:                                len = 0;
                    784:                        else {
1.13      markus    785:                                /* EOF or error, but can't even print error message. */
1.11      markus    786:                                quit_pending = 1;
                    787:                                return;
                    788:                        }
                    789:                }
                    790:                /* Consume printed characters from the buffer. */
                    791:                buffer_consume(&stderr_buffer, len);
1.57      markus    792:                stderr_bytes += len;
1.11      markus    793:        }
1.1       deraadt   794: }
                    795:
1.13      markus    796: /*
1.15      markus    797:  * Get packets from the connection input buffer, and process them as long as
                    798:  * there are packets available.
                    799:  *
                    800:  * Any unknown packets received during the actual
                    801:  * session cause the session to terminate.  This is
                    802:  * intended to make debugging easier since no
                    803:  * confirmations are sent.  Any compatible protocol
                    804:  * extensions must be negotiated during the
                    805:  * preparatory phase.
                    806:  */
                    807:
1.77      itojun    808: static void
1.49      itojun    809: client_process_buffered_input_packets(void)
1.15      markus    810: {
1.54      markus    811:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
1.15      markus    812: }
                    813:
1.31      markus    814: /* scan buf[] for '~' before sending data to the peer */
1.30      markus    815:
1.77      itojun    816: static int
1.31      markus    817: simple_escape_filter(Channel *c, char *buf, int len)
1.30      markus    818: {
1.31      markus    819:        /* XXX we assume c->extended is writeable */
                    820:        return process_escapes(&c->input, &c->output, &c->extended, buf, len);
1.30      markus    821: }
                    822:
1.77      itojun    823: static void
1.60      markus    824: client_channel_closed(int id, void *arg)
                    825: {
                    826:        if (id != session_ident)
                    827:                error("client_channel_closed: id %d != session_ident %d",
                    828:                    id, session_ident);
1.83      markus    829:        channel_cancel_cleanup(id);
1.60      markus    830:        session_closed = 1;
1.62      stevesk   831:        if (in_raw_mode())
1.61      markus    832:                leave_raw_mode();
1.60      markus    833: }
                    834:
1.15      markus    835: /*
1.13      markus    836:  * Implements the interactive session with the server.  This is called after
                    837:  * the user has been authenticated, and a command has been started on the
1.72      stevesk   838:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                    839:  * used as an escape character for terminating or suspending the session.
1.13      markus    840:  */
1.1       deraadt   841:
1.20      markus    842: int
1.30      markus    843: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1       deraadt   844: {
1.46      markus    845:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus    846:        double start_time, total_time;
1.81      markus    847:        int max_fd = 0, max_fd2 = 0, len, rekeying = 0, nalloc = 0;
1.11      markus    848:        char buf[100];
                    849:
                    850:        debug("Entering interactive session.");
                    851:
                    852:        start_time = get_current_time();
                    853:
                    854:        /* Initialize variables. */
                    855:        escape_pending = 0;
                    856:        last_was_cr = 1;
                    857:        exit_status = -1;
                    858:        stdin_eof = 0;
                    859:        buffer_high = 64 * 1024;
                    860:        connection_in = packet_get_connection_in();
                    861:        connection_out = packet_get_connection_out();
1.46      markus    862:        max_fd = MAX(connection_in, connection_out);
                    863:
                    864:        if (!compat20) {
1.63      markus    865:                /* enable nonblocking unless tty */
                    866:                if (!isatty(fileno(stdin)))
                    867:                        set_nonblock(fileno(stdin));
                    868:                if (!isatty(fileno(stdout)))
                    869:                        set_nonblock(fileno(stdout));
                    870:                if (!isatty(fileno(stderr)))
                    871:                        set_nonblock(fileno(stderr));
1.46      markus    872:                max_fd = MAX(max_fd, fileno(stdin));
                    873:                max_fd = MAX(max_fd, fileno(stdout));
                    874:                max_fd = MAX(max_fd, fileno(stderr));
                    875:        }
1.11      markus    876:        stdin_bytes = 0;
                    877:        stdout_bytes = 0;
                    878:        stderr_bytes = 0;
                    879:        quit_pending = 0;
                    880:        escape_char = escape_char_arg;
                    881:
                    882:        /* Initialize buffers. */
                    883:        buffer_init(&stdin_buffer);
                    884:        buffer_init(&stdout_buffer);
                    885:        buffer_init(&stderr_buffer);
                    886:
1.15      markus    887:        client_init_dispatch();
                    888:
1.11      markus    889:        /* Set signal handlers to restore non-blocking mode.  */
                    890:        signal(SIGINT, signal_handler);
                    891:        signal(SIGQUIT, signal_handler);
                    892:        signal(SIGTERM, signal_handler);
                    893:        if (have_pty)
                    894:                signal(SIGWINCH, window_change_handler);
                    895:
                    896:        if (have_pty)
                    897:                enter_raw_mode();
                    898:
1.48      markus    899:        if (compat20) {
                    900:                session_ident = ssh2_chan_id;
1.72      stevesk   901:                if (escape_char != SSH_ESCAPECHAR_NONE)
1.48      markus    902:                        channel_register_filter(session_ident,
                    903:                            simple_escape_filter);
1.60      markus    904:                if (session_ident != -1)
                    905:                        channel_register_cleanup(session_ident,
                    906:                            client_channel_closed);
1.48      markus    907:        } else {
                    908:                /* Check if we should immediately send eof on stdin. */
1.16      markus    909:                client_check_initial_eof_on_stdin();
1.48      markus    910:        }
1.30      markus    911:
1.11      markus    912:        /* Main loop of the client for the interactive session mode. */
                    913:        while (!quit_pending) {
                    914:
1.13      markus    915:                /* Process buffered packets sent by the server. */
1.11      markus    916:                client_process_buffered_input_packets();
                    917:
1.60      markus    918:                if (compat20 && session_closed && !channel_still_open())
                    919:                        break;
                    920:
1.56      markus    921:                rekeying = (xxx_kex != NULL && !xxx_kex->done);
1.16      markus    922:
1.56      markus    923:                if (rekeying) {
                    924:                        debug("rekeying in progress");
                    925:                } else {
                    926:                        /*
                    927:                         * Make packets of buffered stdin data, and buffer
                    928:                         * them for sending to the server.
                    929:                         */
                    930:                        if (!compat20)
                    931:                                client_make_packets_from_stdin_data();
1.11      markus    932:
1.56      markus    933:                        /*
                    934:                         * Make packets from buffered channel data, and
                    935:                         * enqueue them for sending to the server.
                    936:                         */
                    937:                        if (packet_not_very_much_data_to_write())
                    938:                                channel_output_poll();
1.11      markus    939:
1.56      markus    940:                        /*
                    941:                         * Check if the window size has changed, and buffer a
                    942:                         * message about it to the server if so.
                    943:                         */
                    944:                        client_check_window_change();
1.11      markus    945:
1.56      markus    946:                        if (quit_pending)
                    947:                                break;
                    948:                }
1.13      markus    949:                /*
                    950:                 * Wait until we have something to do (something becomes
                    951:                 * available on one of the descriptors).
                    952:                 */
1.81      markus    953:                max_fd2 = max_fd;
1.56      markus    954:                client_wait_until_can_do_something(&readset, &writeset,
1.81      markus    955:                    &max_fd2, &nalloc, rekeying);
1.11      markus    956:
                    957:                if (quit_pending)
                    958:                        break;
                    959:
1.56      markus    960:                /* Do channel operations unless rekeying in progress. */
                    961:                if (!rekeying) {
                    962:                        channel_after_select(readset, writeset);
                    963:
                    964:                        if (need_rekeying) {
                    965:                                debug("user requests rekeying");
                    966:                                xxx_kex->done = 0;
                    967:                                kex_send_kexinit(xxx_kex);
                    968:                                need_rekeying = 0;
                    969:                        }
                    970:                }
1.11      markus    971:
1.17      markus    972:                /* Buffer input from the connection.  */
1.46      markus    973:                client_process_net_input(readset);
1.17      markus    974:
                    975:                if (quit_pending)
                    976:                        break;
1.11      markus    977:
1.17      markus    978:                if (!compat20) {
                    979:                        /* Buffer data from stdin */
1.46      markus    980:                        client_process_input(readset);
1.17      markus    981:                        /*
                    982:                         * Process output to stdout and stderr.  Output to
                    983:                         * the connection is processed elsewhere (above).
                    984:                         */
1.46      markus    985:                        client_process_output(writeset);
1.17      markus    986:                }
1.11      markus    987:
1.13      markus    988:                /* Send as much buffered packet data as possible to the sender. */
1.46      markus    989:                if (FD_ISSET(connection_out, writeset))
1.11      markus    990:                        packet_write_poll();
                    991:        }
1.46      markus    992:        if (readset)
                    993:                xfree(readset);
                    994:        if (writeset)
                    995:                xfree(writeset);
1.11      markus    996:
                    997:        /* Terminate the session. */
                    998:
                    999:        /* Stop watching for window change. */
                   1000:        if (have_pty)
                   1001:                signal(SIGWINCH, SIG_DFL);
                   1002:
1.76      markus   1003:        channel_free_all();
1.11      markus   1004:
1.75      markus   1005:        if (have_pty)
                   1006:                leave_raw_mode();
                   1007:
                   1008:        /* restore blocking io */
                   1009:        if (!isatty(fileno(stdin)))
                   1010:                unset_nonblock(fileno(stdin));
                   1011:        if (!isatty(fileno(stdout)))
                   1012:                unset_nonblock(fileno(stdout));
                   1013:        if (!isatty(fileno(stderr)))
                   1014:                unset_nonblock(fileno(stderr));
                   1015:
                   1016:        if (received_signal) {
                   1017:                if (in_non_blocking_mode)       /* XXX */
                   1018:                        leave_non_blocking();
1.89      itojun   1019:                fatal("Killed by signal %d.", (int) received_signal);
1.75      markus   1020:        }
                   1021:
1.13      markus   1022:        /*
                   1023:         * In interactive mode (with pseudo tty) display a message indicating
                   1024:         * that the connection has been closed.
                   1025:         */
1.11      markus   1026:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
                   1027:                snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
                   1028:                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1029:        }
1.70      markus   1030:
1.11      markus   1031:        /* Output any buffered data for stdout. */
1.70      markus   1032:        while (buffer_len(&stdout_buffer) > 0) {
                   1033:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1034:                    buffer_len(&stdout_buffer));
1.70      markus   1035:                if (len <= 0) {
1.11      markus   1036:                        error("Write failed flushing stdout buffer.");
1.70      markus   1037:                        break;
                   1038:                }
1.11      markus   1039:                buffer_consume(&stdout_buffer, len);
1.57      markus   1040:                stdout_bytes += len;
1.11      markus   1041:        }
                   1042:
                   1043:        /* Output any buffered data for stderr. */
1.70      markus   1044:        while (buffer_len(&stderr_buffer) > 0) {
                   1045:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1046:                    buffer_len(&stderr_buffer));
1.70      markus   1047:                if (len <= 0) {
1.11      markus   1048:                        error("Write failed flushing stderr buffer.");
1.70      markus   1049:                        break;
                   1050:                }
1.11      markus   1051:                buffer_consume(&stderr_buffer, len);
1.57      markus   1052:                stderr_bytes += len;
1.11      markus   1053:        }
                   1054:
                   1055:        /* Clear and free any buffers. */
                   1056:        memset(buf, 0, sizeof(buf));
                   1057:        buffer_free(&stdin_buffer);
                   1058:        buffer_free(&stdout_buffer);
                   1059:        buffer_free(&stderr_buffer);
                   1060:
                   1061:        /* Report bytes transferred, and transfer rates. */
                   1062:        total_time = get_current_time() - start_time;
                   1063:        debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
1.90      deraadt  1064:            stdin_bytes, stdout_bytes, stderr_bytes, total_time);
1.11      markus   1065:        if (total_time > 0)
                   1066:                debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
1.90      deraadt  1067:                    stdin_bytes / total_time, stdout_bytes / total_time,
                   1068:                    stderr_bytes / total_time);
1.11      markus   1069:
                   1070:        /* Return the exit status of the program. */
                   1071:        debug("Exit status %d", exit_status);
                   1072:        return exit_status;
1.15      markus   1073: }
                   1074:
                   1075: /*********/
                   1076:
1.77      itojun   1077: static void
1.94      markus   1078: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1079: {
1.42      markus   1080:        u_int data_len;
1.15      markus   1081:        char *data = packet_get_string(&data_len);
1.93      markus   1082:        packet_check_eom();
1.15      markus   1083:        buffer_append(&stdout_buffer, data, data_len);
                   1084:        memset(data, 0, data_len);
                   1085:        xfree(data);
                   1086: }
1.77      itojun   1087: static void
1.94      markus   1088: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1089: {
1.42      markus   1090:        u_int data_len;
1.15      markus   1091:        char *data = packet_get_string(&data_len);
1.93      markus   1092:        packet_check_eom();
1.15      markus   1093:        buffer_append(&stderr_buffer, data, data_len);
                   1094:        memset(data, 0, data_len);
                   1095:        xfree(data);
                   1096: }
1.77      itojun   1097: static void
1.94      markus   1098: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15      markus   1099: {
                   1100:        exit_status = packet_get_int();
1.93      markus   1101:        packet_check_eom();
1.15      markus   1102:        /* Acknowledge the exit. */
                   1103:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                   1104:        packet_send();
                   1105:        /*
                   1106:         * Must wait for packet to be sent since we are
                   1107:         * exiting the loop.
                   1108:         */
                   1109:        packet_write_wait();
                   1110:        /* Flag that we want to exit. */
                   1111:        quit_pending = 1;
                   1112: }
                   1113:
1.77      itojun   1114: static Channel *
1.40      markus   1115: client_request_forwarded_tcpip(const char *request_type, int rchan)
                   1116: {
                   1117:        Channel* c = NULL;
                   1118:        char *listen_address, *originator_address;
                   1119:        int listen_port, originator_port;
1.67      markus   1120:        int sock;
1.40      markus   1121:
                   1122:        /* Get rest of the packet */
                   1123:        listen_address = packet_get_string(NULL);
                   1124:        listen_port = packet_get_int();
                   1125:        originator_address = packet_get_string(NULL);
                   1126:        originator_port = packet_get_int();
1.93      markus   1127:        packet_check_eom();
1.40      markus   1128:
                   1129:        debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
                   1130:            listen_address, listen_port, originator_address, originator_port);
                   1131:
1.80      stevesk  1132:        sock = channel_connect_by_listen_address(listen_port);
1.67      markus   1133:        if (sock < 0) {
                   1134:                xfree(originator_address);
                   1135:                xfree(listen_address);
                   1136:                return NULL;
                   1137:        }
                   1138:        c = channel_new("forwarded-tcpip",
                   1139:            SSH_CHANNEL_CONNECTING, sock, sock, -1,
                   1140:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
                   1141:            xstrdup(originator_address), 1);
1.40      markus   1142:        xfree(originator_address);
                   1143:        xfree(listen_address);
                   1144:        return c;
                   1145: }
                   1146:
1.77      itojun   1147: static Channel*
1.40      markus   1148: client_request_x11(const char *request_type, int rchan)
                   1149: {
                   1150:        Channel *c = NULL;
                   1151:        char *originator;
                   1152:        int originator_port;
1.67      markus   1153:        int sock;
1.40      markus   1154:
                   1155:        if (!options.forward_x11) {
                   1156:                error("Warning: ssh server tried X11 forwarding.");
                   1157:                error("Warning: this is probably a break in attempt by a malicious server.");
                   1158:                return NULL;
                   1159:        }
                   1160:        originator = packet_get_string(NULL);
                   1161:        if (datafellows & SSH_BUG_X11FWD) {
                   1162:                debug2("buggy server: x11 request w/o originator_port");
                   1163:                originator_port = 0;
                   1164:        } else {
                   1165:                originator_port = packet_get_int();
                   1166:        }
1.93      markus   1167:        packet_check_eom();
1.40      markus   1168:        /* XXX check permission */
1.47      markus   1169:        debug("client_request_x11: request from %s %d", originator,
                   1170:            originator_port);
1.67      markus   1171:        xfree(originator);
1.40      markus   1172:        sock = x11_connect_display();
1.67      markus   1173:        if (sock < 0)
                   1174:                return NULL;
                   1175:        c = channel_new("x11",
                   1176:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
                   1177:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0,
                   1178:            xstrdup("x11"), 1);
1.82      markus   1179:        c->force_drain = 1;
1.40      markus   1180:        return c;
                   1181: }
                   1182:
1.77      itojun   1183: static Channel*
1.40      markus   1184: client_request_agent(const char *request_type, int rchan)
                   1185: {
                   1186:        Channel *c = NULL;
1.67      markus   1187:        int sock;
1.40      markus   1188:
                   1189:        if (!options.forward_agent) {
                   1190:                error("Warning: ssh server tried agent forwarding.");
                   1191:                error("Warning: this is probably a break in attempt by a malicious server.");
                   1192:                return NULL;
                   1193:        }
                   1194:        sock =  ssh_get_authentication_socket();
1.67      markus   1195:        if (sock < 0)
                   1196:                return NULL;
                   1197:        c = channel_new("authentication agent connection",
                   1198:            SSH_CHANNEL_OPEN, sock, sock, -1,
                   1199:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
                   1200:            xstrdup("authentication agent connection"), 1);
1.82      markus   1201:        c->force_drain = 1;
1.40      markus   1202:        return c;
                   1203: }
                   1204:
1.22      markus   1205: /* XXXX move to generic input handler */
1.77      itojun   1206: static void
1.94      markus   1207: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22      markus   1208: {
                   1209:        Channel *c = NULL;
                   1210:        char *ctype;
                   1211:        int rchan;
1.102   ! markus   1212:        u_int rmaxpack, rwindow, len;
1.22      markus   1213:
                   1214:        ctype = packet_get_string(&len);
                   1215:        rchan = packet_get_int();
                   1216:        rwindow = packet_get_int();
                   1217:        rmaxpack = packet_get_int();
                   1218:
1.24      markus   1219:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1220:            ctype, rchan, rwindow, rmaxpack);
                   1221:
1.40      markus   1222:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
                   1223:                c = client_request_forwarded_tcpip(ctype, rchan);
                   1224:        } else if (strcmp(ctype, "x11") == 0) {
                   1225:                c = client_request_x11(ctype, rchan);
                   1226:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
                   1227:                c = client_request_agent(ctype, rchan);
1.22      markus   1228:        }
                   1229: /* XXX duplicate : */
                   1230:        if (c != NULL) {
                   1231:                debug("confirm %s", ctype);
                   1232:                c->remote_id = rchan;
                   1233:                c->remote_window = rwindow;
                   1234:                c->remote_maxpacket = rmaxpack;
1.69      markus   1235:                if (c->type != SSH_CHANNEL_CONNECTING) {
                   1236:                        packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1237:                        packet_put_int(c->remote_id);
                   1238:                        packet_put_int(c->self);
                   1239:                        packet_put_int(c->local_window);
                   1240:                        packet_put_int(c->local_maxpacket);
                   1241:                        packet_send();
                   1242:                }
1.22      markus   1243:        } else {
                   1244:                debug("failure %s", ctype);
                   1245:                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1246:                packet_put_int(rchan);
                   1247:                packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66      markus   1248:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69      markus   1249:                        packet_put_cstring("open failed");
1.66      markus   1250:                        packet_put_cstring("");
                   1251:                }
1.22      markus   1252:                packet_send();
                   1253:        }
                   1254:        xfree(ctype);
                   1255: }
1.77      itojun   1256: static void
1.94      markus   1257: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48      markus   1258: {
                   1259:        Channel *c = NULL;
                   1260:        int id, reply, success = 0;
                   1261:        char *rtype;
                   1262:
                   1263:        id = packet_get_int();
                   1264:        rtype = packet_get_string(NULL);
                   1265:        reply = packet_get_char();
                   1266:
                   1267:        debug("client_input_channel_req: channel %d rtype %s reply %d",
                   1268:            id, rtype, reply);
                   1269:
                   1270:        if (session_ident == -1) {
                   1271:                error("client_input_channel_req: no channel %d", session_ident);
                   1272:        } else if (id != session_ident) {
                   1273:                error("client_input_channel_req: channel %d: wrong channel: %d",
                   1274:                    session_ident, id);
                   1275:        }
                   1276:        c = channel_lookup(id);
                   1277:        if (c == NULL) {
                   1278:                error("client_input_channel_req: channel %d: unknown channel", id);
                   1279:        } else if (strcmp(rtype, "exit-status") == 0) {
                   1280:                success = 1;
                   1281:                exit_status = packet_get_int();
1.93      markus   1282:                packet_check_eom();
1.48      markus   1283:        }
                   1284:        if (reply) {
                   1285:                packet_start(success ?
                   1286:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
                   1287:                packet_put_int(c->remote_id);
                   1288:                packet_send();
                   1289:        }
                   1290:        xfree(rtype);
                   1291: }
1.95      markus   1292: static void
                   1293: client_input_global_request(int type, u_int32_t seq, void *ctxt)
                   1294: {
                   1295:        char *rtype;
                   1296:        int want_reply;
                   1297:        int success = 0;
                   1298:
                   1299:        rtype = packet_get_string(NULL);
                   1300:        want_reply = packet_get_char();
                   1301:        debug("client_input_global_request: rtype %s want_reply %d", rtype, want_reply);
                   1302:        if (want_reply) {
                   1303:                packet_start(success ?
                   1304:                    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
                   1305:                packet_send();
                   1306:                packet_write_wait();
                   1307:        }
                   1308:        xfree(rtype);
                   1309: }
1.22      markus   1310:
1.77      itojun   1311: static void
1.49      itojun   1312: client_init_dispatch_20(void)
1.16      markus   1313: {
1.55      markus   1314:        dispatch_init(&dispatch_protocol_error);
1.100     markus   1315:
1.16      markus   1316:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   1317:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   1318:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   1319:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22      markus   1320:        dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16      markus   1321:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   1322:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48      markus   1323:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16      markus   1324:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.95      markus   1325:        dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   1326:
                   1327:        /* rekeying */
                   1328:        dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   1329:
                   1330:        /* global request reply messages */
                   1331:        dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   1332:        dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16      markus   1333: }
1.77      itojun   1334: static void
1.49      itojun   1335: client_init_dispatch_13(void)
1.15      markus   1336: {
                   1337:        dispatch_init(NULL);
                   1338:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                   1339:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                   1340:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                   1341:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   1342:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   1343:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                   1344:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                   1345:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                   1346:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39      markus   1347:
                   1348:        dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
                   1349:            &auth_input_open_request : &deny_input_open);
                   1350:        dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
                   1351:            &x11_input_open : &deny_input_open);
1.15      markus   1352: }
1.77      itojun   1353: static void
1.49      itojun   1354: client_init_dispatch_15(void)
1.15      markus   1355: {
                   1356:        client_init_dispatch_13();
                   1357:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                   1358:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                   1359: }
1.79      stevesk  1360: static void
1.49      itojun   1361: client_init_dispatch(void)
1.15      markus   1362: {
1.16      markus   1363:        if (compat20)
                   1364:                client_init_dispatch_20();
                   1365:        else if (compat13)
1.15      markus   1366:                client_init_dispatch_13();
                   1367:        else
                   1368:                client_init_dispatch_15();
1.1       deraadt  1369: }