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

1.241   ! dtucker     1: /* $OpenBSD: clientloop.c,v 1.240 2012/06/20 04:42:58 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 "match.h"
                    103: #include "msg.h"
1.212     andreas   104: #include "roaming.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.217     djm       116: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
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:
1.222     djm       137: /* Time when backgrounded control master using ControlPersist should exit */
                    138: static time_t control_persist_exit_time = 0;
                    139:
1.1       deraadt   140: /* Common data for the client loop code. */
1.217     djm       141: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.195     djm       142: static int escape_char1;       /* Escape character. (proto1 only) */
                    143: static int escape_pending1;    /* Last character was an escape (proto1 only) */
1.11      markus    144: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       145: static int exit_status;                /* Used to store the command exit status. */
                    146: static int stdin_eof;          /* EOF has been encountered on stderr. */
1.11      markus    147: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                    148: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                    149: static Buffer stderr_buffer;   /* Buffer for stderr data. */
1.221     djm       150: static u_int buffer_high;      /* Soft max buffer size. */
1.11      markus    151: static int connection_in;      /* Connection to server (input). */
                    152: static int connection_out;     /* Connection to server (output). */
1.56      markus    153: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221     djm       154: static int session_closed;     /* In SSH2: login session closed. */
                    155: static int x11_refuse_time;    /* If >0, refuse x11 opens after this time. */
1.1       deraadt   156:
1.77      itojun    157: static void client_init_dispatch(void);
1.16      markus    158: int    session_ident = -1;
                    159:
1.214     andreas   160: int    session_resumed = 0;
                    161:
1.195     djm       162: /* Track escape per proto2 channel */
                    163: struct escape_filter_ctx {
                    164:        int escape_pending;
                    165:        int escape_char;
                    166: };
                    167:
                    168: /* Context for channel confirmation replies */
1.190     djm       169: struct channel_reply_ctx {
                    170:        const char *request_type;
1.234     djm       171:        int id;
                    172:        enum confirm_action action;
1.190     djm       173: };
                    174:
1.196     djm       175: /* Global request success/failure callbacks */
                    176: struct global_confirm {
                    177:        TAILQ_ENTRY(global_confirm) entry;
                    178:        global_confirm_cb *cb;
                    179:        void *ctx;
                    180:        int ref_count;
                    181: };
                    182: TAILQ_HEAD(global_confirms, global_confirm);
                    183: static struct global_confirms global_confirms =
                    184:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    185:
1.54      markus    186: /*XXX*/
                    187: extern Kex *xxx_kex;
                    188:
1.123     djm       189: void ssh_process_session2_setup(int, int, int, Buffer *);
                    190:
1.1       deraadt   191: /* Restores stdin to blocking mode. */
                    192:
1.77      itojun    193: static void
1.49      itojun    194: leave_non_blocking(void)
1.1       deraadt   195: {
1.11      markus    196:        if (in_non_blocking_mode) {
1.125     djm       197:                unset_nonblock(fileno(stdin));
1.11      markus    198:                in_non_blocking_mode = 0;
                    199:        }
1.1       deraadt   200: }
                    201:
1.11      markus    202: /* Puts stdin terminal in non-blocking mode. */
                    203:
1.77      itojun    204: static void
1.49      itojun    205: enter_non_blocking(void)
1.1       deraadt   206: {
1.11      markus    207:        in_non_blocking_mode = 1;
1.124     djm       208:        set_nonblock(fileno(stdin));
1.1       deraadt   209: }
                    210:
1.13      markus    211: /*
                    212:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    213:  * flag indicating that the window has changed.
                    214:  */
1.157     deraadt   215: /*ARGSUSED */
1.77      itojun    216: static void
1.11      markus    217: window_change_handler(int sig)
1.1       deraadt   218: {
1.11      markus    219:        received_window_change_signal = 1;
                    220:        signal(SIGWINCH, window_change_handler);
1.1       deraadt   221: }
                    222:
1.13      markus    223: /*
                    224:  * Signal handler for signals that cause the program to terminate.  These
                    225:  * signals must be trapped to restore terminal modes.
                    226:  */
1.157     deraadt   227: /*ARGSUSED */
1.77      itojun    228: static void
1.11      markus    229: signal_handler(int sig)
1.1       deraadt   230: {
1.75      markus    231:        received_signal = sig;
                    232:        quit_pending = 1;
1.1       deraadt   233: }
                    234:
1.13      markus    235: /*
                    236:  * Returns current time in seconds from Jan 1, 1970 with the maximum
                    237:  * available resolution.
                    238:  */
1.1       deraadt   239:
1.77      itojun    240: static double
1.49      itojun    241: get_current_time(void)
1.1       deraadt   242: {
1.11      markus    243:        struct timeval tv;
                    244:        gettimeofday(&tv, NULL);
                    245:        return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
1.138     djm       246: }
                    247:
1.222     djm       248: /*
                    249:  * Sets control_persist_exit_time to the absolute time when the
                    250:  * backgrounded control master should exit due to expiry of the
                    251:  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
                    252:  * control master process, or if there is no ControlPersist timeout.
                    253:  */
                    254: static void
                    255: set_control_persist_exit_time(void)
                    256: {
                    257:        if (muxserver_sock == -1 || !options.control_persist
1.232     djm       258:            || options.control_persist_timeout == 0) {
1.222     djm       259:                /* not using a ControlPersist timeout */
                    260:                control_persist_exit_time = 0;
1.232     djm       261:        } else if (channel_still_open()) {
1.222     djm       262:                /* some client connections are still open */
                    263:                if (control_persist_exit_time > 0)
                    264:                        debug2("%s: cancel scheduled exit", __func__);
                    265:                control_persist_exit_time = 0;
                    266:        } else if (control_persist_exit_time <= 0) {
                    267:                /* a client connection has recently closed */
                    268:                control_persist_exit_time = time(NULL) +
                    269:                        (time_t)options.control_persist_timeout;
                    270:                debug2("%s: schedule exit in %d seconds", __func__,
                    271:                    options.control_persist_timeout);
                    272:        }
                    273:        /* else we are already counting down to the timeout */
                    274: }
                    275:
1.238     dtucker   276: #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
                    277: static int
                    278: client_x11_display_valid(const char *display)
                    279: {
                    280:        size_t i, dlen;
                    281:
                    282:        dlen = strlen(display);
                    283:        for (i = 0; i < dlen; i++) {
                    284:                if (!isalnum(display[i]) &&
                    285:                    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
                    286:                        debug("Invalid character '%c' in DISPLAY", display[i]);
                    287:                        return 0;
                    288:                }
                    289:        }
                    290:        return 1;
                    291: }
                    292:
1.138     djm       293: #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
                    294: void
                    295: client_x11_get_proto(const char *display, const char *xauth_path,
1.221     djm       296:     u_int trusted, u_int timeout, char **_proto, char **_data)
1.138     djm       297: {
                    298:        char cmd[1024];
                    299:        char line[512];
                    300:        char xdisplay[512];
                    301:        static char proto[512], data[512];
                    302:        FILE *f;
                    303:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    304:        char *xauthdir, *xauthfile;
                    305:        struct stat st;
1.221     djm       306:        u_int now;
1.138     djm       307:
                    308:        xauthdir = xauthfile = NULL;
                    309:        *_proto = proto;
                    310:        *_data = data;
                    311:        proto[0] = data[0] = '\0';
                    312:
                    313:        if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
                    314:                debug("No xauth program.");
1.238     dtucker   315:        } else if (!client_x11_display_valid(display)) {
                    316:                logit("DISPLAY '%s' invalid, falling back to fake xauth data",
                    317:                    display);
1.138     djm       318:        } else {
                    319:                if (display == NULL) {
                    320:                        debug("x11_get_proto: DISPLAY not set");
                    321:                        return;
                    322:                }
                    323:                /*
                    324:                 * Handle FamilyLocal case where $DISPLAY does
                    325:                 * not match an authorization entry.  For this we
                    326:                 * just try "xauth list unix:displaynum.screennum".
                    327:                 * XXX: "localhost" match to determine FamilyLocal
                    328:                 *      is not perfect.
                    329:                 */
                    330:                if (strncmp(display, "localhost:", 10) == 0) {
                    331:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    332:                            display + 10);
                    333:                        display = xdisplay;
                    334:                }
                    335:                if (trusted == 0) {
                    336:                        xauthdir = xmalloc(MAXPATHLEN);
                    337:                        xauthfile = xmalloc(MAXPATHLEN);
1.225     djm       338:                        mktemp_proto(xauthdir, MAXPATHLEN);
1.138     djm       339:                        if (mkdtemp(xauthdir) != NULL) {
                    340:                                do_unlink = 1;
                    341:                                snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
                    342:                                    xauthdir);
                    343:                                snprintf(cmd, sizeof(cmd),
                    344:                                    "%s -f %s generate %s " SSH_X11_PROTO
1.221     djm       345:                                    " untrusted timeout %u 2>" _PATH_DEVNULL,
                    346:                                    xauth_path, xauthfile, display, timeout);
1.138     djm       347:                                debug2("x11_get_proto: %s", cmd);
                    348:                                if (system(cmd) == 0)
                    349:                                        generated = 1;
1.221     djm       350:                                if (x11_refuse_time == 0) {
                    351:                                        now = time(NULL) + 1;
                    352:                                        if (UINT_MAX - timeout < now)
                    353:                                                x11_refuse_time = UINT_MAX;
                    354:                                        else
                    355:                                                x11_refuse_time = now + timeout;
                    356:                                }
1.138     djm       357:                        }
                    358:                }
1.181     markus    359:
                    360:                /*
                    361:                 * When in untrusted mode, we read the cookie only if it was
                    362:                 * successfully generated as an untrusted one in the step
                    363:                 * above.
                    364:                 */
                    365:                if (trusted || generated) {
                    366:                        snprintf(cmd, sizeof(cmd),
                    367:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    368:                            xauth_path,
                    369:                            generated ? "-f " : "" ,
                    370:                            generated ? xauthfile : "",
                    371:                            display);
                    372:                        debug2("x11_get_proto: %s", cmd);
                    373:                        f = popen(cmd, "r");
                    374:                        if (f && fgets(line, sizeof(line), f) &&
                    375:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    376:                                got_data = 1;
                    377:                        if (f)
                    378:                                pclose(f);
                    379:                } else
                    380:                        error("Warning: untrusted X11 forwarding setup failed: "
                    381:                            "xauth key data not generated");
1.138     djm       382:        }
                    383:
                    384:        if (do_unlink) {
                    385:                unlink(xauthfile);
                    386:                rmdir(xauthdir);
                    387:        }
                    388:        if (xauthdir)
                    389:                xfree(xauthdir);
                    390:        if (xauthfile)
                    391:                xfree(xauthfile);
                    392:
                    393:        /*
                    394:         * If we didn't get authentication data, just make up some
                    395:         * data.  The forwarding code will check the validity of the
                    396:         * response anyway, and substitute this data.  The X11
                    397:         * server, however, will ignore this fake data and use
                    398:         * whatever authentication mechanisms it was using otherwise
                    399:         * for the local connection.
                    400:         */
                    401:        if (!got_data) {
                    402:                u_int32_t rnd = 0;
                    403:
                    404:                logit("Warning: No xauth data; "
                    405:                    "using fake authentication data for X11 forwarding.");
                    406:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
                    407:                for (i = 0; i < 16; i++) {
                    408:                        if (i % 4 == 0)
                    409:                                rnd = arc4random();
                    410:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
                    411:                            rnd & 0xff);
                    412:                        rnd >>= 8;
                    413:                }
                    414:        }
