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

1.193   ! markus      1: /* $OpenBSD: clientloop.c,v 1.192 2008/05/09 14:18:44 djm Exp $ */
1.1       deraadt     2: /*
1.12      deraadt     3:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      4:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      5:  *                    All rights reserved
1.33      deraadt     6:  * The main loop for the interactive session (client side).
1.20      markus      7:  *
1.33      deraadt     8:  * As far as I am concerned, the code I have written for this software
                      9:  * can be used freely for any purpose.  Any derived versions of this
                     10:  * software must be clearly marked as such, and if the derived work is
                     11:  * incompatible with the protocol description in the RFC file, it must be
                     12:  * called by a name other than "ssh" or "Secure Shell".
                     13:  *
                     14:  *
                     15:  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
                     16:  *
                     17:  * Redistribution and use in source and binary forms, with or without
                     18:  * modification, are permitted provided that the following conditions
                     19:  * are met:
                     20:  * 1. Redistributions of source code must retain the above copyright
                     21:  *    notice, this list of conditions and the following disclaimer.
                     22:  * 2. Redistributions in binary form must reproduce the above copyright
                     23:  *    notice, this list of conditions and the following disclaimer in the
                     24:  *    documentation and/or other materials provided with the distribution.
                     25:  *
                     26:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     27:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     28:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     29:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     30:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     31:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     32:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     33:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     34:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     35:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.20      markus     36:  *
                     37:  *
1.33      deraadt    38:  * SSH2 support added by Markus Friedl.
1.78      markus     39:  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
1.20      markus     40:  *
1.33      deraadt    41:  * Redistribution and use in source and binary forms, with or without
                     42:  * modification, are permitted provided that the following conditions
                     43:  * are met:
                     44:  * 1. Redistributions of source code must retain the above copyright
                     45:  *    notice, this list of conditions and the following disclaimer.
                     46:  * 2. Redistributions in binary form must reproduce the above copyright
                     47:  *    notice, this list of conditions and the following disclaimer in the
                     48:  *    documentation and/or other materials provided with the distribution.
                     49:  *
                     50:  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
                     51:  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
                     52:  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
                     53:  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
                     54:  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
                     55:  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
                     56:  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                     57:  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
                     58:  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
                     59:  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.12      deraadt    60:  */
1.1       deraadt    61:
1.152     stevesk    62:
1.175     deraadt    63: #include <sys/types.h>
1.152     stevesk    64: #include <sys/ioctl.h>
1.154     stevesk    65: #include <sys/stat.h>
1.166     stevesk    66: #include <sys/socket.h>
1.171     stevesk    67: #include <sys/time.h>
1.172     stevesk    68: #include <sys/param.h>
1.189     djm        69: #include <sys/queue.h>
1.150     stevesk    70:
1.155     stevesk    71: #include <ctype.h>
1.168     stevesk    72: #include <errno.h>
1.151     stevesk    73: #include <paths.h>
1.153     stevesk    74: #include <signal.h>
1.174     stevesk    75: #include <stdio.h>
1.173     stevesk    76: #include <stdlib.h>
1.170     stevesk    77: #include <string.h>
1.150     stevesk    78: #include <termios.h>
1.175     deraadt    79: #include <pwd.h>
1.169     stevesk    80: #include <unistd.h>
1.1       deraadt    81:
1.175     deraadt    82: #include "xmalloc.h"
1.45      markus     83: #include "ssh.h"
                     84: #include "ssh1.h"
                     85: #include "ssh2.h"
1.1       deraadt    86: #include "packet.h"
                     87: #include "buffer.h"
1.15      markus     88: #include "compat.h"
1.74      markus     89: #include "channels.h"
1.15      markus     90: #include "dispatch.h"
1.40      markus     91: #include "key.h"
1.175     deraadt    92: #include "cipher.h"
1.54      markus     93: #include "kex.h"
1.45      markus     94: #include "log.h"
                     95: #include "readconf.h"
                     96: #include "clientloop.h"
1.147     djm        97: #include "sshconnect.h"
1.40      markus     98: #include "authfd.h"
1.45      markus     99: #include "atomicio.h"
1.118     deraadt   100: #include "sshpty.h"
1.63      markus    101: #include "misc.h"
1.123     djm       102: #include "monitor_fdpass.h"
                    103: #include "match.h"
                    104: #include "msg.h"
1.39      markus    105:
                    106: /* import options */
                    107: extern Options options;
                    108:
1.1       deraadt   109: /* Flag indicating that stdin should be redirected from /dev/null. */
                    110: extern int stdin_null_flag;
                    111:
1.116     dtucker   112: /* Flag indicating that no shell has been requested */
                    113: extern int no_shell_flag;
                    114:
1.123     djm       115: /* Control socket */
1.192     djm       116: extern int muxserver_sock;
1.123     djm       117:
1.13      markus    118: /*
                    119:  * Name of the host we are connecting to.  This is the name given on the
                    120:  * command line, or the HostName specified for the user-supplied name in a
                    121:  * configuration file.
                    122:  */
1.1       deraadt   123: extern char *host;
                    124:
1.13      markus    125: /*
                    126:  * Flag to indicate that we have received a window change signal which has
                    127:  * not yet been processed.  This will cause a message indicating the new
                    128:  * window size to be sent to the server a little later.  This is volatile
                    129:  * because this is updated in a signal handler.
                    130:  */
1.88      markus    131: static volatile sig_atomic_t received_window_change_signal = 0;
                    132: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   133:
1.145     djm       134: /* Flag indicating whether the user's terminal is in non-blocking mode. */
1.1       deraadt   135: static int in_non_blocking_mode = 0;
                    136:
                    137: /* Common data for the client loop code. */
1.162     djm       138: static volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.31      markus    139: static int escape_char;                /* Escape character. */
1.11      markus    140: static int escape_pending;     /* Last character was the escape character */
                    141: static int last_was_cr;                /* Last character was a newline. */
                    142: static int exit_status;                /* Used to store the exit status of the command. */
                    143: static int stdin_eof;          /* EOF has been encountered on standard error. */
                    144: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                    145: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                    146: static Buffer stderr_buffer;   /* Buffer for stderr data. */
1.42      markus    147: static u_long stdin_bytes, stdout_bytes, stderr_bytes;
                    148: static u_int buffer_high;/* Soft max buffer size. */
1.11      markus    149: static int connection_in;      /* Connection to server (input). */
                    150: static int connection_out;     /* Connection to server (output). */
1.56      markus    151: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.60      markus    152: static int session_closed = 0; /* In SSH2: login session closed. */
1.1       deraadt   153:
1.77      itojun    154: static void client_init_dispatch(void);
1.16      markus    155: int    session_ident = -1;
                    156:
1.190     djm       157: struct channel_reply_ctx {
                    158:        const char *request_type;
                    159:        int id, do_close;
                    160: };
                    161:
1.54      markus    162: /*XXX*/
                    163: extern Kex *xxx_kex;
                    164:
1.123     djm       165: void ssh_process_session2_setup(int, int, int, Buffer *);
                    166:
1.1       deraadt   167: /* Restores stdin to blocking mode. */
                    168:
1.77      itojun    169: static void
1.49      itojun    170: leave_non_blocking(void)
1.1       deraadt   171: {
1.11      markus    172:        if (in_non_blocking_mode) {
1.125     djm       173:                unset_nonblock(fileno(stdin));
1.11      markus    174:                in_non_blocking_mode = 0;
                    175:        }
1.1       deraadt   176: }
                    177:
1.11      markus    178: /* Puts stdin terminal in non-blocking mode. */
                    179:
1.77      itojun    180: static void
1.49      itojun    181: enter_non_blocking(void)
1.1       deraadt   182: {
1.11      markus    183:        in_non_blocking_mode = 1;
1.124     djm       184:        set_nonblock(fileno(stdin));
1.1       deraadt   185: }
                    186:
1.13      markus    187: /*
                    188:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    189:  * flag indicating that the window has changed.
                    190:  */
1.157     deraadt   191: /*ARGSUSED */
1.77      itojun    192: static void
1.11      markus    193: window_change_handler(int sig)
1.1       deraadt   194: {
1.11      markus    195:        received_window_change_signal = 1;
                    196:        signal(SIGWINCH, window_change_handler);
1.1       deraadt   197: }
                    198:
1.13      markus    199: /*
                    200:  * Signal handler for signals that cause the program to terminate.  These
                    201:  * signals must be trapped to restore terminal modes.
                    202:  */
1.157     deraadt   203: /*ARGSUSED */
1.77      itojun    204: static void
1.11      markus    205: signal_handler(int sig)
1.1       deraadt   206: {
1.75      markus    207:        received_signal = sig;
                    208:        quit_pending = 1;
1.1       deraadt   209: }
                    210:
1.13      markus    211: /*
                    212:  * Returns current time in seconds from Jan 1, 1970 with the maximum
                    213:  * available resolution.
                    214:  */
1.1       deraadt   215:
1.77      itojun    216: static double
1.49      itojun    217: get_current_time(void)
1.1       deraadt   218: {
1.11      markus    219:        struct timeval tv;
                    220:        gettimeofday(&tv, NULL);
                    221:        return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
1.138     djm       222: }
                    223:
                    224: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
                    225: void
                    226: client_x11_get_proto(const char *display, const char *xauth_path,
                    227:     u_int trusted, char **_proto, char **_data)
                    228: {
                    229:        char cmd[1024];
                    230:        char line[512];
                    231:        char xdisplay[512];
                    232:        static char proto[512], data[512];
                    233:        FILE *f;
                    234:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    235:        char *xauthdir, *xauthfile;
                    236:        struct stat st;
                    237:
                    238:        xauthdir = xauthfile = NULL;
                    239:        *_proto = proto;
                    240:        *_data = data;
                    241:        proto[0] = data[0] = '\0';
                    242:
                    243:        if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
                    244:                debug("No xauth program.");
                    245:        } else {
                    246:                if (display == NULL) {
                    247:                        debug("x11_get_proto: DISPLAY not set");
                    248:                        return;
                    249:                }
                    250:                /*
                    251:                 * Handle FamilyLocal case where $DISPLAY does
                    252:                 * not match an authorization entry.  For this we
                    253:                 * just try "xauth list unix:displaynum.screennum".
                    254:                 * XXX: "localhost" match to determine FamilyLocal
                    255:                 *      is not perfect.
                    256:                 */
                    257:                if (strncmp(display, "localhost:", 10) == 0) {
                    258:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    259:                            display + 10);
                    260:                        display = xdisplay;
                    261:                }
                    262:                if (trusted == 0) {
                    263:                        xauthdir = xmalloc(MAXPATHLEN);
                    264:                        xauthfile = xmalloc(MAXPATHLEN);
                    265:                        strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
                    266:                        if (mkdtemp(xauthdir) != NULL) {
                    267:                                do_unlink = 1;
                    268:                                snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
                    269:                                    xauthdir);
                    270:                                snprintf(cmd, sizeof(cmd),
                    271:                                    "%s -f %s generate %s " SSH_X11_PROTO
                    272:                                    " untrusted timeout 1200 2>" _PATH_DEVNULL,
                    273:                                    xauth_path, xauthfile, display);
                    274:                                debug2("x11_get_proto: %s", cmd);
                    275:                                if (system(cmd) == 0)
                    276:                                        generated = 1;
                    277:                        }
                    278:                }
1.181     markus    279:
                    280:                /*
                    281:                 * When in untrusted mode, we read the cookie only if it was
                    282:                 * successfully generated as an untrusted one in the step
                    283:                 * above.
                    284:                 */
                    285:                if (trusted || generated) {
                    286:                        snprintf(cmd, sizeof(cmd),
                    287:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    288:                            xauth_path,
                    289:                            generated ? "-f " : "" ,
                    290:                            generated ? xauthfile : "",
                    291:                            display);
                    292:                        debug2("x11_get_proto: %s", cmd);
                    293:                        f = popen(cmd, "r");
                    294:                        if (f && fgets(line, sizeof(line), f) &&
                    295:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    296:                                got_data = 1;
                    297:                        if (f)
                    298:                                pclose(f);
                    299:                } else
                    300:                        error("Warning: untrusted X11 forwarding setup failed: "
                    301:                            "xauth key data not generated");
1.138     djm       302:        }
                    303:
                    304:        if (do_unlink) {
                    305:                unlink(xauthfile);
                    306:                rmdir(xauthdir);
                    307:        }
                    308:        if (xauthdir)
                    309:                xfree(xauthdir);
                    310:        if (xauthfile)
                    311:                xfree(xauthfile);
                    312:
                    313:        /*
                    314:         * If we didn't get authentication data, just make up some
                    315:         * data.  The forwarding code will check the validity of the
                    316:         * response anyway, and substitute this data.  The X11
                    317:         * server, however, will ignore this fake data and use
                    318:         * whatever authentication mechanisms it was using otherwise
                    319:         * for the local connection.
                    320:         */
                    321:        if (!got_data) {
                    322:                u_int32_t rnd = 0;
                    323:
                    324:                logit("Warning: No xauth data; "
                    325:                    "using fake authentication data for X11 forwarding.");
                    326:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
                    327:                for (i = 0; i < 16; i++) {
                    328:                        if (i % 4 == 0)
                    329:                                rnd = arc4random();
                    330:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
                    331:                            rnd & 0xff);
                    332:                        rnd >>= 8;
                    333:                }
                    334:        }
1.1       deraadt   335: }
                    336:
1.13      markus    337: /*
                    338:  * This is called when the interactive is entered.  This checks if there is
                    339:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    340:  * not appear to wake up when redirecting from /dev/null.
                    341:  */
1.1       deraadt   342:
1.77      itojun    343: static void
1.49      itojun    344: client_check_initial_eof_on_stdin(void)
1.1       deraadt   345: {
1.11      markus    346:        int len;
                    347:        char buf[1];
1.1       deraadt   348:
1.13      markus    349:        /*
                    350:         * If standard input is to be "redirected from /dev/null", we simply
                    351:         * mark that we have seen an EOF and send an EOF message to the
                    352:         * server. Otherwise, we try to read a single character; it appears
                    353:         * that for some files, such /dev/null, select() never wakes up for
                    354:         * read for this descriptor, which means that we never get EOF.  This
                    355:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    356:         */
1.11      markus    357:        if (stdin_null_flag) {
                    358:                /* Fake EOF on stdin. */
                    359:                debug("Sending eof.");
                    360:                stdin_eof = 1;
                    361:                packet_start(SSH_CMSG_EOF);
                    362:                packet_send();
                    363:        } else {
                    364:                enter_non_blocking();
                    365:
                    366:                /* Check for immediate EOF on stdin. */
                    367:                len = read(fileno(stdin), buf, 1);
                    368:                if (len == 0) {
1.13      markus    369:                        /* EOF.  Record that we have seen it and send EOF to server. */
1.11      markus    370:                        debug("Sending eof.");
                    371:                        stdin_eof = 1;
                    372:                        packet_start(SSH_CMSG_EOF);
                    373:                        packet_send();
                    374:                } else if (len > 0) {
1.13      markus    375:                        /*
                    376:                         * Got data.  We must store the data in the buffer,
                    377:                         * and also process it as an escape character if
                    378:                         * appropriate.
                    379:                         */
1.42      markus    380:                        if ((u_char) buf[0] == escape_char)
1.11      markus    381:                                escape_pending = 1;
1.52      markus    382:                        else
1.11      markus    383:                                buffer_append(&stdin_buffer, buf, 1);
                    384:                }
                    385:                leave_non_blocking();
                    386:        }
1.1       deraadt   387: }
                    388:
                    389:
1.13      markus    390: /*
                    391:  * Make packets from buffered stdin data, and buffer them for sending to the
                    392:  * connection.
                    393:  */
1.1       deraadt   394:
1.77      itojun    395: static void
1.49      itojun    396: client_make_packets_from_stdin_data(void)
1.1       deraadt   397: {
1.42      markus    398:        u_int len;
1.1       deraadt   399:
1.11      markus    400:        /* Send buffered stdin data to the server. */
                    401:        while (buffer_len(&stdin_buffer) > 0 &&
1.90      deraadt   402:            packet_not_very_much_data_to_write()) {
1.11      markus    403:                len = buffer_len(&stdin_buffer);
                    404:                /* Keep the packets at reasonable size. */
                    405:                if (len > packet_get_maxsize())
                    406:                        len = packet_get_maxsize();
                    407:                packet_start(SSH_CMSG_STDIN_DATA);
                    408:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    409:                packet_send();
                    410:                buffer_consume(&stdin_buffer, len);
1.52      markus    411:                stdin_bytes += len;
1.11      markus    412:                /* If we have a pending EOF, send it now. */
                    413:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    414:                        packet_start(SSH_CMSG_EOF);
                    415:                        packet_send();
                    416:                }
1.1       deraadt   417:        }
                    418: }
                    419:
1.13      markus    420: /*
                    421:  * Checks if the client window has changed, and sends a packet about it to
                    422:  * the server if so.  The actual change is detected elsewhere (by a software
                    423:  * interrupt on Unix); this just checks the flag and sends a message if
                    424:  * appropriate.
                    425:  */
1.1       deraadt   426:
1.77      itojun    427: static void
1.49      itojun    428: client_check_window_change(void)
1.1       deraadt   429: {
1.16      markus    430:        struct winsize ws;
                    431:
                    432:        if (! received_window_change_signal)
                    433:                return;
                    434:        /** XXX race */
                    435:        received_window_change_signal = 0;
                    436:
1.37      markus    437:        debug2("client_check_window_change: changed");
1.16      markus    438:
                    439:        if (compat20) {
1.123     djm       440:                channel_send_window_changes();
1.16      markus    441:        } else {
1.123     djm       442:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    443:                        return;
1.16      markus    444:                packet_start(SSH_CMSG_WINDOW_SIZE);
1.158     deraadt   445:                packet_put_int((u_int)ws.ws_row);
                    446:                packet_put_int((u_int)ws.ws_col);
                    447:                packet_put_int((u_int)ws.ws_xpixel);
                    448:                packet_put_int((u_int)ws.ws_ypixel);
1.16      markus    449:                packet_send();
1.1       deraadt   450:        }
                    451: }
                    452:
1.117     markus    453: static void
                    454: client_global_request_reply(int type, u_int32_t seq, void *ctxt)
                    455: {
1.188     dtucker   456:        keep_alive_timeouts = 0;
1.117     markus    457:        client_global_request_reply_fwd(type, seq, ctxt);
                    458: }
                    459:
                    460: static void
                    461: server_alive_check(void)
                    462: {
1.188     dtucker   463:        if (++keep_alive_timeouts > options.server_alive_count_max) {
1.176     markus    464:                logit("Timeout, server not responding.");
                    465:                cleanup_exit(255);
                    466:        }
1.117     markus    467:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                    468:        packet_put_cstring("keepalive@openssh.com");
                    469:        packet_put_char(1);     /* boolean: want reply */
                    470:        packet_send();
                    471: }
                    472:
1.13      markus    473: /*
                    474:  * Waits until the client can do something (some data becomes available on
                    475:  * one of the file descriptors).
                    476:  */
1.77      itojun    477: static void
1.46      markus    478: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.130     avsm      479:     int *maxfdp, u_int *nallocp, int rekeying)
1.11      markus    480: {
1.117     markus    481:        struct timeval tv, *tvp;
                    482:        int ret;
                    483:
1.46      markus    484:        /* Add any selections by the channel mechanism. */
1.81      markus    485:        channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
1.11      markus    486:
1.16      markus    487:        if (!compat20) {
1.17      markus    488:                /* Read from the connection, unless our buffers are full. */
1.16      markus    489:                if (buffer_len(&stdout_buffer) < buffer_high &&
                    490:                    buffer_len(&stderr_buffer) < buffer_high &&
                    491:                    channel_not_very_much_buffered_data())
1.46      markus    492:                        FD_SET(connection_in, *readsetp);
1.17      markus    493:                /*
                    494:                 * Read from stdin, unless we have seen EOF or have very much
                    495:                 * buffered data to send to the server.
                    496:                 */
                    497:                if (!stdin_eof && packet_not_very_much_data_to_write())
1.46      markus    498:                        FD_SET(fileno(stdin), *readsetp);
1.17      markus    499:
                    500:                /* Select stdout/stderr if have data in buffer. */
                    501:                if (buffer_len(&stdout_buffer) > 0)
1.46      markus    502:                        FD_SET(fileno(stdout), *writesetp);
1.17      markus    503:                if (buffer_len(&stderr_buffer) > 0)
1.46      markus    504:                        FD_SET(fileno(stderr), *writesetp);
1.16      markus    505:        } else {
1.71      markus    506:                /* channel_prepare_select could have closed the last channel */
1.84      markus    507:                if (session_closed && !channel_still_open() &&
                    508:                    !packet_have_data_to_write()) {
                    509:                        /* clear mask since we did not call select() */
1.87      markus    510:                        memset(*readsetp, 0, *nallocp);
                    511:                        memset(*writesetp, 0, *nallocp);
1.84      markus    512:                        return;
1.71      markus    513:                } else {
                    514:                        FD_SET(connection_in, *readsetp);
                    515:                }
1.16      markus    516:        }
1.11      markus    517:
                    518:        /* Select server connection if have data to write to the server. */
                    519:        if (packet_have_data_to_write())
1.46      markus    520:                FD_SET(connection_out, *writesetp);
1.11      markus    521:
1.192     djm       522:        if (muxserver_sock != -1)
                    523:                FD_SET(muxserver_sock, *readsetp);
1.123     djm       524:
1.13      markus    525:        /*
                    526:         * Wait for something to happen.  This will suspend the process until
                    527:         * some selected descriptor can be read, written, or has some other
1.117     markus    528:         * event pending.
1.13      markus    529:         */
1.11      markus    530:
1.117     markus    531:        if (options.server_alive_interval == 0 || !compat20)
                    532:                tvp = NULL;
1.129     deraadt   533:        else {
1.117     markus    534:                tv.tv_sec = options.server_alive_interval;
                    535:                tv.tv_usec = 0;
                    536:                tvp = &tv;
                    537:        }
                    538:        ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
                    539:        if (ret < 0) {
1.11      markus    540:                char buf[100];
1.51      markus    541:
                    542:                /*
                    543:                 * We have to clear the select masks, because we return.
                    544:                 * We have to return, because the mainloop checks for the flags
                    545:                 * set by the signal handlers.
                    546:                 */
1.87      markus    547:                memset(*readsetp, 0, *nallocp);
                    548:                memset(*writesetp, 0, *nallocp);
1.50      deraadt   549:
1.11      markus    550:                if (errno == EINTR)
                    551:                        return;
                    552:                /* Note: we might still have data in the buffers. */
                    553:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    554:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    555:                quit_pending = 1;
1.117     markus    556:        } else if (ret == 0)
                    557:                server_alive_check();
1.11      markus    558: }
                    559:
1.77      itojun    560: static void
1.31      markus    561: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1       deraadt   562: {
1.11      markus    563:        /* Flush stdout and stderr buffers. */
1.31      markus    564:        if (buffer_len(bout) > 0)
1.112     deraadt   565:                atomicio(vwrite, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
1.31      markus    566:        if (buffer_len(berr) > 0)
1.112     deraadt   567:                atomicio(vwrite, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
1.11      markus    568:
                    569:        leave_raw_mode();
                    570:
1.13      markus    571:        /*
                    572:         * Free (and clear) the buffer to reduce the amount of data that gets
                    573:         * written to swap.
                    574:         */
1.31      markus    575:        buffer_free(bin);
                    576:        buffer_free(bout);
                    577:        buffer_free(berr);
1.11      markus    578:
                    579:        /* Send the suspend signal to the program itself. */
                    580:        kill(getpid(), SIGTSTP);
                    581:
1.132     djm       582:        /* Reset window sizes in case they have changed */
                    583:        received_window_change_signal = 1;
1.11      markus    584:
                    585:        /* OK, we have been continued by the user. Reinitialize buffers. */
1.31      markus    586:        buffer_init(bin);
                    587:        buffer_init(bout);
                    588:        buffer_init(berr);
1.11      markus    589:
                    590:        enter_raw_mode();
                    591: }
                    592:
1.77      itojun    593: static void
1.161     deraadt   594: client_process_net_input(fd_set *readset)
1.11      markus    595: {
1.17      markus    596:        int len;
                    597:        char buf[8192];
1.11      markus    598:
1.13      markus    599:        /*
                    600:         * Read input from the server, and add any such data to the buffer of
                    601:         * the packet subsystem.
                    602:         */
1.11      markus    603:        if (FD_ISSET(connection_in, readset)) {
                    604:                /* Read as much as possible. */
                    605:                len = read(connection_in, buf, sizeof(buf));
                    606:                if (len == 0) {
                    607:                        /* Received EOF.  The remote host has closed the connection. */
                    608:                        snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
                    609:                                 host);
1.1       deraadt   610:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    611:                        quit_pending = 1;
                    612:                        return;
1.11      markus    613:                }
1.13      markus    614:                /*
                    615:                 * There is a kernel bug on Solaris that causes select to
                    616:                 * sometimes wake up even though there is no data available.
                    617:                 */
1.53      millert   618:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11      markus    619:                        len = 0;
                    620:
                    621:                if (len < 0) {
                    622:                        /* An error has encountered.  Perhaps there is a network problem. */
                    623:                        snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
                    624:                                 host, strerror(errno));
                    625:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    626:                        quit_pending = 1;
                    627:                        return;
                    628:                }
                    629:                packet_process_incoming(buf, len);
                    630:        }
1.17      markus    631: }
1.16      markus    632:
1.97      jakob     633: static void
1.190     djm       634: client_status_confirm(int type, Channel *c, void *ctx)
1.123     djm       635: {
1.190     djm       636:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    637:        char errmsg[256];
                    638:        int tochan;
                    639:
                    640:        /* XXX supress on mux _client_ quietmode */
                    641:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
                    642:            c->ctl_fd != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
                    643:
                    644:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    645:                debug2("%s request accepted on channel %d",
                    646:                    cr->request_type, c->self);
                    647:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    648:                if (tochan) {
                    649:                        snprintf(errmsg, sizeof(errmsg),
                    650:                            "%s request failed\r\n", cr->request_type);
                    651:                } else {
                    652:                        snprintf(errmsg, sizeof(errmsg),
                    653:                            "%s request failed on channel %d",
                    654:                            cr->request_type, c->self);
                    655:                }
                    656:                /* If error occurred on primary session channel, then exit */
                    657:                if (cr->do_close && c->self == session_ident)
                    658:                        fatal("%s", errmsg);
                    659:                /* If error occurred on mux client, append to their stderr */
                    660:                if (tochan)
                    661:                        buffer_append(&c->extended, errmsg, strlen(errmsg));
                    662:                else
                    663:                        error("%s", errmsg);
                    664:                if (cr->do_close) {
                    665:                        chan_read_failed(c);
                    666:                        chan_write_failed(c);
                    667:                }
                    668:        }
                    669:        xfree(cr);
                    670: }
                    671:
                    672: static void
                    673: client_abandon_status_confirm(Channel *c, void *ctx)
                    674: {
                    675:        xfree(ctx);
                    676: }
1.129     deraadt   677:
1.190     djm       678: static void
                    679: client_expect_confirm(int id, const char *request, int do_close)
                    680: {
                    681:        struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
1.123     djm       682:
1.190     djm       683:        cr->request_type = request;
                    684:        cr->do_close = do_close;
1.123     djm       685:
1.190     djm       686:        channel_register_status_confirm(id, client_status_confirm,
                    687:            client_abandon_status_confirm, cr);
1.123     djm       688: }
                    689:
                    690: static void