1.1       deraadt   415: }
                    416:
1.13      markus    417: /*
                    418:  * This is called when the interactive is entered.  This checks if there is
                    419:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    420:  * not appear to wake up when redirecting from /dev/null.
                    421:  */
1.1       deraadt   422:
1.77      itojun    423: static void
1.49      itojun    424: client_check_initial_eof_on_stdin(void)
1.1       deraadt   425: {
1.11      markus    426:        int len;
                    427:        char buf[1];
1.1       deraadt   428:
1.13      markus    429:        /*
                    430:         * If standard input is to be "redirected from /dev/null", we simply
                    431:         * mark that we have seen an EOF and send an EOF message to the
                    432:         * server. Otherwise, we try to read a single character; it appears
                    433:         * that for some files, such /dev/null, select() never wakes up for
                    434:         * read for this descriptor, which means that we never get EOF.  This
                    435:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    436:         */
1.11      markus    437:        if (stdin_null_flag) {
                    438:                /* Fake EOF on stdin. */
                    439:                debug("Sending eof.");
                    440:                stdin_eof = 1;
                    441:                packet_start(SSH_CMSG_EOF);
                    442:                packet_send();
                    443:        } else {
                    444:                enter_non_blocking();
                    445:
                    446:                /* Check for immediate EOF on stdin. */
                    447:                len = read(fileno(stdin), buf, 1);
                    448:                if (len == 0) {
1.197     djm       449:                        /*
                    450:                         * EOF.  Record that we have seen it and send
                    451:                         * EOF to server.
                    452:                         */
1.11      markus    453:                        debug("Sending eof.");
                    454:                        stdin_eof = 1;
                    455:                        packet_start(SSH_CMSG_EOF);
                    456:                        packet_send();
                    457:                } else if (len > 0) {
1.13      markus    458:                        /*
                    459:                         * Got data.  We must store the data in the buffer,
                    460:                         * and also process it as an escape character if
                    461:                         * appropriate.
                    462:                         */
1.195     djm       463:                        if ((u_char) buf[0] == escape_char1)
                    464:                                escape_pending1 = 1;
1.52      markus    465:                        else
1.11      markus    466:                                buffer_append(&stdin_buffer, buf, 1);
                    467:                }
                    468:                leave_non_blocking();
                    469:        }
1.1       deraadt   470: }
                    471:
                    472:
1.13      markus    473: /*
                    474:  * Make packets from buffered stdin data, and buffer them for sending to the
                    475:  * connection.
                    476:  */
1.1       deraadt   477:
1.77      itojun    478: static void
1.49      itojun    479: client_make_packets_from_stdin_data(void)
1.1       deraadt   480: {
1.42      markus    481:        u_int len;
1.1       deraadt   482:
1.11      markus    483:        /* Send buffered stdin data to the server. */
                    484:        while (buffer_len(&stdin_buffer) > 0 &&
1.90      deraadt   485:            packet_not_very_much_data_to_write()) {
1.11      markus    486:                len = buffer_len(&stdin_buffer);
                    487:                /* Keep the packets at reasonable size. */
                    488:                if (len > packet_get_maxsize())
                    489:                        len = packet_get_maxsize();
                    490:                packet_start(SSH_CMSG_STDIN_DATA);
                    491:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    492:                packet_send();
                    493:                buffer_consume(&stdin_buffer, len);
                    494:                /* If we have a pending EOF, send it now. */
                    495:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    496:                        packet_start(SSH_CMSG_EOF);
                    497:                        packet_send();
                    498:                }
1.1       deraadt   499:        }
                    500: }
                    501:
1.13      markus    502: /*
                    503:  * Checks if the client window has changed, and sends a packet about it to
                    504:  * the server if so.  The actual change is detected elsewhere (by a software
                    505:  * interrupt on Unix); this just checks the flag and sends a message if
                    506:  * appropriate.
                    507:  */
1.1       deraadt   508:
1.77      itojun    509: static void
1.49      itojun    510: client_check_window_change(void)
1.1       deraadt   511: {
1.16      markus    512:        struct winsize ws;
                    513:
                    514:        if (! received_window_change_signal)
                    515:                return;
                    516:        /** XXX race */
                    517:        received_window_change_signal = 0;
                    518:
1.37      markus    519:        debug2("client_check_window_change: changed");
1.16      markus    520:
                    521:        if (compat20) {
1.123     djm       522:                channel_send_window_changes();
1.16      markus    523:        } else {
1.123     djm       524:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    525:                        return;
1.16      markus    526:                packet_start(SSH_CMSG_WINDOW_SIZE);
1.158     deraadt   527:                packet_put_int((u_int)ws.ws_row);
                    528:                packet_put_int((u_int)ws.ws_col);
                    529:                packet_put_int((u_int)ws.ws_xpixel);
                    530:                packet_put_int((u_int)ws.ws_ypixel);
1.16      markus    531:                packet_send();
1.1       deraadt   532:        }
                    533: }
                    534:
1.117     markus    535: static void
                    536: client_global_request_reply(int type, u_int32_t seq, void *ctxt)
                    537: {
1.196     djm       538:        struct global_confirm *gc;
                    539:
                    540:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
                    541:                return;
                    542:        if (gc->cb != NULL)
                    543:                gc->cb(type, seq, gc->ctx);
                    544:        if (--gc->ref_count <= 0) {
                    545:                TAILQ_REMOVE(&global_confirms, gc, entry);
                    546:                bzero(gc, sizeof(*gc));
                    547:                xfree(gc);
                    548:        }
                    549:
1.210     andreas   550:        packet_set_alive_timeouts(0);
1.117     markus    551: }
                    552:
                    553: static void
                    554: server_alive_check(void)
                    555: {
1.210     andreas   556:        if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
1.228     djm       557:                logit("Timeout, server %s not responding.", host);
1.176     markus    558:                cleanup_exit(255);
                    559:        }
1.117     markus    560:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                    561:        packet_put_cstring("keepalive@openssh.com");
                    562:        packet_put_char(1);     /* boolean: want reply */
                    563:        packet_send();
1.196     djm       564:        /* Insert an empty placeholder to maintain ordering */
                    565:        client_register_global_confirm(NULL, NULL);
1.117     markus    566: }
                    567:
1.13      markus    568: /*
                    569:  * Waits until the client can do something (some data becomes available on
                    570:  * one of the file descriptors).
                    571:  */
1.77      itojun    572: static void
1.46      markus    573: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.130     avsm      574:     int *maxfdp, u_int *nallocp, int rekeying)
1.11      markus    575: {
1.117     markus    576:        struct timeval tv, *tvp;
1.222     djm       577:        int timeout_secs;
1.240     djm       578:        time_t minwait_secs = 0;
1.117     markus    579:        int ret;
                    580:
1.46      markus    581:        /* Add any selections by the channel mechanism. */
1.239     djm       582:        channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
                    583:            &minwait_secs, rekeying);
1.11      markus    584:
1.16      markus    585:        if (!compat20) {
1.17      markus    586:                /* Read from the connection, unless our buffers are full. */
1.16      markus    587:                if (buffer_len(&stdout_buffer) < buffer_high &&
                    588:                    buffer_len(&stderr_buffer) < buffer_high &&
                    589:                    channel_not_very_much_buffered_data())
1.46      markus    590:                        FD_SET(connection_in, *readsetp);
1.17      markus    591:                /*
                    592:                 * Read from stdin, unless we have seen EOF or have very much
                    593:                 * buffered data to send to the server.
                    594:                 */
                    595:                if (!stdin_eof && packet_not_very_much_data_to_write())
1.46      markus    596:                        FD_SET(fileno(stdin), *readsetp);
1.17      markus    597:
                    598:                /* Select stdout/stderr if have data in buffer. */
                    599:                if (buffer_len(&stdout_buffer) > 0)
1.46      markus    600:                        FD_SET(fileno(stdout), *writesetp);
1.17      markus    601:                if (buffer_len(&stderr_buffer) > 0)
1.46      markus    602:                        FD_SET(fileno(stderr), *writesetp);
1.16      markus    603:        } else {
1.71      markus    604:                /* channel_prepare_select could have closed the last channel */
1.84      markus    605:                if (session_closed && !channel_still_open() &&
                    606:                    !packet_have_data_to_write()) {
                    607:                        /* clear mask since we did not call select() */
1.87      markus    608:                        memset(*readsetp, 0, *nallocp);
                    609:                        memset(*writesetp, 0, *nallocp);
1.84      markus    610:                        return;
1.71      markus    611:                } else {
                    612:                        FD_SET(connection_in, *readsetp);
                    613:                }
1.16      markus    614:        }
1.11      markus    615:
                    616:        /* Select server connection if have data to write to the server. */
                    617:        if (packet_have_data_to_write())
1.46      markus    618:                FD_SET(connection_out, *writesetp);
1.11      markus    619:
1.13      markus    620:        /*
                    621:         * Wait for something to happen.  This will suspend the process until
                    622:         * some selected descriptor can be read, written, or has some other
1.222     djm       623:         * event pending, or a timeout expires.
1.13      markus    624:         */
1.11      markus    625:
1.222     djm       626:        timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
                    627:        if (options.server_alive_interval > 0 && compat20)
                    628:                timeout_secs = options.server_alive_interval;
                    629:        set_control_persist_exit_time();
                    630:        if (control_persist_exit_time > 0) {
                    631:                timeout_secs = MIN(timeout_secs,
                    632:                        control_persist_exit_time - time(NULL));
                    633:                if (timeout_secs < 0)
                    634:                        timeout_secs = 0;
                    635:        }
1.239     djm       636:        if (minwait_secs != 0)
                    637:                timeout_secs = MIN(timeout_secs, (int)minwait_secs);
1.222     djm       638:        if (timeout_secs == INT_MAX)
1.117     markus    639:                tvp = NULL;
1.129     deraadt   640:        else {
1.222     djm       641:                tv.tv_sec = timeout_secs;
1.117     markus    642:                tv.tv_usec = 0;
                    643:                tvp = &tv;
                    644:        }
1.222     djm       645:
1.117     markus    646:        ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
                    647:        if (ret < 0) {
1.11      markus    648:                char buf[100];
1.51      markus    649:
                    650:                /*
                    651:                 * We have to clear the select masks, because we return.
                    652:                 * We have to return, because the mainloop checks for the flags
                    653:                 * set by the signal handlers.
                    654:                 */
1.87      markus    655:                memset(*readsetp, 0, *nallocp);
                    656:                memset(*writesetp, 0, *nallocp);
1.50      deraadt   657:
1.11      markus    658:                if (errno == EINTR)
                    659:                        return;
                    660:                /* Note: we might still have data in the buffers. */
                    661:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    662:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    663:                quit_pending = 1;
1.117     markus    664:        } else if (ret == 0)
                    665:                server_alive_check();
1.11      markus    666: }
                    667:
1.77      itojun    668: static void
1.31      markus    669: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1       deraadt   670: {
1.11      markus    671:        /* Flush stdout and stderr buffers. */
1.31      markus    672:        if (buffer_len(bout) > 0)
1.197     djm       673:                atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
                    674:                    buffer_len(bout));
1.31      markus    675:        if (buffer_len(berr) > 0)
1.197     djm       676:                atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
                    677:                    buffer_len(berr));
1.11      markus    678:
1.233     djm       679:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    680:
1.13      markus    681:        /*
                    682:         * Free (and clear) the buffer to reduce the amount of data that gets
                    683:         * written to swap.
                    684:         */
1.31      markus    685:        buffer_free(bin);
                    686:        buffer_free(bout);
                    687:        buffer_free(berr);
1.11      markus    688:
                    689:        /* Send the suspend signal to the program itself. */
                    690:        kill(getpid(), SIGTSTP);
                    691:
1.132     djm       692:        /* Reset window sizes in case they have changed */
                    693:        received_window_change_signal = 1;
1.11      markus    694:
                    695:        /* OK, we have been continued by the user. Reinitialize buffers. */
1.31      markus    696:        buffer_init(bin);
                    697:        buffer_init(bout);
                    698:        buffer_init(berr);
1.11      markus    699:
1.233     djm       700:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    701: }
                    702:
1.77      itojun    703: static void
1.161     deraadt   704: client_process_net_input(fd_set *readset)
1.11      markus    705: {
1.212     andreas   706:        int len, cont = 0;
1.17      markus    707:        char buf[8192];
1.11      markus    708:
1.13      markus    709:        /*
                    710:         * Read input from the server, and add any such data to the buffer of
                    711:         * the packet subsystem.
                    712:         */
1.11      markus    713:        if (FD_ISSET(connection_in, readset)) {
                    714:                /* Read as much as possible. */
1.212     andreas   715:                len = roaming_read(connection_in, buf, sizeof(buf), &cont);
                    716:                if (len == 0 && cont == 0) {
1.197     djm       717:                        /*
                    718:                         * Received EOF.  The remote host has closed the
                    719:                         * connection.
                    720:                         */
                    721:                        snprintf(buf, sizeof buf,
                    722:                            "Connection to %.300s closed by remote host.\r\n",
                    723:                            host);
1.1       deraadt   724:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    725:                        quit_pending = 1;
                    726:                        return;
1.11      markus    727:                }
1.13      markus    728:                /*
                    729:                 * There is a kernel bug on Solaris that causes select to
                    730:                 * sometimes wake up even though there is no data available.
                    731:                 */
1.53      millert   732:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11      markus    733:                        len = 0;
                    734:
                    735:                if (len < 0) {
1.197     djm       736:                        /*
                    737:                         * An error has encountered.  Perhaps there is a
                    738:                         * network problem.
                    739:                         */
                    740:                        snprintf(buf, sizeof buf,
                    741:                            "Read from remote host %.300s: %.100s\r\n",
                    742:                            host, strerror(errno));
1.11      markus    743:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    744:                        quit_pending = 1;
                    745:                        return;
                    746:                }
                    747:                packet_process_incoming(buf, len);
                    748:        }
1.17      markus    749: }
1.16      markus    750:
1.97      jakob     751: static void
1.190     djm       752: client_status_confirm(int type, Channel *c, void *ctx)
1.123     djm       753: {
1.190     djm       754:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    755:        char errmsg[256];
                    756:        int tochan;
                    757:
1.234     djm       758:        /*
                    759:         * If a TTY was explicitly requested, then a failure to allocate
                    760:         * one is fatal.
                    761:         */
                    762:        if (cr->action == CONFIRM_TTY &&
                    763:            (options.request_tty == REQUEST_TTY_FORCE ||
                    764:            options.request_tty == REQUEST_TTY_YES))
                    765:                cr->action = CONFIRM_CLOSE;
                    766:
1.190     djm       767:        /* XXX supress on mux _client_ quietmode */
                    768:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       769:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       770:
                    771:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    772:                debug2("%s request accepted on channel %d",
                    773:                    cr->request_type, c->self);
                    774:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    775:                if (tochan) {
                    776:                        snprintf(errmsg, sizeof(errmsg),
                    777:                            "%s request failed\r\n", cr->request_type);
                    778:                } else {
                    779:                        snprintf(errmsg, sizeof(errmsg),
                    780:                            "%s request failed on channel %d",
                    781:                            cr->request_type, c->self);
                    782:                }
                    783:                /* If error occurred on primary session channel, then exit */
1.234     djm       784:                if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190     djm       785:                        fatal("%s", errmsg);
1.234     djm       786:                /*
                    787:                 * If error occurred on mux client, append to
                    788:                 * their stderr.
                    789:                 */
                    790:                if (tochan) {
                    791:                        buffer_append(&c->extended, errmsg,
                    792:                            strlen(errmsg));
                    793:                } else
1.190     djm       794:                        error("%s", errmsg);
1.234     djm       795:                if (cr->action == CONFIRM_TTY) {
                    796:                        /*
                    797:                         * If a TTY allocation error occurred, then arrange
                    798:                         * for the correct TTY to leave raw mode.
                    799:                         */
                    800:                        if (c->self == session_ident)
                    801:                                leave_raw_mode(0);
                    802:                        else
                    803:                                mux_tty_alloc_failed(c);
                    804:                } else if (cr->action == CONFIRM_CLOSE) {
1.190     djm       805:                        chan_read_failed(c);
                    806:                        chan_write_failed(c);
                    807:                }
                    808:        }
                    809:        xfree(cr);
                    810: }
                    811:
                    812: static void
                    813: client_abandon_status_confirm(Channel *c, void *ctx)
                    814: {
                    815:        xfree(ctx);
                    816: }
1.129     deraadt   817:
1.236     djm       818: void
1.234     djm       819: client_expect_confirm(int id, const char *request,
                    820:     enum confirm_action action)
1.190     djm       821: {
                    822:        struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
1.123     djm       823:
1.190     djm       824:        cr->request_type = request;
1.234     djm       825:        cr->action = action;
1.123     djm       826:
1.190     djm       827:        channel_register_status_confirm(id, client_status_confirm,
                    828:            client_abandon_status_confirm, cr);
1.196     djm       829: }
                    830:
                    831: void
                    832: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    833: {
1.201     djm       834:        struct global_confirm *gc, *last_gc;
1.196     djm       835:
                    836:        /* Coalesce identical callbacks */
1.201     djm       837:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    838:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    839:                if (++last_gc->ref_count >= INT_MAX)
                    840:                        fatal("%s: last_gc->ref_count = %d",
                    841:                            __func__, last_gc->ref_count);
1.196     djm       842:                return;
                    843:        }
                    844:
                    845:        gc = xmalloc(sizeof(*gc));
                    846:        gc->cb = cb;
                    847:        gc->ctx = ctx;
                    848:        gc->ref_count = 1;
                    849:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       850: }
                    851:
                    852: static void
1.99      markus    853: process_cmdline(void)
1.97      jakob     854: {
                    855:        void (*handler)(int);
1.135     djm       856:        char *s, *cmd, *cancel_host;
1.237     markus    857:        int delete = 0, local = 0, remote = 0, dynamic = 0;
                    858:        int cancel_port, ok;
1.135     djm       859:        Forward fwd;
1.97      jakob     860:
1.183     djm       861:        bzero(&fwd, sizeof(fwd));
                    862:        fwd.listen_host = fwd.connect_host = NULL;
                    863:
1.233     djm       864:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.101     markus    865:        handler = signal(SIGINT, SIG_IGN);
1.99      markus    866:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     867:        if (s == NULL)
                    868:                goto out;
1.179     tedu      869:        while (isspace(*s))
1.97      jakob     870:                s++;
1.121     djm       871:        if (*s == '-')
                    872:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   873:        if (*s == '\0')
1.97      jakob     874:                goto out;
1.121     djm       875:
1.122     djm       876:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       877:                logit("Commands:");
1.164     djm       878:                logit("      -L[bind_address:]port:host:hostport    "
                    879:                    "Request local forward");
                    880:                logit("      -R[bind_address:]port:host:hostport    "
                    881:                    "Request remote forward");
1.204     stevesk   882:                logit("      -D[bind_address:]port                  "
                    883:                    "Request dynamic forward");
1.237     markus    884:                logit("      -KL[bind_address:]port                 "
                    885:                    "Cancel local forward");
1.165     stevesk   886:                logit("      -KR[bind_address:]port                 "
1.164     djm       887:                    "Cancel remote forward");
1.237     markus    888:                logit("      -KD[bind_address:]port                 "
                    889:                    "Cancel dynamic forward");
1.146     reyk      890:                if (!options.permit_local_command)
                    891:                        goto out;
1.164     djm       892:                logit("      !args                                  "
                    893:                    "Execute local command");
1.146     reyk      894:                goto out;
                    895:        }
                    896:
                    897:        if (*s == '!' && options.permit_local_command) {
                    898:                s++;
                    899:                ssh_local_cmd(s);
1.121     djm       900:                goto out;
                    901:        }
                    902:
                    903:        if (*s == 'K') {
                    904:                delete = 1;
                    905:                s++;
                    906:        }
1.204     stevesk   907:        if (*s == 'L')
                    908:                local = 1;
                    909:        else if (*s == 'R')
                    910:                remote = 1;
                    911:        else if (*s == 'D')
                    912:                dynamic = 1;
                    913:        else {
1.109     itojun    914:                logit("Invalid command.");
1.97      jakob     915:                goto out;
                    916:        }