1.99      markus    691: process_cmdline(void)
1.97      jakob     692: {
                    693:        void (*handler)(int);
1.135     djm       694:        char *s, *cmd, *cancel_host;
1.121     djm       695:        int delete = 0;
1.97      jakob     696:        int local = 0;
1.135     djm       697:        u_short cancel_port;
                    698:        Forward fwd;
1.97      jakob     699:
1.183     djm       700:        bzero(&fwd, sizeof(fwd));
                    701:        fwd.listen_host = fwd.connect_host = NULL;
                    702:
1.97      jakob     703:        leave_raw_mode();
1.101     markus    704:        handler = signal(SIGINT, SIG_IGN);
1.99      markus    705:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     706:        if (s == NULL)
                    707:                goto out;
1.179     tedu      708:        while (isspace(*s))
1.97      jakob     709:                s++;
1.121     djm       710:        if (*s == '-')
                    711:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   712:        if (*s == '\0')
1.97      jakob     713:                goto out;
1.121     djm       714:
1.122     djm       715:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       716:                logit("Commands:");
1.164     djm       717:                logit("      -L[bind_address:]port:host:hostport    "
                    718:                    "Request local forward");
                    719:                logit("      -R[bind_address:]port:host:hostport    "
                    720:                    "Request remote forward");
1.165     stevesk   721:                logit("      -KR[bind_address:]port                 "
1.164     djm       722:                    "Cancel remote forward");
1.146     reyk      723:                if (!options.permit_local_command)
                    724:                        goto out;
1.164     djm       725:                logit("      !args                                  "
                    726:                    "Execute local command");
1.146     reyk      727:                goto out;
                    728:        }
                    729:
                    730:        if (*s == '!' && options.permit_local_command) {
                    731:                s++;
                    732:                ssh_local_cmd(s);
1.121     djm       733:                goto out;
                    734:        }
                    735:
                    736:        if (*s == 'K') {
                    737:                delete = 1;
                    738:                s++;
                    739:        }
                    740:        if (*s != 'L' && *s != 'R') {
1.109     itojun    741:                logit("Invalid command.");
1.97      jakob     742:                goto out;
                    743:        }
1.121     djm       744:        if (*s == 'L')
1.97      jakob     745:                local = 1;
1.121     djm       746:        if (local && delete) {
                    747:                logit("Not supported.");
                    748:                goto out;
                    749:        }
                    750:        if ((!local || delete) && !compat20) {
1.109     itojun    751:                logit("Not supported for SSH protocol version 1.");
1.97      jakob     752:                goto out;
                    753:        }
1.121     djm       754:
1.179     tedu      755:        while (isspace(*++s))
                    756:                ;
1.97      jakob     757:
1.121     djm       758:        if (delete) {
1.135     djm       759:                cancel_port = 0;
                    760:                cancel_host = hpdelim(&s);      /* may be NULL */
                    761:                if (s != NULL) {
                    762:                        cancel_port = a2port(s);
                    763:                        cancel_host = cleanhostname(cancel_host);
                    764:                } else {
                    765:                        cancel_port = a2port(cancel_host);
                    766:                        cancel_host = NULL;
1.121     djm       767:                }
1.135     djm       768:                if (cancel_port == 0) {
                    769:                        logit("Bad forwarding close port");
1.121     djm       770:                        goto out;
                    771:                }
1.135     djm       772:                channel_request_rforward_cancel(cancel_host, cancel_port);
1.121     djm       773:        } else {
1.135     djm       774:                if (!parse_forward(&fwd, s)) {
1.121     djm       775:                        logit("Bad forwarding specification.");
                    776:                        goto out;
                    777:                }
                    778:                if (local) {
1.135     djm       779:                        if (channel_setup_local_fwd_listener(fwd.listen_host,
                    780:                            fwd.listen_port, fwd.connect_host,
                    781:                            fwd.connect_port, options.gateway_ports) < 0) {
1.121     djm       782:                                logit("Port forwarding failed.");
                    783:                                goto out;
                    784:                        }
1.135     djm       785:                } else {
1.167     markus    786:                        if (channel_request_remote_forwarding(fwd.listen_host,
1.135     djm       787:                            fwd.listen_port, fwd.connect_host,
1.167     markus    788:                            fwd.connect_port) < 0) {
                    789:                                logit("Port forwarding failed.");
                    790:                                goto out;
                    791:                        }
1.135     djm       792:                }
                    793:
1.121     djm       794:                logit("Forwarding port.");
                    795:        }
                    796:
1.97      jakob     797: out:
                    798:        signal(SIGINT, handler);
                    799:        enter_raw_mode();
                    800:        if (cmd)
                    801:                xfree(cmd);
1.183     djm       802:        if (fwd.listen_host != NULL)
                    803:                xfree(fwd.listen_host);
                    804:        if (fwd.connect_host != NULL)
                    805:                xfree(fwd.connect_host);
1.97      jakob     806: }
                    807:
1.31      markus    808: /* process the characters one by one */
1.77      itojun    809: static int
1.31      markus    810: process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
                    811: {
1.32      markus    812:        char string[1024];
1.31      markus    813:        pid_t pid;
                    814:        int bytes = 0;
1.42      markus    815:        u_int i;
                    816:        u_char ch;
1.31      markus    817:        char *s;
                    818:
1.139     djm       819:        if (len <= 0)
                    820:                return (0);
                    821:
                    822:        for (i = 0; i < (u_int)len; i++) {
1.31      markus    823:                /* Get one character at a time. */
                    824:                ch = buf[i];
                    825:
                    826:                if (escape_pending) {
                    827:                        /* We have previously seen an escape character. */
                    828:                        /* Clear the flag now. */
                    829:                        escape_pending = 0;
                    830:
                    831:                        /* Process the escaped character. */
                    832:                        switch (ch) {
                    833:                        case '.':
                    834:                                /* Terminate the connection. */
1.32      markus    835:                                snprintf(string, sizeof string, "%c.\r\n", escape_char);
                    836:                                buffer_append(berr, string, strlen(string));
1.31      markus    837:
                    838:                                quit_pending = 1;
                    839:                                return -1;
                    840:
                    841:                        case 'Z' - 64:
                    842:                                /* Suspend the program. */
                    843:                                /* Print a message to that effect to the user. */
1.32      markus    844:                                snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
                    845:                                buffer_append(berr, string, strlen(string));
1.31      markus    846:
                    847:                                /* Restore terminal modes and suspend. */
                    848:                                client_suspend_self(bin, bout, berr);
                    849:
                    850:                                /* We have been continued. */
                    851:                                continue;
                    852:
1.111     markus    853:                        case 'B':
                    854:                                if (compat20) {
                    855:                                        snprintf(string, sizeof string,
                    856:                                            "%cB\r\n", escape_char);
                    857:                                        buffer_append(berr, string,
                    858:                                            strlen(string));
                    859:                                        channel_request_start(session_ident,
                    860:                                            "break", 0);
                    861:                                        packet_put_int(1000);
                    862:                                        packet_send();
                    863:                                }
                    864:                                continue;
                    865:
1.54      markus    866:                        case 'R':
1.59      markus    867:                                if (compat20) {
                    868:                                        if (datafellows & SSH_BUG_NOREKEY)
1.109     itojun    869:                                                logit("Server does not support re-keying");
1.59      markus    870:                                        else
                    871:                                                need_rekeying = 1;
                    872:                                }
1.54      markus    873:                                continue;
                    874:
1.31      markus    875:                        case '&':
                    876:                                /*
                    877:                                 * Detach the program (continue to serve connections,
                    878:                                 * but put in background and no more new connections).
                    879:                                 */
                    880:                                /* Restore tty modes. */
                    881:                                leave_raw_mode();
                    882:
                    883:                                /* Stop listening for new connections. */
1.86      markus    884:                                channel_stop_listening();
1.31      markus    885:
1.86      markus    886:                                snprintf(string, sizeof string,
                    887:                                    "%c& [backgrounded]\n", escape_char);
                    888:                                buffer_append(berr, string, strlen(string));
1.31      markus    889:
                    890:                                /* Fork into background. */
                    891:                                pid = fork();
                    892:                                if (pid < 0) {
                    893:                                        error("fork: %.100s", strerror(errno));
                    894:                                        continue;
                    895:                                }
                    896:                                if (pid != 0) { /* This is the parent. */
                    897:                                        /* The parent just exits. */
                    898:                                        exit(0);
                    899:                                }
                    900:                                /* The child continues serving connections. */
1.86      markus    901:                                if (compat20) {
                    902:                                        buffer_append(bin, "\004", 1);
                    903:                                        /* fake EOF on stdin */
                    904:                                        return -1;
                    905:                                } else if (!stdin_eof) {
                    906:                                        /*
                    907:                                         * Sending SSH_CMSG_EOF alone does not always appear
                    908:                                         * to be enough.  So we try to send an EOF character
                    909:                                         * first.
                    910:                                         */
                    911:                                        packet_start(SSH_CMSG_STDIN_DATA);
                    912:                                        packet_put_string("\004", 1);
                    913:                                        packet_send();
                    914:                                        /* Close stdin. */
                    915:                                        stdin_eof = 1;
                    916:                                        if (buffer_len(bin) == 0) {
                    917:                                                packet_start(SSH_CMSG_EOF);
                    918:                                                packet_send();
                    919:                                        }
                    920:                                }
                    921:                                continue;
1.31      markus    922:
                    923:                        case '?':
1.32      markus    924:                                snprintf(string, sizeof string,
1.31      markus    925: "%c?\r\n\
                    926: Supported escape sequences:\r\n\
1.104     stevesk   927: %c.  - terminate connection\r\n\
1.111     markus    928: %cB  - send a BREAK to the remote system\r\n\
1.104     stevesk   929: %cC  - open a command line\r\n\
                    930: %cR  - Request rekey (SSH protocol 2 only)\r\n\
                    931: %c^Z - suspend ssh\r\n\
                    932: %c#  - list forwarded connections\r\n\
                    933: %c&  - background ssh (when waiting for connections to terminate)\r\n\
                    934: %c?  - this message\r\n\
                    935: %c%c  - send the escape character by typing it twice\r\n\
1.31      markus    936: (Note that escapes are only recognized immediately after newline.)\r\n",
1.104     stevesk   937:                                    escape_char, escape_char, escape_char, escape_char,
                    938:                                    escape_char, escape_char, escape_char, escape_char,
1.111     markus    939:                                    escape_char, escape_char, escape_char);
1.32      markus    940:                                buffer_append(berr, string, strlen(string));
1.31      markus    941:                                continue;
                    942:
                    943:                        case '#':
1.32      markus    944:                                snprintf(string, sizeof string, "%c#\r\n", escape_char);
                    945:                                buffer_append(berr, string, strlen(string));
1.31      markus    946:                                s = channel_open_message();
                    947:                                buffer_append(berr, s, strlen(s));
                    948:                                xfree(s);
1.97      jakob     949:                                continue;
                    950:
                    951:                        case 'C':
1.99      markus    952:                                process_cmdline();
1.31      markus    953:                                continue;
                    954:
                    955:                        default:
                    956:                                if (ch != escape_char) {
                    957:                                        buffer_put_char(bin, escape_char);
                    958:                                        bytes++;
                    959:                                }
                    960:                                /* Escaped characters fall through here */
                    961:                                break;
                    962:                        }
                    963:                } else {
                    964:                        /*
                    965:                         * The previous character was not an escape char. Check if this
                    966:                         * is an escape.
                    967:                         */
                    968:                        if (last_was_cr && ch == escape_char) {
                    969:                                /* It is. Set the flag and continue to next character. */
                    970:                                escape_pending = 1;
                    971:                                continue;
                    972:                        }
                    973:                }
                    974:
                    975:                /*
                    976:                 * Normal character.  Record whether it was a newline,
                    977:                 * and append it to the buffer.
                    978:                 */
                    979:                last_was_cr = (ch == '\r' || ch == '\n');
                    980:                buffer_put_char(bin, ch);
                    981:                bytes++;
                    982:        }
                    983:        return bytes;
                    984: }
                    985:
1.77      itojun    986: static void
1.161     deraadt   987: client_process_input(fd_set *readset)
1.17      markus    988: {
1.21      deraadt   989:        int len;
1.31      markus    990:        char buf[8192];
1.16      markus    991:
1.11      markus    992:        /* Read input from stdin. */
                    993:        if (FD_ISSET(fileno(stdin), readset)) {
                    994:                /* Read as much as possible. */
                    995:                len = read(fileno(stdin), buf, sizeof(buf));
1.64      markus    996:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
                    997:                        return;         /* we'll try again later */
1.11      markus    998:                if (len <= 0) {
1.13      markus    999:                        /*
                   1000:                         * Received EOF or error.  They are treated
                   1001:                         * similarly, except that an error message is printed
                   1002:                         * if it was an error condition.
                   1003:                         */
1.11      markus   1004:                        if (len < 0) {
                   1005:                                snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
                   1006:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1007:                        }
                   1008:                        /* Mark that we have seen EOF. */
                   1009:                        stdin_eof = 1;
1.13      markus   1010:                        /*
                   1011:                         * Send an EOF message to the server unless there is
                   1012:                         * data in the buffer.  If there is data in the
                   1013:                         * buffer, no message will be sent now.  Code
                   1014:                         * elsewhere will send the EOF when the buffer
                   1015:                         * becomes empty if stdin_eof is set.
                   1016:                         */
1.11      markus   1017:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt  1018:                                packet_start(SSH_CMSG_EOF);
                   1019:                                packet_send();
1.11      markus   1020:                        }
1.72      stevesk  1021:                } else if (escape_char == SSH_ESCAPECHAR_NONE) {
1.13      markus   1022:                        /*
                   1023:                         * Normal successful read, and no escape character.
                   1024:                         * Just append the data to buffer.
                   1025:                         */
1.11      markus   1026:                        buffer_append(&stdin_buffer, buf, len);
                   1027:                } else {
1.13      markus   1028:                        /*
                   1029:                         * Normal, successful read.  But we have an escape character
                   1030:                         * and have to process the characters one by one.
                   1031:                         */
1.52      markus   1032:                        if (process_escapes(&stdin_buffer, &stdout_buffer,
                   1033:                            &stderr_buffer, buf, len) == -1)
1.31      markus   1034:                                return;
1.11      markus   1035:                }
                   1036:        }
                   1037: }
                   1038:
1.77      itojun   1039: static void
1.161     deraadt  1040: client_process_output(fd_set *writeset)
1.11      markus   1041: {
                   1042:        int len;
                   1043:        char buf[100];
1.1       deraadt  1044:
1.11      markus   1045:        /* Write buffered output to stdout. */
                   1046:        if (FD_ISSET(fileno(stdout), writeset)) {
                   1047:                /* Write as much data as possible. */
                   1048:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1049:                    buffer_len(&stdout_buffer));
1.11      markus   1050:                if (len <= 0) {
1.64      markus   1051:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1052:                                len = 0;
                   1053:                        else {
1.13      markus   1054:                                /*
                   1055:                                 * An error or EOF was encountered.  Put an
                   1056:                                 * error message to stderr buffer.
                   1057:                                 */
1.11      markus   1058:                                snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
                   1059:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1060:                                quit_pending = 1;
                   1061:                                return;
                   1062:                        }
                   1063:                }
                   1064:                /* Consume printed data from the buffer. */
                   1065:                buffer_consume(&stdout_buffer, len);
1.57      markus   1066:                stdout_bytes += len;
1.11      markus   1067:        }
                   1068:        /* Write buffered output to stderr. */
                   1069:        if (FD_ISSET(fileno(stderr), writeset)) {
                   1070:                /* Write as much data as possible. */
                   1071:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1072:                    buffer_len(&stderr_buffer));
1.11      markus   1073:                if (len <= 0) {
1.64      markus   1074:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1075:                                len = 0;
                   1076:                        else {
1.13      markus   1077:                                /* EOF or error, but can't even print error message. */
1.11      markus   1078:                                quit_pending = 1;
                   1079:                                return;
                   1080:                        }
                   1081:                }
                   1082:                /* Consume printed characters from the buffer. */
                   1083:                buffer_consume(&stderr_buffer, len);
1.57      markus   1084:                stderr_bytes += len;
1.11      markus   1085:        }
1.1       deraadt  1086: }
                   1087:
1.13      markus   1088: /*
1.15      markus   1089:  * Get packets from the connection input buffer, and process them as long as
                   1090:  * there are packets available.
                   1091:  *
                   1092:  * Any unknown packets received during the actual
                   1093:  * session cause the session to terminate.  This is
                   1094:  * intended to make debugging easier since no
                   1095:  * confirmations are sent.  Any compatible protocol
                   1096:  * extensions must be negotiated during the
                   1097:  * preparatory phase.
                   1098:  */
                   1099:
1.77      itojun   1100: static void
1.49      itojun   1101: client_process_buffered_input_packets(void)
1.15      markus   1102: {
1.54      markus   1103:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
1.15      markus   1104: }
                   1105:
1.31      markus   1106: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1107:
1.77      itojun   1108: static int
1.31      markus   1109: simple_escape_filter(Channel *c, char *buf, int len)
1.30      markus   1110: {
1.190     djm      1111:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1112:                return 0;
                   1113:
1.31      markus   1114:        return process_escapes(&c->input, &c->output, &c->extended, buf, len);
1.30      markus   1115: }
                   1116:
1.77      itojun   1117: static void
1.60      markus   1118: client_channel_closed(int id, void *arg)
                   1119: {
1.83      markus   1120:        channel_cancel_cleanup(id);
1.60      markus   1121:        session_closed = 1;
1.113     markus   1122:        leave_raw_mode();
1.60      markus   1123: }
                   1124:
1.15      markus   1125: /*
1.13      markus   1126:  * Implements the interactive session with the server.  This is called after
                   1127:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1128:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1129:  * used as an escape character for terminating or suspending the session.
1.13      markus   1130:  */
1.1       deraadt  1131:
1.20      markus   1132: int
1.30      markus   1133: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1       deraadt  1134: {
1.46      markus   1135:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus   1136:        double start_time, total_time;
1.130     avsm     1137:        int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
                   1138:        u_int nalloc = 0;
1.11      markus   1139:        char buf[100];
                   1140:
                   1141:        debug("Entering interactive session.");
                   1142:
                   1143:        start_time = get_current_time();
                   1144:
                   1145:        /* Initialize variables. */
                   1146:        escape_pending = 0;
                   1147:        last_was_cr = 1;
                   1148:        exit_status = -1;
                   1149:        stdin_eof = 0;
                   1150:        buffer_high = 64 * 1024;
                   1151:        connection_in = packet_get_connection_in();
                   1152:        connection_out = packet_get_connection_out();
1.46      markus   1153:        max_fd = MAX(connection_in, connection_out);
1.192     djm      1154:        if (muxserver_sock != -1)
                   1155:                max_fd = MAX(max_fd, muxserver_sock);
1.46      markus   1156:
                   1157:        if (!compat20) {
1.63      markus   1158:                /* enable nonblocking unless tty */
                   1159:                if (!isatty(fileno(stdin)))
                   1160:                        set_nonblock(fileno(stdin));
                   1161:                if (!isatty(fileno(stdout)))
                   1162:                        set_nonblock(fileno(stdout));
                   1163:                if (!isatty(fileno(stderr)))
                   1164:                        set_nonblock(fileno(stderr));
1.46      markus   1165:                max_fd = MAX(max_fd, fileno(stdin));
                   1166:                max_fd = MAX(max_fd, fileno(stdout));
                   1167:                max_fd = MAX(max_fd, fileno(stderr));
                   1168:        }
1.11      markus   1169:        stdin_bytes = 0;
                   1170:        stdout_bytes = 0;
                   1171:        stderr_bytes = 0;
                   1172:        quit_pending = 0;
                   1173:        escape_char = escape_char_arg;
                   1174:
                   1175:        /* Initialize buffers. */
                   1176:        buffer_init(&stdin_buffer);
                   1177:        buffer_init(&stdout_buffer);
                   1178:        buffer_init(&stderr_buffer);
                   1179:
1.15      markus   1180:        client_init_dispatch();
                   1181:
1.105     markus   1182:        /*
                   1183:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1184:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1185:         */
1.131     djm      1186:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1187:                signal(SIGHUP, signal_handler);
1.105     markus   1188:        if (signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1189:                signal(SIGINT, signal_handler);
                   1190:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1191:                signal(SIGQUIT, signal_handler);
                   1192:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1193:                signal(SIGTERM, signal_handler);
1.132     djm      1194:        signal(SIGWINCH, window_change_handler);
1.11      markus   1195:
                   1196:        if (have_pty)
                   1197:                enter_raw_mode();
                   1198:
1.48      markus   1199:        if (compat20) {
                   1200:                session_ident = ssh2_chan_id;
1.72      stevesk  1201:                if (escape_char != SSH_ESCAPECHAR_NONE)
1.48      markus   1202:                        channel_register_filter(session_ident,
1.149     reyk     1203:                            simple_escape_filter, NULL);
1.60      markus   1204:                if (session_ident != -1)
                   1205:                        channel_register_cleanup(session_ident,
1.143     djm      1206:                            client_channel_closed, 0);
1.48      markus   1207:        } else {
                   1208:                /* Check if we should immediately send eof on stdin. */
1.16      markus   1209:                client_check_initial_eof_on_stdin();
1.48      markus   1210:        }
1.30      markus   1211:
1.11      markus   1212:        /* Main loop of the client for the interactive session mode. */
                   1213:        while (!quit_pending) {
                   1214:
1.13      markus   1215:                /* Process buffered packets sent by the server. */
1.11      markus   1216:                client_process_buffered_input_packets();
                   1217:
1.60      markus   1218:                if (compat20 && session_closed && !channel_still_open())
                   1219:                        break;
                   1220:
1.56      markus   1221:                rekeying = (xxx_kex != NULL && !xxx_kex->done);
1.16      markus   1222:
1.56      markus   1223:                if (rekeying) {
                   1224:                        debug("rekeying in progress");
                   1225:                } else {
                   1226:                        /*
                   1227:                         * Make packets of buffered stdin data, and buffer
                   1228:                         * them for sending to the server.
                   1229:                         */
                   1230:                        if (!compat20)
                   1231:                                client_make_packets_from_stdin_data();
1.11      markus   1232:
1.56      markus   1233:                        /*
                   1234:                         * Make packets from buffered channel data, and
                   1235:                         * enqueue them for sending to the server.
                   1236:                         */
                   1237:                        if (packet_not_very_much_data_to_write())
                   1238:                                channel_output_poll();
1.11      markus   1239:
1.56      markus   1240:                        /*
                   1241:                         * Check if the window size has changed, and buffer a
                   1242:                         * message about it to the server if so.
                   1243:                         */
                   1244:                        client_check_window_change();
1.11      markus   1245:
1.56      markus   1246:                        if (quit_pending)
                   1247:                                break;
                   1248:                }
1.13      markus   1249:                /*
                   1250:                 * Wait until we have something to do (something becomes
                   1251:                 * available on one of the descriptors).
                   1252:                 */
1.81      markus   1253:                max_fd2 = max_fd;
1.56      markus   1254:                client_wait_until_can_do_something(&readset, &writeset,
1.81      markus   1255:                    &max_fd2, &nalloc, rekeying);
1.11      markus   1256:
                   1257:                if (quit_pending)
                   1258:                        break;
                   1259:
1.56      markus   1260:                /* Do channel operations unless rekeying in progress. */
                   1261:                if (!rekeying) {
                   1262:                        channel_after_select(readset, writeset);
1.108     markus   1263:                        if (need_rekeying || packet_need_rekeying()) {
                   1264:                                debug("need rekeying");
1.56      markus   1265:                                xxx_kex->done = 0;
                   1266:                                kex_send_kexinit(xxx_kex);
                   1267:                                need_rekeying = 0;
                   1268:                        }
                   1269:                }
1.11      markus   1270:
1.17      markus   1271:                /* Buffer input from the connection.  */
1.46      markus   1272:                client_process_net_input(readset);
1.17      markus   1273:
1.123     djm      1274:                /* Accept control connections.  */
1.192     djm      1275:                if (muxserver_sock != -1 &&FD_ISSET(muxserver_sock, readset)) {
                   1276:                        if (muxserver_accept_control())
                   1277:                                quit_pending = 1;
                   1278:                }
1.123     djm      1279:
1.17      markus   1280:                if (quit_pending)
                   1281:                        break;
1.11      markus   1282:
1.17      markus   1283:                if (!compat20) {
                   1284:                        /* Buffer data from stdin */
1.46      markus   1285:                        client_process_input(readset);
1.17      markus   1286:                        /*
                   1287:                         * Process output to stdout and stderr.  Output to
                   1288:                         * the connection is processed elsewhere (above).
                   1289:                         */
1.46      markus   1290:                        client_process_output(writeset);
1.17      markus   1291:                }
1.11      markus   1292:
1.13      markus   1293:                /* Send as much buffered packet data as possible to the sender. */
1.46      markus   1294:                if (FD_ISSET(connection_out, writeset))
1.11      markus   1295:                        packet_write_poll();
                   1296:        }
1.46      markus   1297:        if (readset)
                   1298:                xfree(readset);
                   1299:        if (writeset)
                   1300:                xfree(writeset);
1.11      markus   1301:
                   1302:        /* Terminate the session. */
                   1303:
                   1304:        /* Stop watching for window change. */
1.132     djm      1305:        signal(SIGWINCH, SIG_DFL);
1.11      markus   1306:
1.76      markus   1307:        channel_free_all();
1.11      markus   1308:
1.75      markus   1309:        if (have_pty)
                   1310:                leave_raw_mode();
                   1311:
                   1312:        /* restore blocking io */
                   1313:        if (!isatty(fileno(stdin)))
                   1314:                unset_nonblock(fileno(stdin));
                   1315:        if (!isatty(fileno(stdout)))
                   1316:                unset_nonblock(fileno(stdout));
                   1317:        if (!isatty(fileno(stderr)))
                   1318:                unset_nonblock(fileno(stderr));
1.116     dtucker  1319:
                   1320:        /*
                   1321:         * If there was no shell or command requested, there will be no remote
                   1322:         * exit status to be returned.  In that case, clear error code if the
                   1323:         * connection was deliberately terminated at this end.
                   1324:         */
                   1325:        if (no_shell_flag && received_signal == SIGTERM) {
                   1326:                received_signal = 0;
                   1327:                exit_status = 0;
                   1328:        }
1.75      markus   1329:
1.113     markus   1330:        if (received_signal)
1.89      itojun   1331:                fatal("Killed by signal %d.", (int) received_signal);
1.75      markus   1332:
1.13      markus   1333:        /*
                   1334:         * In interactive mode (with pseudo tty) display a message indicating
                   1335:         * that the connection has been closed.
                   1336:         */
1.11      markus   1337:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
                   1338:                snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
                   1339:                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1340:        }
1.70      markus   1341:
1.11      markus   1342:        /* Output any buffered data for stdout. */
1.70      markus   1343:        while (buffer_len(&stdout_buffer) > 0) {
                   1344:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1345:                    buffer_len(&stdout_buffer));
1.70      markus   1346:                if (len <= 0) {
1.11      markus   1347:                        error("Write failed flushing stdout buffer.");
1.70      markus   1348:                        break;
                   1349:                }
1.11      markus   1350:                buffer_consume(&stdout_buffer, len);
1.57      markus   1351:                stdout_bytes += len;
1.11      markus   1352:        }
                   1353:
                   1354:        /* Output any buffered data for stderr. */
1.70      markus   1355:        while (buffer_len(&stderr_buffer) > 0) {
                   1356:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1357:                    buffer_len(&stderr_buffer));
1.70      markus   1358:                if (len <= 0) {
1.11      markus   1359:                        error("Write failed flushing stderr buffer.");
1.70      markus   1360:                        break;
                   1361:                }
1.11      markus   1362:                buffer_consume(&stderr_buffer, len);
1.57      markus   1363:                stderr_bytes += len;
1.11      markus   1364:        }
                   1365:
                   1366:        /* Clear and free any buffers. */
                   1367:        memset(buf, 0, sizeof(buf));
                   1368:        buffer_free(&stdin_buffer);
                   1369:        buffer_free(&stdout_buffer);
                   1370:        buffer_free(&stderr_buffer);
                   1371:
                   1372:        /* Report bytes transferred, and transfer rates. */
                   1373:        total_time = get_current_time() - start_time;
                   1374:        debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
1.90      deraadt  1375:            stdin_bytes, stdout_bytes, stderr_bytes, total_time);
1.11      markus   1376:        if (total_time > 0)
                   1377:                debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