1.204     stevesk   917:
1.237     markus    918:        if (delete && !compat20) {
1.109     itojun    919:                logit("Not supported for SSH protocol version 1.");
1.97      jakob     920:                goto out;
                    921:        }
1.121     djm       922:
1.179     tedu      923:        while (isspace(*++s))
                    924:                ;
1.97      jakob     925:
1.217     djm       926:        /* XXX update list of forwards in options */
1.121     djm       927:        if (delete) {
1.135     djm       928:                cancel_port = 0;
                    929:                cancel_host = hpdelim(&s);      /* may be NULL */
                    930:                if (s != NULL) {
                    931:                        cancel_port = a2port(s);
                    932:                        cancel_host = cleanhostname(cancel_host);
                    933:                } else {
                    934:                        cancel_port = a2port(cancel_host);
                    935:                        cancel_host = NULL;
1.121     djm       936:                }
1.208     djm       937:                if (cancel_port <= 0) {
1.135     djm       938:                        logit("Bad forwarding close port");
1.121     djm       939:                        goto out;
                    940:                }
1.237     markus    941:                if (remote)
                    942:                        ok = channel_request_rforward_cancel(cancel_host,
                    943:                            cancel_port) == 0;
                    944:                else if (dynamic)
                    945:                        ok = channel_cancel_lport_listener(cancel_host,
                    946:                            cancel_port, 0, options.gateway_ports) > 0;
                    947:                else
                    948:                        ok = channel_cancel_lport_listener(cancel_host,
                    949:                            cancel_port, CHANNEL_CANCEL_PORT_STATIC,
                    950:                            options.gateway_ports) > 0;
                    951:                if (!ok) {
                    952:                        logit("Unkown port forwarding.");
                    953:                        goto out;
                    954:                }
                    955:                logit("Canceled forwarding.");
1.121     djm       956:        } else {
1.209     djm       957:                if (!parse_forward(&fwd, s, dynamic, remote)) {
1.121     djm       958:                        logit("Bad forwarding specification.");
                    959:                        goto out;
                    960:                }
1.204     stevesk   961:                if (local || dynamic) {
1.135     djm       962:                        if (channel_setup_local_fwd_listener(fwd.listen_host,
                    963:                            fwd.listen_port, fwd.connect_host,
                    964:                            fwd.connect_port, options.gateway_ports) < 0) {
1.121     djm       965:                                logit("Port forwarding failed.");
                    966:                                goto out;
                    967:                        }
1.135     djm       968:                } else {
1.167     markus    969:                        if (channel_request_remote_forwarding(fwd.listen_host,
1.135     djm       970:                            fwd.listen_port, fwd.connect_host,
1.167     markus    971:                            fwd.connect_port) < 0) {
                    972:                                logit("Port forwarding failed.");
                    973:                                goto out;
                    974:                        }
1.135     djm       975:                }
1.121     djm       976:                logit("Forwarding port.");
                    977:        }
                    978:
1.97      jakob     979: out:
                    980:        signal(SIGINT, handler);
1.233     djm       981:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.97      jakob     982:        if (cmd)
                    983:                xfree(cmd);
1.183     djm       984:        if (fwd.listen_host != NULL)
                    985:                xfree(fwd.listen_host);
                    986:        if (fwd.connect_host != NULL)
                    987:                xfree(fwd.connect_host);
1.97      jakob     988: }
                    989:
1.195     djm       990: /*
                    991:  * Process the characters one by one, call with c==NULL for proto1 case.
                    992:  */
1.77      itojun    993: static int
1.195     djm       994: process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
                    995:     char *buf, int len)
1.31      markus    996: {
1.32      markus    997:        char string[1024];
1.31      markus    998:        pid_t pid;
                    999:        int bytes = 0;
1.42      markus   1000:        u_int i;
                   1001:        u_char ch;
1.31      markus   1002:        char *s;
1.195     djm      1003:        int *escape_pendingp, escape_char;
                   1004:        struct escape_filter_ctx *efc;
1.31      markus   1005:
1.195     djm      1006:        if (c == NULL) {
                   1007:                escape_pendingp = &escape_pending1;
                   1008:                escape_char = escape_char1;
                   1009:        } else {
                   1010:                if (c->filter_ctx == NULL)
                   1011:                        return 0;
                   1012:                efc = (struct escape_filter_ctx *)c->filter_ctx;
                   1013:                escape_pendingp = &efc->escape_pending;
                   1014:                escape_char = efc->escape_char;
                   1015:        }
                   1016:
1.139     djm      1017:        if (len <= 0)
                   1018:                return (0);
                   1019:
                   1020:        for (i = 0; i < (u_int)len; i++) {
1.31      markus   1021:                /* Get one character at a time. */
                   1022:                ch = buf[i];
                   1023:
1.195     djm      1024:                if (*escape_pendingp) {
1.31      markus   1025:                        /* We have previously seen an escape character. */
                   1026:                        /* Clear the flag now. */
1.195     djm      1027:                        *escape_pendingp = 0;
1.31      markus   1028:
                   1029:                        /* Process the escaped character. */
                   1030:                        switch (ch) {
                   1031:                        case '.':
                   1032:                                /* Terminate the connection. */
1.195     djm      1033:                                snprintf(string, sizeof string, "%c.\r\n",
                   1034:                                    escape_char);
1.32      markus   1035:                                buffer_append(berr, string, strlen(string));
1.31      markus   1036:
1.217     djm      1037:                                if (c && c->ctl_chan != -1) {
1.195     djm      1038:                                        chan_read_failed(c);
                   1039:                                        chan_write_failed(c);
1.241   ! dtucker  1040:                                        mux_master_session_cleanup_cb(c->self,
        !          1041:                                            NULL);
1.195     djm      1042:                                        return 0;
                   1043:                                } else
                   1044:                                        quit_pending = 1;
1.31      markus   1045:                                return -1;
                   1046:
                   1047:                        case 'Z' - 64:
1.195     djm      1048:                                /* XXX support this for mux clients */
1.217     djm      1049:                                if (c && c->ctl_chan != -1) {
1.195     djm      1050:  noescape:
                   1051:                                        snprintf(string, sizeof string,
                   1052:                                            "%c%c escape not available to "
                   1053:                                            "multiplexed sessions\r\n",
                   1054:                                            escape_char, ch);
                   1055:                                        buffer_append(berr, string,
                   1056:                                            strlen(string));
                   1057:                                        continue;
                   1058:                                }
1.197     djm      1059:                                /* Suspend the program. Inform the user */
1.195     djm      1060:                                snprintf(string, sizeof string,
                   1061:                                    "%c^Z [suspend ssh]\r\n", escape_char);
1.32      markus   1062:                                buffer_append(berr, string, strlen(string));
1.31      markus   1063:
                   1064:                                /* Restore terminal modes and suspend. */
                   1065:                                client_suspend_self(bin, bout, berr);
                   1066:
                   1067:                                /* We have been continued. */
                   1068:                                continue;
                   1069:
1.111     markus   1070:                        case 'B':
                   1071:                                if (compat20) {
                   1072:                                        snprintf(string, sizeof string,
                   1073:                                            "%cB\r\n", escape_char);
                   1074:                                        buffer_append(berr, string,
                   1075:                                            strlen(string));
                   1076:                                        channel_request_start(session_ident,
                   1077:                                            "break", 0);
                   1078:                                        packet_put_int(1000);
                   1079:                                        packet_send();
                   1080:                                }
                   1081:                                continue;
                   1082:
1.54      markus   1083:                        case 'R':
1.59      markus   1084:                                if (compat20) {
                   1085:                                        if (datafellows & SSH_BUG_NOREKEY)
1.197     djm      1086:                                                logit("Server does not "
                   1087:                                                    "support re-keying");
1.59      markus   1088:                                        else
                   1089:                                                need_rekeying = 1;
                   1090:                                }
1.54      markus   1091:                                continue;
                   1092:
1.31      markus   1093:                        case '&':
1.217     djm      1094:                                if (c && c->ctl_chan != -1)
1.195     djm      1095:                                        goto noescape;
1.31      markus   1096:                                /*
1.197     djm      1097:                                 * Detach the program (continue to serve
                   1098:                                 * connections, but put in background and no
                   1099:                                 * more new connections).
1.31      markus   1100:                                 */
                   1101:                                /* Restore tty modes. */
1.233     djm      1102:                                leave_raw_mode(
                   1103:                                    options.request_tty == REQUEST_TTY_FORCE);
1.31      markus   1104:
                   1105:                                /* Stop listening for new connections. */
1.86      markus   1106:                                channel_stop_listening();
1.31      markus   1107:
1.86      markus   1108:                                snprintf(string, sizeof string,
                   1109:                                    "%c& [backgrounded]\n", escape_char);
                   1110:                                buffer_append(berr, string, strlen(string));
1.31      markus   1111:
                   1112:                                /* Fork into background. */
                   1113:                                pid = fork();
                   1114:                                if (pid < 0) {
                   1115:                                        error("fork: %.100s", strerror(errno));
                   1116:                                        continue;
                   1117:                                }
                   1118:                                if (pid != 0) { /* This is the parent. */
                   1119:                                        /* The parent just exits. */
                   1120:                                        exit(0);
                   1121:                                }
                   1122:                                /* The child continues serving connections. */
1.86      markus   1123:                                if (compat20) {
                   1124:                                        buffer_append(bin, "\004", 1);
                   1125:                                        /* fake EOF on stdin */
                   1126:                                        return -1;
                   1127:                                } else if (!stdin_eof) {
                   1128:                                        /*
1.197     djm      1129:                                         * Sending SSH_CMSG_EOF alone does not
                   1130:                                         * always appear to be enough.  So we
                   1131:                                         * try to send an EOF character first.
1.86      markus   1132:                                         */
                   1133:                                        packet_start(SSH_CMSG_STDIN_DATA);
                   1134:                                        packet_put_string("\004", 1);
                   1135:                                        packet_send();
                   1136:                                        /* Close stdin. */
                   1137:                                        stdin_eof = 1;
                   1138:                                        if (buffer_len(bin) == 0) {
                   1139:                                                packet_start(SSH_CMSG_EOF);
                   1140:                                                packet_send();
                   1141:                                        }
                   1142:                                }
                   1143:                                continue;
1.31      markus   1144:
                   1145:                        case '?':
1.217     djm      1146:                                if (c && c->ctl_chan != -1) {
1.195     djm      1147:                                        snprintf(string, sizeof string,
                   1148: "%c?\r\n\
                   1149: Supported escape sequences:\r\n\
                   1150:   %c.  - terminate session\r\n\
                   1151:   %cB  - send a BREAK to the remote system\r\n\
                   1152:   %cR  - Request rekey (SSH protocol 2 only)\r\n\
                   1153:   %c#  - list forwarded connections\r\n\
                   1154:   %c?  - this message\r\n\
                   1155:   %c%c  - send the escape character by typing it twice\r\n\
                   1156: (Note that escapes are only recognized immediately after newline.)\r\n",
                   1157:                                            escape_char, escape_char,
                   1158:                                            escape_char, escape_char,
                   1159:                                            escape_char, escape_char,
1.206     djm      1160:                                            escape_char, escape_char);
1.195     djm      1161:                                } else {
                   1162:                                        snprintf(string, sizeof string,
1.31      markus   1163: "%c?\r\n\
                   1164: Supported escape sequences:\r\n\
1.195     djm      1165:   %c.  - terminate connection (and any multiplexed sessions)\r\n\
                   1166:   %cB  - send a BREAK to the remote system\r\n\
                   1167:   %cC  - open a command line\r\n\
                   1168:   %cR  - Request rekey (SSH protocol 2 only)\r\n\
                   1169:   %c^Z - suspend ssh\r\n\
                   1170:   %c#  - list forwarded connections\r\n\
                   1171:   %c&  - background ssh (when waiting for connections to terminate)\r\n\
                   1172:   %c?  - this message\r\n\
                   1173:   %c%c  - send the escape character by typing it twice\r\n\
1.31      markus   1174: (Note that escapes are only recognized immediately after newline.)\r\n",
1.195     djm      1175:                                            escape_char, escape_char,
                   1176:                                            escape_char, escape_char,
                   1177:                                            escape_char, escape_char,
                   1178:                                            escape_char, escape_char,
                   1179:                                            escape_char, escape_char,
                   1180:                                            escape_char);
                   1181:                                }
1.32      markus   1182:                                buffer_append(berr, string, strlen(string));
1.31      markus   1183:                                continue;
                   1184:
                   1185:                        case '#':
1.195     djm      1186:                                snprintf(string, sizeof string, "%c#\r\n",
                   1187:                                    escape_char);
1.32      markus   1188:                                buffer_append(berr, string, strlen(string));
1.31      markus   1189:                                s = channel_open_message();
                   1190:                                buffer_append(berr, s, strlen(s));
                   1191:                                xfree(s);
1.97      jakob    1192:                                continue;
                   1193:
                   1194:                        case 'C':
1.217     djm      1195:                                if (c && c->ctl_chan != -1)
1.206     djm      1196:                                        goto noescape;
1.99      markus   1197:                                process_cmdline();
1.31      markus   1198:                                continue;
                   1199:
                   1200:                        default:
                   1201:                                if (ch != escape_char) {
                   1202:                                        buffer_put_char(bin, escape_char);
                   1203:                                        bytes++;
                   1204:                                }
                   1205:                                /* Escaped characters fall through here */
                   1206:                                break;
                   1207:                        }
                   1208:                } else {
                   1209:                        /*
1.197     djm      1210:                         * The previous character was not an escape char.
                   1211:                         * Check if this is an escape.
1.31      markus   1212:                         */
                   1213:                        if (last_was_cr && ch == escape_char) {
1.197     djm      1214:                                /*
                   1215:                                 * It is. Set the flag and continue to
                   1216:                                 * next character.
                   1217:                                 */
1.195     djm      1218:                                *escape_pendingp = 1;
1.31      markus   1219:                                continue;
                   1220:                        }
                   1221:                }
                   1222:
                   1223:                /*
                   1224:                 * Normal character.  Record whether it was a newline,
                   1225:                 * and append it to the buffer.
                   1226:                 */
                   1227:                last_was_cr = (ch == '\r' || ch == '\n');
                   1228:                buffer_put_char(bin, ch);
                   1229:                bytes++;
                   1230:        }
                   1231:        return bytes;
                   1232: }
                   1233:
1.77      itojun   1234: static void
1.161     deraadt  1235: client_process_input(fd_set *readset)
1.17      markus   1236: {
1.21      deraadt  1237:        int len;
1.31      markus   1238:        char buf[8192];
1.16      markus   1239:
1.11      markus   1240:        /* Read input from stdin. */
                   1241:        if (FD_ISSET(fileno(stdin), readset)) {
                   1242:                /* Read as much as possible. */
                   1243:                len = read(fileno(stdin), buf, sizeof(buf));
1.64      markus   1244:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
                   1245:                        return;         /* we'll try again later */
1.11      markus   1246:                if (len <= 0) {
1.13      markus   1247:                        /*
                   1248:                         * Received EOF or error.  They are treated
                   1249:                         * similarly, except that an error message is printed
                   1250:                         * if it was an error condition.
                   1251:                         */
1.11      markus   1252:                        if (len < 0) {
1.197     djm      1253:                                snprintf(buf, sizeof buf, "read: %.100s\r\n",
                   1254:                                    strerror(errno));
1.11      markus   1255:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1256:                        }
                   1257:                        /* Mark that we have seen EOF. */
                   1258:                        stdin_eof = 1;
1.13      markus   1259:                        /*
                   1260:                         * Send an EOF message to the server unless there is
                   1261:                         * data in the buffer.  If there is data in the
                   1262:                         * buffer, no message will be sent now.  Code
                   1263:                         * elsewhere will send the EOF when the buffer
                   1264:                         * becomes empty if stdin_eof is set.
                   1265:                         */
1.11      markus   1266:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt  1267:                                packet_start(SSH_CMSG_EOF);
                   1268:                                packet_send();
1.11      markus   1269:                        }
1.195     djm      1270:                } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1.13      markus   1271:                        /*
                   1272:                         * Normal successful read, and no escape character.
                   1273:                         * Just append the data to buffer.
                   1274:                         */
1.11      markus   1275:                        buffer_append(&stdin_buffer, buf, len);
                   1276:                } else {
1.13      markus   1277:                        /*
1.197     djm      1278:                         * Normal, successful read.  But we have an escape
                   1279:                         * character and have to process the characters one
                   1280:                         * by one.
1.13      markus   1281:                         */
1.195     djm      1282:                        if (process_escapes(NULL, &stdin_buffer,
                   1283:                            &stdout_buffer, &stderr_buffer, buf, len) == -1)
1.31      markus   1284:                                return;
1.11      markus   1285:                }
                   1286:        }
                   1287: }
                   1288:
1.77      itojun   1289: static void
1.161     deraadt  1290: client_process_output(fd_set *writeset)
1.11      markus   1291: {
                   1292:        int len;
                   1293:        char buf[100];
1.1       deraadt  1294:
1.11      markus   1295:        /* Write buffered output to stdout. */
                   1296:        if (FD_ISSET(fileno(stdout), writeset)) {
                   1297:                /* Write as much data as possible. */
                   1298:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1299:                    buffer_len(&stdout_buffer));
1.11      markus   1300:                if (len <= 0) {
1.64      markus   1301:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1302:                                len = 0;
                   1303:                        else {
1.13      markus   1304:                                /*
                   1305:                                 * An error or EOF was encountered.  Put an
                   1306:                                 * error message to stderr buffer.
                   1307:                                 */
1.197     djm      1308:                                snprintf(buf, sizeof buf,
                   1309:                                    "write stdout: %.50s\r\n", strerror(errno));
1.11      markus   1310:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1311:                                quit_pending = 1;
                   1312:                                return;
                   1313:                        }
                   1314:                }
                   1315:                /* Consume printed data from the buffer. */
                   1316:                buffer_consume(&stdout_buffer, len);
                   1317:        }
                   1318:        /* Write buffered output to stderr. */
                   1319:        if (FD_ISSET(fileno(stderr), writeset)) {
                   1320:                /* Write as much data as possible. */
                   1321:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1322:                    buffer_len(&stderr_buffer));
1.11      markus   1323:                if (len <= 0) {
1.64      markus   1324:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1325:                                len = 0;
                   1326:                        else {
1.197     djm      1327:                                /*
                   1328:                                 * EOF or error, but can't even print
                   1329:                                 * error message.
                   1330:                                 */
1.11      markus   1331:                                quit_pending = 1;
                   1332:                                return;
                   1333:                        }
                   1334:                }
                   1335:                /* Consume printed characters from the buffer. */
                   1336:                buffer_consume(&stderr_buffer, len);
                   1337:        }
1.1       deraadt  1338: }
                   1339:
1.13      markus   1340: /*
1.15      markus   1341:  * Get packets from the connection input buffer, and process them as long as
                   1342:  * there are packets available.
                   1343:  *
                   1344:  * Any unknown packets received during the actual
                   1345:  * session cause the session to terminate.  This is
                   1346:  * intended to make debugging easier since no
                   1347:  * confirmations are sent.  Any compatible protocol
                   1348:  * extensions must be negotiated during the
                   1349:  * preparatory phase.
                   1350:  */
                   1351:
1.77      itojun   1352: static void
1.49      itojun   1353: client_process_buffered_input_packets(void)
1.15      markus   1354: {
1.197     djm      1355:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
                   1356:            compat20 ? xxx_kex : NULL);
1.15      markus   1357: }
                   1358:
1.31      markus   1359: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1360:
1.195     djm      1361: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1362: void *
                   1363: client_new_escape_filter_ctx(int escape_char)
                   1364: {
                   1365:        struct escape_filter_ctx *ret;
                   1366:
                   1367:        ret = xmalloc(sizeof(*ret));
                   1368:        ret->escape_pending = 0;
                   1369:        ret->escape_char = escape_char;
                   1370:        return (void *)ret;
                   1371: }
                   1372:
1.198     djm      1373: /* Free the escape filter context on channel free */
                   1374: void
                   1375: client_filter_cleanup(int cid, void *ctx)
                   1376: {
                   1377:        xfree(ctx);
                   1378: }
                   1379:
1.195     djm      1380: int
                   1381: client_simple_escape_filter(Channel *c, char *buf, int len)
1.30      markus   1382: {
1.190     djm      1383:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1384:                return 0;
                   1385:
1.195     djm      1386:        return process_escapes(c, &c->input, &c->output, &c->extended,
                   1387:            buf, len);
1.30      markus   1388: }
                   1389:
1.77      itojun   1390: static void
1.60      markus   1391: client_channel_closed(int id, void *arg)
                   1392: {
1.83      markus   1393:        channel_cancel_cleanup(id);
1.60      markus   1394:        session_closed = 1;
1.233     djm      1395:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60      markus   1396: }
                   1397:
1.15      markus   1398: /*
1.13      markus   1399:  * Implements the interactive session with the server.  This is called after
                   1400:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1401:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1402:  * used as an escape character for terminating or suspending the session.
1.13      markus   1403:  */
1.1       deraadt  1404:
1.20      markus   1405: int
1.30      markus   1406: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1       deraadt  1407: {
1.46      markus   1408:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus   1409:        double start_time, total_time;
1.130     avsm     1410:        int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1.200     markus   1411:        u_int64_t ibytes, obytes;
1.130     avsm     1412:        u_int nalloc = 0;
1.11      markus   1413:        char buf[100];
                   1414:
                   1415:        debug("Entering interactive session.");
                   1416:
                   1417:        start_time = get_current_time();
                   1418:
                   1419:        /* Initialize variables. */
1.195     djm      1420:        escape_pending1 = 0;
1.11      markus   1421:        last_was_cr = 1;
                   1422:        exit_status = -1;
                   1423:        stdin_eof = 0;
                   1424:        buffer_high = 64 * 1024;
                   1425:        connection_in = packet_get_connection_in();
                   1426:        connection_out = packet_get_connection_out();
1.46      markus   1427:        max_fd = MAX(connection_in, connection_out);
                   1428:
                   1429:        if (!compat20) {
1.63      markus   1430:                /* enable nonblocking unless tty */
                   1431:                if (!isatty(fileno(stdin)))
                   1432:                        set_nonblock(fileno(stdin));
                   1433:                if (!isatty(fileno(stdout)))
                   1434:                        set_nonblock(fileno(stdout));
                   1435:                if (!isatty(fileno(stderr)))
                   1436:                        set_nonblock(fileno(stderr));
1.46      markus   1437:                max_fd = MAX(max_fd, fileno(stdin));
                   1438:                max_fd = MAX(max_fd, fileno(stdout));
                   1439:                max_fd = MAX(max_fd, fileno(stderr));
                   1440:        }
1.11      markus   1441:        quit_pending = 0;
1.195     djm      1442:        escape_char1 = escape_char_arg;
1.11      markus   1443:
                   1444:        /* Initialize buffers. */
                   1445:        buffer_init(&stdin_buffer);
                   1446:        buffer_init(&stdout_buffer);
                   1447:        buffer_init(&stderr_buffer);
                   1448:
1.15      markus   1449:        client_init_dispatch();
                   1450:
1.105     markus   1451:        /*
                   1452:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1453:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1454:         */
1.131     djm      1455:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1456:                signal(SIGHUP, signal_handler);
1.105     markus   1457:        if (signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1458:                signal(SIGINT, signal_handler);
                   1459:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1460:                signal(SIGQUIT, signal_handler);
                   1461:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1462:                signal(SIGTERM, signal_handler);
1.132     djm      1463:        signal(SIGWINCH, window_change_handler);
1.11      markus   1464:
                   1465:        if (have_pty)
1.233     djm      1466:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus   1467:
1.48      markus   1468:        if (compat20) {
                   1469:                session_ident = ssh2_chan_id;
1.232     djm      1470:                if (session_ident != -1) {
                   1471:                        if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
                   1472:                                channel_register_filter(session_ident,
                   1473:                                    client_simple_escape_filter, NULL,
                   1474:                                    client_filter_cleanup,
                   1475:                                    client_new_escape_filter_ctx(
                   1476:                                    escape_char_arg));
                   1477:                        }
1.60      markus   1478:                        channel_register_cleanup(session_ident,
1.143     djm      1479:                            client_channel_closed, 0);
1.232     djm      1480:                }
1.48      markus   1481:        } else {
                   1482:                /* Check if we should immediately send eof on stdin. */
1.16      markus   1483:                client_check_initial_eof_on_stdin();
1.48      markus   1484:        }
1.30      markus   1485:
1.11      markus   1486:        /* Main loop of the client for the interactive session mode. */
                   1487:        while (!quit_pending) {
                   1488:
1.13      markus   1489:                /* Process buffered packets sent by the server. */
1.11      markus   1490:                client_process_buffered_input_packets();
                   1491:
1.60      markus   1492:                if (compat20 && session_closed && !channel_still_open())
                   1493:                        break;
                   1494:
1.56      markus   1495:                rekeying = (xxx_kex != NULL && !xxx_kex->done);
1.16      markus   1496:
1.56      markus   1497:                if (rekeying) {
                   1498:                        debug("rekeying in progress");
                   1499:                } else {
                   1500:                        /*
                   1501:                         * Make packets of buffered stdin data, and buffer
                   1502:                         * them for sending to the server.
                   1503:                         */
                   1504:                        if (!compat20)
                   1505:                                client_make_packets_from_stdin_data();
1.11      markus   1506:
1.56      markus   1507:                        /*
                   1508:                         * Make packets from buffered channel data, and
                   1509:                         * enqueue them for sending to the server.
                   1510:                         */
                   1511:                        if (packet_not_very_much_data_to_write())
                   1512:                                channel_output_poll();
1.11      markus   1513:
1.56      markus   1514:                        /*
                   1515:                         * Check if the window size has changed, and buffer a
                   1516:                         * message about it to the server if so.
                   1517:                         */
                   1518:                        client_check_window_change();
1.11      markus   1519:
1.56      markus   1520:                        if (quit_pending)
                   1521:                                break;
                   1522:                }
1.13      markus   1523:                /*
                   1524:                 * Wait until we have something to do (something becomes
                   1525:                 * available on one of the descriptors).
                   1526:                 */
1.81      markus   1527:                max_fd2 = max_fd;
1.56      markus   1528:                client_wait_until_can_do_something(&readset, &writeset,
1.81      markus   1529:                    &max_fd2, &nalloc, rekeying);
1.11      markus   1530:
                   1531:                if (quit_pending)
                   1532:                        break;
                   1533:
1.56      markus   1534:                /* Do channel operations unless rekeying in progress. */
                   1535:                if (!rekeying) {
                   1536:                        channel_after_select(readset, writeset);
1.108     markus   1537:                        if (need_rekeying || packet_need_rekeying()) {
                   1538:                                debug("need rekeying");
1.56      markus   1539:                                xxx_kex->done = 0;
                   1540:                                kex_send_kexinit(xxx_kex);
                   1541:                                need_rekeying = 0;
                   1542:                        }
                   1543:                }
1.11      markus   1544:
1.17      markus   1545:                /* Buffer input from the connection.  */
1.46      markus   1546:                client_process_net_input(readset);
1.17      markus   1547:
                   1548:                if (quit_pending)
                   1549:                        break;
1.11      markus   1550:
1.17      markus   1551:                if (!compat20) {
                   1552:                        /* Buffer data from stdin */
1.46      markus   1553:                        client_process_input(readset);
1.17      markus   1554:                        /*
                   1555:                         * Process output to stdout and stderr.  Output to
                   1556:                         * the connection is processed elsewhere (above).
                   1557:                         */
1.46      markus   1558:                        client_process_output(writeset);
1.214     andreas  1559:                }
                   1560:
                   1561:                if (session_resumed) {
                   1562:                        connection_in = packet_get_connection_in();
                   1563:                        connection_out = packet_get_connection_out();
                   1564:                        max_fd = MAX(max_fd, connection_out);
                   1565:                        max_fd = MAX(max_fd, connection_in);
                   1566:                        session_resumed = 0;
1.17      markus   1567:                }
1.11      markus   1568:
1.197     djm      1569:                /*
                   1570:                 * Send as much buffered packet data as possible to the
                   1571:                 * sender.
                   1572:                 */
1.46      markus   1573:                if (FD_ISSET(connection_out, writeset))
1.11      markus   1574:                        packet_write_poll();
1.222     djm      1575:
                   1576:                /*
                   1577:                 * If we are a backgrounded control master, and the
                   1578:                 * timeout has expired without any active client
                   1579:                 * connections, then quit.
                   1580:                 */
                   1581:                if (control_persist_exit_time > 0) {
                   1582:                        if (time(NULL) >= control_persist_exit_time) {
                   1583:                                debug("ControlPersist timeout expired");
                   1584:                                break;
                   1585:                        }
                   1586:                }
1.11      markus   1587:        }
1.46      markus   1588:        if (readset)
                   1589:                xfree(readset);
                   1590:        if (writeset)
                   1591:                xfree(writeset);
1.11      markus   1592:
                   1593:        /* Terminate the session. */
                   1594:
                   1595:        /* Stop watching for window change. */
1.132     djm      1596:        signal(SIGWINCH, SIG_DFL);
1.211     andreas  1597:
1.213     stevesk  1598:        if (compat20) {
                   1599:                packet_start(SSH2_MSG_DISCONNECT);
                   1600:                packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
                   1601:                packet_put_cstring("disconnected by user");
1.219     djm      1602:                packet_put_cstring(""); /* language tag */
1.213     stevesk  1603:                packet_send();
                   1604:                packet_write_wait();
                   1605:        }
1.11      markus   1606:
1.76      markus   1607:        channel_free_all();
1.11      markus   1608:
1.75      markus   1609:        if (have_pty)
1.233     djm      1610:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.75      markus   1611:
                   1612:        /* restore blocking io */
                   1613:        if (!isatty(fileno(stdin)))
                   1614:                unset_nonblock(fileno(stdin));
                   1615:        if (!isatty(fileno(stdout)))
                   1616:                unset_nonblock(fileno(stdout));
                   1617:        if (!isatty(fileno(stderr)))
                   1618:                unset_nonblock(fileno(stderr));
1.116     dtucker  1619:
                   1620:        /*
                   1621:         * If there was no shell or command requested, there will be no remote
                   1622:         * exit status to be returned.  In that case, clear error code if the
                   1623:         * connection was deliberately terminated at this end.
                   1624:         */
                   1625:        if (no_shell_flag && received_signal == SIGTERM) {
                   1626:                received_signal = 0;
                   1627:                exit_status = 0;
                   1628:        }
1.75      markus   1629:
1.113     markus   1630:        if (received_signal)
1.89      itojun   1631:                fatal("Killed by signal %d.", (int) received_signal);
1.75      markus   1632:
1.13      markus   1633:        /*
                   1634:         * In interactive mode (with pseudo tty) display a message indicating
                   1635:         * that the connection has been closed.
                   1636:         */
1.11      markus   1637:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.197     djm      1638:                snprintf(buf, sizeof buf,
                   1639:                    "Connection to %.64s closed.\r\n", host);
1.11      markus   1640:                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1641:        }
1.70      markus   1642:
1.11      markus   1643:        /* Output any buffered data for stdout. */
1.231     djm      1644:        if (buffer_len(&stdout_buffer) > 0) {
1.230     djm      1645:                len = atomicio(vwrite, fileno(stdout),
                   1646:                    buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1.231     djm      1647:                if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1.11      markus   1648:                        error("Write failed flushing stdout buffer.");
1.231     djm      1649:                else
                   1650:                        buffer_consume(&stdout_buffer, len);
1.11      markus   1651:        }
                   1652:
                   1653:        /* Output any buffered data for stderr. */
1.231     djm      1654:        if (buffer_len(&stderr_buffer) > 0) {
1.230     djm      1655:                len = atomicio(vwrite, fileno(stderr),
                   1656:                    buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1.231     djm      1657:                if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1.11      markus   1658:                        error("Write failed flushing stderr buffer.");
1.231     djm      1659:                else
                   1660:                        buffer_consume(&stderr_buffer, len);
1.11      markus   1661:        }
                   1662:
                   1663:        /* Clear and free any buffers. */
                   1664:        memset(buf, 0, sizeof(buf));
                   1665:        buffer_free(&stdin_buffer);
                   1666:        buffer_free(&stdout_buffer);
                   1667:        buffer_free(&stderr_buffer);
                   1668:
                   1669:        /* Report bytes transferred, and transfer rates. */
                   1670:        total_time = get_current_time() - start_time;
1.200     markus   1671:        packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
                   1672:        packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
                   1673:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229     djm      1674:            (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11      markus   1675:        if (total_time > 0)
1.200     markus   1676:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1677:                    obytes / total_time, ibytes / total_time);
1.11      markus   1678:        /* Return the exit status of the program. */
                   1679:        debug("Exit status %d", exit_status);
                   1680:        return exit_status;
1.15      markus   1681: }
                   1682:
                   1683: /*********/
                   1684:
1.77      itojun   1685: static void
1.94      markus   1686: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1687: {
1.42      markus   1688:        u_int data_len;
1.15      markus   1689:        char *data = packet_get_string(&data_len);
1.93      markus   1690:        packet_check_eom();
1.15      markus   1691:        buffer_append(&stdout_buffer, data, data_len);
                   1692:        memset(data, 0, data_len);
                   1693:        xfree(data);
                   1694: }
1.77      itojun   1695: static void
1.94      markus   1696: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1697: {
1.42      markus   1698:        u_int data_len;
1.15      markus   1699:        char *data = packet_get_string(&data_len);
1.93      markus   1700:        packet_check_eom();
1.15      markus   1701:        buffer_append(&stderr_buffer, data, data_len);
                   1702:        memset(data, 0, data_len);
                   1703:        xfree(data);
                   1704: }
1.77      itojun   1705: static void
1.94      markus   1706: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15      markus   1707: {
                   1708:        exit_status = packet_get_int();
1.93      markus   1709:        packet_check_eom();
1.15      markus   1710:        /* Acknowledge the exit. */
                   1711:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                   1712:        packet_send();
                   1713:        /*
                   1714:         * Must wait for packet to be sent since we are
                   1715:         * exiting the loop.
                   1716:         */
                   1717:        packet_write_wait();
                   1718:        /* Flag that we want to exit. */
                   1719:        quit_pending = 1;
                   1720: }
1.115     markus   1721: static void
                   1722: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
                   1723: {
                   1724:        Channel *c = NULL;
                   1725:        int remote_id, sock;
                   1726:
                   1727:        /* Read the remote channel number from the message. */
                   1728:        remote_id = packet_get_int();
                   1729:        packet_check_eom();
                   1730:
                   1731:        /*
                   1732:         * Get a connection to the local authentication agent (this may again
                   1733:         * get forwarded).
                   1734:         */
                   1735:        sock = ssh_get_authentication_socket();
                   1736:
                   1737:        /*
                   1738:         * If we could not connect the agent, send an error message back to
                   1739:         * the server. This should never happen unless the agent dies,
                   1740:         * because authentication forwarding is only enabled if we have an
                   1741:         * agent.
                   1742:         */
                   1743:        if (sock >= 0) {
                   1744:                c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
                   1745:                    -1, 0, 0, 0, "authentication agent connection", 1);
                   1746:                c->remote_id = remote_id;
                   1747:                c->force_drain = 1;
                   1748:        }
                   1749:        if (c == NULL) {
                   1750:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1751:                packet_put_int(remote_id);
                   1752:        } else {
                   1753:                /* Send a confirmation to the remote host. */
                   1754:                debug("Forwarding authentication connection.");
                   1755:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1756:                packet_put_int(remote_id);
                   1757:                packet_put_int(c->self);
                   1758:        }
                   1759:        packet_send();
                   1760: }
1.15      markus   1761:
1.77      itojun   1762: static Channel *
1.40      markus   1763: client_request_forwarded_tcpip(const char *request_type, int rchan)
                   1764: {
1.103     deraadt  1765:        Channel *c = NULL;
1.40      markus   1766:        char *listen_address, *originator_address;
1.208     djm      1767:        u_short listen_port, originator_port;
1.40      markus   1768:
                   1769:        /* Get rest of the packet */
                   1770:        listen_address = packet_get_string(NULL);
                   1771:        listen_port = packet_get_int();
                   1772:        originator_address = packet_get_string(NULL);
                   1773:        originator_port = packet_get_int();
1.93      markus   1774:        packet_check_eom();
1.40      markus   1775:
1.191     djm      1776:        debug("client_request_forwarded_tcpip: listen %s port %d, "
                   1777:            "originator %s port %d", listen_address, listen_port,
                   1778:            originator_address, originator_port);
                   1779:
                   1780:        c = channel_connect_by_listen_address(listen_port,
                   1781:            "forwarded-tcpip", originator_address);
1.40      markus   1782:
                   1783:        xfree(originator_address);
                   1784:        xfree(listen_address);
                   1785:        return c;
                   1786: }
                   1787:
1.103     deraadt  1788: static Channel *
1.40      markus   1789: client_request_x11(const char *request_type, int rchan)
                   1790: {
                   1791:        Channel *c = NULL;
                   1792:        char *originator;
1.208     djm      1793:        u_short originator_port;
1.67      markus   1794:        int sock;
1.40      markus   1795:
                   1796:        if (!options.forward_x11) {
                   1797:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1798:                error("Warning: this is probably a break-in attempt by a "
                   1799:                    "malicious server.");
1.221     djm      1800:                return NULL;
                   1801:        }
                   1802:        if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
                   1803:                verbose("Rejected X11 connection after ForwardX11Timeout "
                   1804:                    "expired");
1.40      markus   1805:                return NULL;
                   1806:        }
                   1807:        originator = packet_get_string(NULL);
                   1808:        if (datafellows & SSH_BUG_X11FWD) {
                   1809:                debug2("buggy server: x11 request w/o originator_port");
                   1810:                originator_port = 0;
                   1811:        } else {
                   1812:                originator_port = packet_get_int();
                   1813:        }
1.93      markus   1814:        packet_check_eom();
1.40      markus   1815:        /* XXX check permission */
1.47      markus   1816:        debug("client_request_x11: request from %s %d", originator,
                   1817:            originator_port);
1.67      markus   1818:        xfree(originator);
1.40      markus   1819:        sock = x11_connect_display();
1.67      markus   1820:        if (sock < 0)
                   1821:                return NULL;
                   1822:        c = channel_new("x11",
                   1823:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1824:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1825:        c->force_drain = 1;
1.40      markus   1826:        return c;
                   1827: }
                   1828:
1.103     deraadt  1829: static Channel *
1.40      markus   1830: client_request_agent(const char *request_type, int rchan)
                   1831: {
                   1832:        Channel *c = NULL;
1.67      markus   1833:        int sock;
1.40      markus   1834:
                   1835:        if (!options.forward_agent) {
                   1836:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1837:                error("Warning: this is probably a break-in attempt by a "
                   1838:                    "malicious server.");
1.40      markus   1839:                return NULL;
                   1840:        }
1.177     stevesk  1841:        sock = ssh_get_authentication_socket();
1.67      markus   1842:        if (sock < 0)
                   1843:                return NULL;
                   1844:        c = channel_new("authentication agent connection",
                   1845:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1846:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1847:            "authentication agent connection", 1);
1.82      markus   1848:        c->force_drain = 1;
1.40      markus   1849:        return c;
1.180     djm      1850: }
                   1851:
                   1852: int
                   1853: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
                   1854: {
                   1855:        Channel *c;
                   1856:        int fd;
                   1857:
                   1858:        if (tun_mode == SSH_TUNMODE_NO)
                   1859:                return 0;
                   1860:
                   1861:        if (!compat20) {
1.207     stevesk  1862:                error("Tunnel forwarding is not supported for protocol 1");
1.180     djm      1863:                return -1;
                   1864:        }
                   1865:
                   1866:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1867:
                   1868:        /* Open local tunnel device */
                   1869:        if ((fd = tun_open(local_tun, tun_mode)) == -1) {
                   1870:                error("Tunnel device open failed.");
                   1871:                return -1;
                   1872:        }
                   1873:
                   1874:        c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
                   1875:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1876:        c->datagram = 1;
                   1877:
                   1878:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1879:        packet_put_cstring("tun@openssh.com");
                   1880:        packet_put_int(c->self);
                   1881:        packet_put_int(c->local_window_max);
                   1882:        packet_put_int(c->local_maxpacket);
                   1883:        packet_put_int(tun_mode);
                   1884:        packet_put_int(remote_tun);
                   1885:        packet_send();
                   1886:
                   1887:        return 0;
1.40      markus   1888: }
                   1889:
1.22      markus   1890: /* XXXX move to generic input handler */
1.77      itojun   1891: static void
1.94      markus   1892: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22      markus   1893: {
                   1894:        Channel *c = NULL;
                   1895:        char *ctype;
                   1896:        int rchan;
1.102     markus   1897:        u_int rmaxpack, rwindow, len;
1.22      markus   1898:
                   1899:        ctype = packet_get_string(&len);
                   1900:        rchan = packet_get_int();
                   1901:        rwindow = packet_get_int();
                   1902:        rmaxpack = packet_get_int();
                   1903:
1.24      markus   1904:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1905:            ctype, rchan, rwindow, rmaxpack);
                   1906:
1.40      markus   1907:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
                   1908:                c = client_request_forwarded_tcpip(ctype, rchan);
                   1909:        } else if (strcmp(ctype, "x11") == 0) {
                   1910:                c = client_request_x11(ctype, rchan);
                   1911:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
                   1912:                c = client_request_agent(ctype, rchan);
1.22      markus   1913:        }
                   1914: /* XXX duplicate : */
                   1915:        if (c != NULL) {
                   1916:                debug("confirm %s", ctype);
                   1917:                c->remote_id = rchan;
                   1918:                c->remote_window = rwindow;
                   1919:                c->remote_maxpacket = rmaxpack;
1.69      markus   1920:                if (c->type != SSH_CHANNEL_CONNECTING) {
                   1921:                        packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1922:                        packet_put_int(c->remote_id);
                   1923:                        packet_put_int(c->self);
                   1924:                        packet_put_int(c->local_window);
                   1925:                        packet_put_int(c->local_maxpacket);
                   1926:                        packet_send();
                   1927:                }
1.22      markus   1928:        } else {
                   1929:                debug("failure %s", ctype);
                   1930:                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   1931:                packet_put_int(rchan);
                   1932:                packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66      markus   1933:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69      markus   1934:                        packet_put_cstring("open failed");
1.66      markus   1935:                        packet_put_cstring("");
                   1936:                }