1.90      deraadt  1378:                    stdin_bytes / total_time, stdout_bytes / total_time,
                   1379:                    stderr_bytes / total_time);
1.11      markus   1380:
                   1381:        /* Return the exit status of the program. */
                   1382:        debug("Exit status %d", exit_status);
                   1383:        return exit_status;
1.15      markus   1384: }
                   1385:
                   1386: /*********/
                   1387:
1.77      itojun   1388: static void
1.94      markus   1389: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1390: {
1.42      markus   1391:        u_int data_len;
1.15      markus   1392:        char *data = packet_get_string(&data_len);
1.93      markus   1393:        packet_check_eom();
1.15      markus   1394:        buffer_append(&stdout_buffer, data, data_len);
                   1395:        memset(data, 0, data_len);
                   1396:        xfree(data);
                   1397: }
1.77      itojun   1398: static void
1.94      markus   1399: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1400: {
1.42      markus   1401:        u_int data_len;
1.15      markus   1402:        char *data = packet_get_string(&data_len);
1.93      markus   1403:        packet_check_eom();
1.15      markus   1404:        buffer_append(&stderr_buffer, data, data_len);
                   1405:        memset(data, 0, data_len);
                   1406:        xfree(data);
                   1407: }
1.77      itojun   1408: static void
1.94      markus   1409: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15      markus   1410: {
                   1411:        exit_status = packet_get_int();
1.93      markus   1412:        packet_check_eom();
1.15      markus   1413:        /* Acknowledge the exit. */
                   1414:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                   1415:        packet_send();
                   1416:        /*
                   1417:         * Must wait for packet to be sent since we are
                   1418:         * exiting the loop.
                   1419:         */
                   1420:        packet_write_wait();
                   1421:        /* Flag that we want to exit. */
                   1422:        quit_pending = 1;
                   1423: }
1.115     markus   1424: static void
                   1425: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
                   1426: {
                   1427:        Channel *c = NULL;
                   1428:        int remote_id, sock;
                   1429:
                   1430:        /* Read the remote channel number from the message. */
                   1431:        remote_id = packet_get_int();
                   1432:        packet_check_eom();
                   1433:
                   1434:        /*
                   1435:         * Get a connection to the local authentication agent (this may again
                   1436:         * get forwarded).
                   1437:         */
                   1438:        sock = ssh_get_authentication_socket();
                   1439:
                   1440:        /*
                   1441:         * If we could not connect the agent, send an error message back to
                   1442:         * the server. This should never happen unless the agent dies,
                   1443:         * because authentication forwarding is only enabled if we have an
                   1444:         * agent.
                   1445:         */
                   1446:        if (sock >= 0) {
                   1447:                c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
                   1448:                    -1, 0, 0, 0, "authentication agent connection", 1);
                   1449:                c->remote_id = remote_id;
                   1450:                c->force_drain = 1;
                   1451:        }
                   1452:        if (c == NULL) {
                   1453:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1454:                packet_put_int(remote_id);
                   1455:        } else {
                   1456:                /* Send a confirmation to the remote host. */
                   1457:                debug("Forwarding authentication connection.");
                   1458:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1459:                packet_put_int(remote_id);
                   1460:                packet_put_int(c->self);
                   1461:        }
                   1462:        packet_send();
                   1463: }
1.15      markus   1464:
1.77      itojun   1465: static Channel *
1.40      markus   1466: client_request_forwarded_tcpip(const char *request_type, int rchan)
                   1467: {
1.103     deraadt  1468:        Channel *c = NULL;
1.40      markus   1469:        char *listen_address, *originator_address;
                   1470:        int listen_port, originator_port;
                   1471:
                   1472:        /* Get rest of the packet */
                   1473:        listen_address = packet_get_string(NULL);
                   1474:        listen_port = packet_get_int();
                   1475:        originator_address = packet_get_string(NULL);
                   1476:        originator_port = packet_get_int();
1.93      markus   1477:        packet_check_eom();
1.40      markus   1478:
1.191     djm      1479:        debug("client_request_forwarded_tcpip: listen %s port %d, "
                   1480:            "originator %s port %d", listen_address, listen_port,
                   1481:            originator_address, originator_port);
                   1482:
                   1483:        c = channel_connect_by_listen_address(listen_port,
                   1484:            "forwarded-tcpip", originator_address);
1.40      markus   1485:
                   1486:        xfree(originator_address);
                   1487:        xfree(listen_address);
                   1488:        return c;
                   1489: }
                   1490:
1.103     deraadt  1491: static Channel *
1.40      markus   1492: client_request_x11(const char *request_type, int rchan)
                   1493: {
                   1494:        Channel *c = NULL;
                   1495:        char *originator;
                   1496:        int originator_port;
1.67      markus   1497:        int sock;
1.40      markus   1498:
                   1499:        if (!options.forward_x11) {
                   1500:                error("Warning: ssh server tried X11 forwarding.");
1.148     stevesk  1501:                error("Warning: this is probably a break-in attempt by a malicious server.");
1.40      markus   1502:                return NULL;
                   1503:        }
                   1504:        originator = packet_get_string(NULL);
                   1505:        if (datafellows & SSH_BUG_X11FWD) {
                   1506:                debug2("buggy server: x11 request w/o originator_port");
                   1507:                originator_port = 0;
                   1508:        } else {
                   1509:                originator_port = packet_get_int();
                   1510:        }
1.93      markus   1511:        packet_check_eom();
1.40      markus   1512:        /* XXX check permission */
1.47      markus   1513:        debug("client_request_x11: request from %s %d", originator,
                   1514:            originator_port);
1.67      markus   1515:        xfree(originator);
1.40      markus   1516:        sock = x11_connect_display();
1.67      markus   1517:        if (sock < 0)
                   1518:                return NULL;
                   1519:        c = channel_new("x11",
                   1520:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1521:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1522:        c->force_drain = 1;
1.40      markus   1523:        return c;
                   1524: }
                   1525:
1.103     deraadt  1526: static Channel *
1.40      markus   1527: client_request_agent(const char *request_type, int rchan)
                   1528: {
                   1529:        Channel *c = NULL;
1.67      markus   1530:        int sock;
1.40      markus   1531:
                   1532:        if (!options.forward_agent) {
                   1533:                error("Warning: ssh server tried agent forwarding.");
1.148     stevesk  1534:                error("Warning: this is probably a break-in attempt by a malicious server.");
1.40      markus   1535:                return NULL;
                   1536:        }
1.177     stevesk  1537:        sock = ssh_get_authentication_socket();
1.67      markus   1538:        if (sock < 0)
                   1539:                return NULL;
                   1540:        c = channel_new("authentication agent connection",
                   1541:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1542:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1543:            "authentication agent connection", 1);
1.82      markus   1544:        c->force_drain = 1;
1.40      markus   1545:        return c;
1.180     djm      1546: }
                   1547:
                   1548: int
                   1549: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
                   1550: {
                   1551:        Channel *c;
                   1552:        int fd;
                   1553:
                   1554:        if (tun_mode == SSH_TUNMODE_NO)
                   1555:                return 0;
                   1556:
                   1557:        if (!compat20) {
                   1558:                error("Tunnel forwarding is not support for protocol 1");
                   1559:                return -1;
                   1560:        }
                   1561:
                   1562:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1563:
                   1564:        /* Open local tunnel device */
                   1565:        if ((fd = tun_open(local_tun, tun_mode)) == -1) {
                   1566:                error("Tunnel device open failed.");
                   1567:                return -1;
                   1568:        }
                   1569:
                   1570:        c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
                   1571:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1572:        c->datagram = 1;
                   1573:
                   1574:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1575:        packet_put_cstring("tun@openssh.com");
                   1576:        packet_put_int(c->self);
                   1577:        packet_put_int(c->local_window_max);
                   1578:        packet_put_int(c->local_maxpacket);
                   1579:        packet_put_int(tun_mode);
                   1580:        packet_put_int(remote_tun);
                   1581:        packet_send();
                   1582:
                   1583:        return 0;
1.40      markus   1584: }
                   1585:
1.22      markus   1586: /* XXXX move to generic input handler */
1.77      itojun   1587: static void
1.94      markus   1588: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22      markus   1589: {
                   1590:        Channel *c = NULL;
                   1591:        char *ctype;
                   1592:        int rchan;
1.102     markus   1593:        u_int rmaxpack, rwindow, len;
1.22      markus   1594:
                   1595:        ctype = packet_get_string(&len);
                   1596:        rchan = packet_get_int();
                   1597:        rwindow = packet_get_int();
                   1598:        rmaxpack = packet_get_int();
                   1599:
1.24      markus   1600:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1601:            ctype, rchan, rwindow, rmaxpack);
                   1602:
1.40      markus   1603:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
                   1604:                c = client_request_forwarded_tcpip(ctype, rchan);
                   1605:        } else if (strcmp(ctype, "x11") == 0) {
                   1606:                c = client_request_x11(ctype, rchan);
                   1607:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
                   1608:                c = client_request_agent(ctype, rchan);
1.22      markus   1609:        }
                   1610: /* XXX duplicate : */
                   1611:        if (c != NULL) {
                   1612:                debug("confirm %s", ctype);
                   1613:                c->remote_id = rchan;
                   1614:                c->remote_window = rwindow;
                   1615:                c->remote_maxpacket = rmaxpack;
1.69      markus   1616:                if (c->type != SSH_CHANNEL_CONNECTING) {
                   1617:                        packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1618:                        packet_put_int(c->remote_id);
                   1619:                        packet_put_int(c->self);
                   1620:                        packet_put_int(c->local_window);
                   1621:                        packet_put_int(c->local_maxpacket);
                   1622:                        packet_send();
                   1623:                }
1.22      markus   1624:        } else {
                   1625:                debug("failure %s", ctype);
                   1626:                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1627:                packet_put_int(rchan);
                   1628:                packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66      markus   1629:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69      markus   1630:                        packet_put_cstring("open failed");
1.66      markus   1631:                        packet_put_cstring("");
                   1632:                }