1.22      markus   1937:                packet_send();
                   1938:        }
                   1939:        xfree(ctype);
                   1940: }
1.77      itojun   1941: static void
1.94      markus   1942: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48      markus   1943: {
                   1944:        Channel *c = NULL;
1.123     djm      1945:        int exitval, id, reply, success = 0;
1.48      markus   1946:        char *rtype;
                   1947:
                   1948:        id = packet_get_int();
                   1949:        rtype = packet_get_string(NULL);
                   1950:        reply = packet_get_char();
                   1951:
                   1952:        debug("client_input_channel_req: channel %d rtype %s reply %d",
                   1953:            id, rtype, reply);
                   1954:
1.128     djm      1955:        if (id == -1) {
                   1956:                error("client_input_channel_req: request for channel -1");
                   1957:        } else if ((c = channel_lookup(id)) == NULL) {
1.197     djm      1958:                error("client_input_channel_req: channel %d: "
                   1959:                    "unknown channel", id);
1.193     markus   1960:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
                   1961:                packet_check_eom();
                   1962:                chan_rcvd_eow(c);
1.48      markus   1963:        } else if (strcmp(rtype, "exit-status") == 0) {
1.123     djm      1964:                exitval = packet_get_int();
1.217     djm      1965:                if (c->ctl_chan != -1) {
                   1966:                        mux_exit_message(c, exitval);
1.215     djm      1967:                        success = 1;
                   1968:                } else if (id == session_ident) {
                   1969:                        /* Record exit value of local session */
1.123     djm      1970:                        success = 1;
                   1971:                        exit_status = exitval;
1.215     djm      1972:                } else {
1.218     djm      1973:                        /* Probably for a mux channel that has already closed */
                   1974:                        debug("%s: no sink for exit-status on channel %d",
                   1975:                            __func__, id);
1.123     djm      1976:                }
1.93      markus   1977:                packet_check_eom();
1.48      markus   1978:        }
1.226     djm      1979:        if (reply && c != NULL) {
1.48      markus   1980:                packet_start(success ?
                   1981:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.205     markus   1982:                packet_put_int(c->remote_id);
1.48      markus   1983:                packet_send();
                   1984:        }
                   1985:        xfree(rtype);
                   1986: }
1.95      markus   1987: static void
                   1988: client_input_global_request(int type, u_int32_t seq, void *ctxt)
                   1989: {
                   1990:        char *rtype;
                   1991:        int want_reply;
                   1992:        int success = 0;
                   1993:
                   1994:        rtype = packet_get_string(NULL);
                   1995:        want_reply = packet_get_char();
1.117     markus   1996:        debug("client_input_global_request: rtype %s want_reply %d",
                   1997:            rtype, want_reply);
1.95      markus   1998:        if (want_reply) {
                   1999:                packet_start(success ?
                   2000:                    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
                   2001:                packet_send();
                   2002:                packet_write_wait();
                   2003:        }
                   2004:        xfree(rtype);
                   2005: }
1.22      markus   2006:
1.123     djm      2007: void
1.129     deraadt  2008: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190     djm      2009:     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123     djm      2010: {
                   2011:        int len;
1.132     djm      2012:        Channel *c = NULL;
1.123     djm      2013:
                   2014:        debug2("%s: id %d", __func__, id);
                   2015:
1.132     djm      2016:        if ((c = channel_lookup(id)) == NULL)
                   2017:                fatal("client_session2_setup: channel %d: unknown channel", id);
1.224     djm      2018:
                   2019:        packet_set_interactive(want_tty,
                   2020:            options.ip_qos_interactive, options.ip_qos_bulk);
1.132     djm      2021:
1.123     djm      2022:        if (want_tty) {
                   2023:                struct winsize ws;
                   2024:
                   2025:                /* Store window size in the packet. */
                   2026:                if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
                   2027:                        memset(&ws, 0, sizeof(ws));
                   2028:
1.190     djm      2029:                channel_request_start(id, "pty-req", 1);
1.234     djm      2030:                client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
1.123     djm      2031:                packet_put_cstring(term != NULL ? term : "");
1.158     deraadt  2032:                packet_put_int((u_int)ws.ws_col);
                   2033:                packet_put_int((u_int)ws.ws_row);
                   2034:                packet_put_int((u_int)ws.ws_xpixel);
                   2035:                packet_put_int((u_int)ws.ws_ypixel);
1.194     djm      2036:                if (tiop == NULL)
                   2037:                        tiop = get_saved_tio();
                   2038:                tty_make_modes(-1, tiop);
1.123     djm      2039:                packet_send();
                   2040:                /* XXX wait for reply */
1.132     djm      2041:                c->client_tty = 1;
1.123     djm      2042:        }
                   2043:
                   2044:        /* Transfer any environment variables from client to server */
1.126     djm      2045:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      2046:                int i, j, matched;
                   2047:                char *name, *val;
                   2048:
                   2049:                debug("Sending environment.");
1.126     djm      2050:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      2051:                        /* Split */
1.126     djm      2052:                        name = xstrdup(env[i]);
1.123     djm      2053:                        if ((val = strchr(name, '=')) == NULL) {
1.144     stevesk  2054:                                xfree(name);
1.123     djm      2055:                                continue;
                   2056:                        }
                   2057:                        *val++ = '\0';
                   2058:
                   2059:                        matched = 0;
                   2060:                        for (j = 0; j < options.num_send_env; j++) {
                   2061:                                if (match_pattern(name, options.send_env[j])) {
                   2062:                                        matched = 1;
                   2063:                                        break;
                   2064:                                }
                   2065:                        }
                   2066:                        if (!matched) {
                   2067:                                debug3("Ignored env %s", name);
1.144     stevesk  2068:                                xfree(name);
1.123     djm      2069:                                continue;
                   2070:                        }
                   2071:
                   2072:                        debug("Sending env %s = %s", name, val);
                   2073:                        channel_request_start(id, "env", 0);
                   2074:                        packet_put_cstring(name);
                   2075:                        packet_put_cstring(val);
                   2076:                        packet_send();
1.144     stevesk  2077:                        xfree(name);
1.123     djm      2078:                }
                   2079:        }
                   2080:
                   2081:        len = buffer_len(cmd);
                   2082:        if (len > 0) {
                   2083:                if (len > 900)
                   2084:                        len = 900;
                   2085:                if (want_subsystem) {
1.190     djm      2086:                        debug("Sending subsystem: %.*s",
                   2087:                            len, (u_char*)buffer_ptr(cmd));
                   2088:                        channel_request_start(id, "subsystem", 1);
1.234     djm      2089:                        client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
1.123     djm      2090:                } else {
1.190     djm      2091:                        debug("Sending command: %.*s",
                   2092:                            len, (u_char*)buffer_ptr(cmd));
                   2093:                        channel_request_start(id, "exec", 1);
1.234     djm      2094:                        client_expect_confirm(id, "exec", CONFIRM_CLOSE);
1.123     djm      2095:                }
                   2096:                packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
                   2097:                packet_send();
                   2098:        } else {
1.190     djm      2099:                channel_request_start(id, "shell", 1);
1.234     djm      2100:                client_expect_confirm(id, "shell", CONFIRM_CLOSE);
1.123     djm      2101:                packet_send();
                   2102:        }
                   2103: }
                   2104:
1.77      itojun   2105: static void
1.49      itojun   2106: client_init_dispatch_20(void)
1.16      markus   2107: {
1.55      markus   2108:        dispatch_init(&dispatch_protocol_error);
1.100     markus   2109:
1.16      markus   2110:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   2111:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   2112:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   2113:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22      markus   2114:        dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16      markus   2115:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2116:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48      markus   2117:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16      markus   2118:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189     djm      2119:        dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2120:        dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95      markus   2121:        dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2122:
                   2123:        /* rekeying */
                   2124:        dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2125:
                   2126:        /* global request reply messages */
                   2127:        dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2128:        dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16      markus   2129: }
1.197     djm      2130:
1.77      itojun   2131: static void
1.49      itojun   2132: client_init_dispatch_13(void)
1.15      markus   2133: {
                   2134:        dispatch_init(NULL);
                   2135:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                   2136:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                   2137:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                   2138:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2139:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2140:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                   2141:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                   2142:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                   2143:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39      markus   2144:
                   2145:        dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115     markus   2146:            &client_input_agent_open : &deny_input_open);
1.39      markus   2147:        dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
                   2148:            &x11_input_open : &deny_input_open);
1.15      markus   2149: }
1.197     djm      2150:
1.77      itojun   2151: static void
1.49      itojun   2152: client_init_dispatch_15(void)
1.15      markus   2153: {
                   2154:        client_init_dispatch_13();
                   2155:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                   2156:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                   2157: }
1.197     djm      2158:
1.79      stevesk  2159: static void
1.49      itojun   2160: client_init_dispatch(void)
1.15      markus   2161: {
1.16      markus   2162:        if (compat20)
                   2163:                client_init_dispatch_20();
                   2164:        else if (compat13)
1.15      markus   2165:                client_init_dispatch_13();
                   2166:        else
                   2167:                client_init_dispatch_15();
1.232     djm      2168: }
                   2169:
                   2170: void
                   2171: client_stop_mux(void)
                   2172: {
                   2173:        if (options.control_path != NULL && muxserver_sock != -1)
                   2174:                unlink(options.control_path);
                   2175:        /*
                   2176:         * If we are in persist mode, signal that we should close when all
                   2177:         * active channels are closed.
                   2178:         */
1.235     djm      2179:        if (options.control_persist) {
1.232     djm      2180:                session_closed = 1;
1.235     djm      2181:                setproctitle("[stopped mux]");
                   2182:        }
1.113     markus   2183: }
                   2184:
                   2185: /* client specific fatal cleanup */
                   2186: void
1.114     markus   2187: cleanup_exit(int i)
1.113     markus   2188: {
1.233     djm      2189:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.113     markus   2190:        leave_non_blocking();
1.192     djm      2191:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2192:                unlink(options.control_path);
1.223     djm      2193:        ssh_kill_proxy_command();
1.114     markus   2194:        _exit(i);
1.1       deraadt  2195: }