1.22      markus   1633:                packet_send();
                   1634:        }
                   1635:        xfree(ctype);
                   1636: }
1.77      itojun   1637: static void
1.94      markus   1638: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48      markus   1639: {
                   1640:        Channel *c = NULL;
1.123     djm      1641:        int exitval, id, reply, success = 0;
1.48      markus   1642:        char *rtype;
                   1643:
                   1644:        id = packet_get_int();
                   1645:        rtype = packet_get_string(NULL);
                   1646:        reply = packet_get_char();
                   1647:
                   1648:        debug("client_input_channel_req: channel %d rtype %s reply %d",
                   1649:            id, rtype, reply);
                   1650:
1.128     djm      1651:        if (id == -1) {
                   1652:                error("client_input_channel_req: request for channel -1");
                   1653:        } else if ((c = channel_lookup(id)) == NULL) {
1.48      markus   1654:                error("client_input_channel_req: channel %d: unknown channel", id);
1.193   ! markus   1655:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
        !          1656:                packet_check_eom();
        !          1657:                chan_rcvd_eow(c);
1.48      markus   1658:        } else if (strcmp(rtype, "exit-status") == 0) {
1.123     djm      1659:                exitval = packet_get_int();
                   1660:                if (id == session_ident) {
                   1661:                        success = 1;
                   1662:                        exit_status = exitval;
                   1663:                } else if (c->ctl_fd == -1) {
                   1664:                        error("client_input_channel_req: unexpected channel %d",
                   1665:                            session_ident);
                   1666:                } else {
                   1667:                        atomicio(vwrite, c->ctl_fd, &exitval, sizeof(exitval));
                   1668:                        success = 1;
                   1669:                }
1.93      markus   1670:                packet_check_eom();
1.48      markus   1671:        }
                   1672:        if (reply) {
                   1673:                packet_start(success ?
                   1674:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.128     djm      1675:                packet_put_int(id);
1.48      markus   1676:                packet_send();
                   1677:        }
                   1678:        xfree(rtype);
                   1679: }
1.95      markus   1680: static void
                   1681: client_input_global_request(int type, u_int32_t seq, void *ctxt)
                   1682: {
                   1683:        char *rtype;
                   1684:        int want_reply;
                   1685:        int success = 0;
                   1686:
                   1687:        rtype = packet_get_string(NULL);
                   1688:        want_reply = packet_get_char();
1.117     markus   1689:        debug("client_input_global_request: rtype %s want_reply %d",
                   1690:            rtype, want_reply);
1.95      markus   1691:        if (want_reply) {
                   1692:                packet_start(success ?
                   1693:                    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
                   1694:                packet_send();
                   1695:                packet_write_wait();
                   1696:        }
                   1697:        xfree(rtype);
                   1698: }
1.22      markus   1699:
1.123     djm      1700: void
1.129     deraadt  1701: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190     djm      1702:     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123     djm      1703: {
                   1704:        int len;
1.132     djm      1705:        Channel *c = NULL;
1.123     djm      1706:
                   1707:        debug2("%s: id %d", __func__, id);
                   1708:
1.132     djm      1709:        if ((c = channel_lookup(id)) == NULL)
                   1710:                fatal("client_session2_setup: channel %d: unknown channel", id);
                   1711:
1.123     djm      1712:        if (want_tty) {
                   1713:                struct winsize ws;
                   1714:                struct termios tio;
                   1715:
                   1716:                /* Store window size in the packet. */
                   1717:                if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
                   1718:                        memset(&ws, 0, sizeof(ws));
                   1719:
1.190     djm      1720:                channel_request_start(id, "pty-req", 1);
                   1721:                client_expect_confirm(id, "PTY allocation", 0);
1.123     djm      1722:                packet_put_cstring(term != NULL ? term : "");
1.158     deraadt  1723:                packet_put_int((u_int)ws.ws_col);
                   1724:                packet_put_int((u_int)ws.ws_row);
                   1725:                packet_put_int((u_int)ws.ws_xpixel);
                   1726:                packet_put_int((u_int)ws.ws_ypixel);
1.123     djm      1727:                tio = get_saved_tio();
                   1728:                tty_make_modes(-1, tiop != NULL ? tiop : &tio);
                   1729:                packet_send();
                   1730:                /* XXX wait for reply */
1.132     djm      1731:                c->client_tty = 1;
1.123     djm      1732:        }
                   1733:
                   1734:        /* Transfer any environment variables from client to server */
1.126     djm      1735:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      1736:                int i, j, matched;
                   1737:                char *name, *val;
                   1738:
                   1739:                debug("Sending environment.");
1.126     djm      1740:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      1741:                        /* Split */
1.126     djm      1742:                        name = xstrdup(env[i]);
1.123     djm      1743:                        if ((val = strchr(name, '=')) == NULL) {
1.144     stevesk  1744:                                xfree(name);
1.123     djm      1745:                                continue;
                   1746:                        }
                   1747:                        *val++ = '\0';
                   1748:
                   1749:                        matched = 0;
                   1750:                        for (j = 0; j < options.num_send_env; j++) {
                   1751:                                if (match_pattern(name, options.send_env[j])) {
                   1752:                                        matched = 1;
                   1753:                                        break;
                   1754:                                }
                   1755:                        }
                   1756:                        if (!matched) {
                   1757:                                debug3("Ignored env %s", name);
1.144     stevesk  1758:                                xfree(name);
1.123     djm      1759:                                continue;
                   1760:                        }
                   1761:
                   1762:                        debug("Sending env %s = %s", name, val);
                   1763:                        channel_request_start(id, "env", 0);
                   1764:                        packet_put_cstring(name);
                   1765:                        packet_put_cstring(val);
                   1766:                        packet_send();
1.144     stevesk  1767:                        xfree(name);
1.123     djm      1768:                }
                   1769:        }
                   1770:
                   1771:        len = buffer_len(cmd);
                   1772:        if (len > 0) {
                   1773:                if (len > 900)
                   1774:                        len = 900;
                   1775:                if (want_subsystem) {
1.190     djm      1776:                        debug("Sending subsystem: %.*s",
                   1777:                            len, (u_char*)buffer_ptr(cmd));
                   1778:                        channel_request_start(id, "subsystem", 1);
                   1779:                        client_expect_confirm(id, "subsystem", 1);
1.123     djm      1780:                } else {
1.190     djm      1781:                        debug("Sending command: %.*s",
                   1782:                            len, (u_char*)buffer_ptr(cmd));
                   1783:                        channel_request_start(id, "exec", 1);
                   1784:                        client_expect_confirm(id, "exec", 1);
1.123     djm      1785:                }
                   1786:                packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
                   1787:                packet_send();
                   1788:        } else {
1.190     djm      1789:                channel_request_start(id, "shell", 1);
                   1790:                client_expect_confirm(id, "shell", 1);
1.123     djm      1791:                packet_send();
                   1792:        }
                   1793: }
                   1794:
1.77      itojun   1795: static void
1.49      itojun   1796: client_init_dispatch_20(void)
1.16      markus   1797: {
1.55      markus   1798:        dispatch_init(&dispatch_protocol_error);
1.100     markus   1799:
1.16      markus   1800:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   1801:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   1802:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   1803:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22      markus   1804:        dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16      markus   1805:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   1806:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48      markus   1807:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16      markus   1808:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189     djm      1809:        dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   1810:        dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95      markus   1811:        dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   1812:
                   1813:        /* rekeying */
                   1814:        dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   1815:
                   1816:        /* global request reply messages */
                   1817:        dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   1818:        dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16      markus   1819: }
1.77      itojun   1820: static void
1.49      itojun   1821: client_init_dispatch_13(void)
1.15      markus   1822: {
                   1823:        dispatch_init(NULL);
                   1824:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                   1825:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                   1826:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                   1827:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   1828:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   1829:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                   1830:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                   1831:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                   1832:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39      markus   1833:
                   1834:        dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115     markus   1835:            &client_input_agent_open : &deny_input_open);
1.39      markus   1836:        dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
                   1837:            &x11_input_open : &deny_input_open);
1.15      markus   1838: }
1.77      itojun   1839: static void
1.49      itojun   1840: client_init_dispatch_15(void)
1.15      markus   1841: {
                   1842:        client_init_dispatch_13();
                   1843:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                   1844:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                   1845: }
1.79      stevesk  1846: static void
1.49      itojun   1847: client_init_dispatch(void)
1.15      markus   1848: {
1.16      markus   1849:        if (compat20)
                   1850:                client_init_dispatch_20();
                   1851:        else if (compat13)
1.15      markus   1852:                client_init_dispatch_13();
                   1853:        else
                   1854:                client_init_dispatch_15();
1.113     markus   1855: }
                   1856:
                   1857: /* client specific fatal cleanup */
                   1858: void
1.114     markus   1859: cleanup_exit(int i)
1.113     markus   1860: {
                   1861:        leave_raw_mode();
                   1862:        leave_non_blocking();
1.192     djm      1863:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      1864:                unlink(options.control_path);
1.114     markus   1865:        _exit(i);
1.1       deraadt  1866: }