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

1.274   ! djm         1: /* $OpenBSD: clientloop.c,v 1.273 2015/05/04 06:10:48 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.266     deraadt    63: #include <sys/param.h> /* MIN MAX */
1.175     deraadt    64: #include <sys/types.h>
1.152     stevesk    65: #include <sys/ioctl.h>
1.154     stevesk    66: #include <sys/stat.h>
1.166     stevesk    67: #include <sys/socket.h>
1.171     stevesk    68: #include <sys/time.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.266     deraadt    81: #include <limits.h>
1.1       deraadt    82:
1.175     deraadt    83: #include "xmalloc.h"
1.45      markus     84: #include "ssh.h"
                     85: #include "ssh1.h"
                     86: #include "ssh2.h"
1.1       deraadt    87: #include "packet.h"
                     88: #include "buffer.h"
1.15      markus     89: #include "compat.h"
1.74      markus     90: #include "channels.h"
1.15      markus     91: #include "dispatch.h"
1.40      markus     92: #include "key.h"
1.175     deraadt    93: #include "cipher.h"
1.54      markus     94: #include "kex.h"
1.45      markus     95: #include "log.h"
1.261     millert    96: #include "misc.h"
1.45      markus     97: #include "readconf.h"
                     98: #include "clientloop.h"
1.147     djm        99: #include "sshconnect.h"
1.40      markus    100: #include "authfd.h"
1.45      markus    101: #include "atomicio.h"
1.118     deraadt   102: #include "sshpty.h"
1.123     djm       103: #include "match.h"
                    104: #include "msg.h"
1.212     andreas   105: #include "roaming.h"
1.262     djm       106: #include "ssherr.h"
1.267     djm       107: #include "hostfile.h"
1.39      markus    108:
                    109: /* import options */
                    110: extern Options options;
                    111:
1.1       deraadt   112: /* Flag indicating that stdin should be redirected from /dev/null. */
                    113: extern int stdin_null_flag;
                    114:
1.116     dtucker   115: /* Flag indicating that no shell has been requested */
                    116: extern int no_shell_flag;
                    117:
1.123     djm       118: /* Control socket */
1.217     djm       119: extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
1.123     djm       120:
1.13      markus    121: /*
                    122:  * Name of the host we are connecting to.  This is the name given on the
                    123:  * command line, or the HostName specified for the user-supplied name in a
                    124:  * configuration file.
                    125:  */
1.1       deraadt   126: extern char *host;
                    127:
1.13      markus    128: /*
                    129:  * Flag to indicate that we have received a window change signal which has
                    130:  * not yet been processed.  This will cause a message indicating the new
                    131:  * window size to be sent to the server a little later.  This is volatile
                    132:  * because this is updated in a signal handler.
                    133:  */
1.88      markus    134: static volatile sig_atomic_t received_window_change_signal = 0;
                    135: static volatile sig_atomic_t received_signal = 0;
1.1       deraadt   136:
1.145     djm       137: /* Flag indicating whether the user's terminal is in non-blocking mode. */
1.1       deraadt   138: static int in_non_blocking_mode = 0;
                    139:
1.222     djm       140: /* Time when backgrounded control master using ControlPersist should exit */
                    141: static time_t control_persist_exit_time = 0;
                    142:
1.1       deraadt   143: /* Common data for the client loop code. */
1.217     djm       144: volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
1.195     djm       145: static int escape_char1;       /* Escape character. (proto1 only) */
                    146: static int escape_pending1;    /* Last character was an escape (proto1 only) */
1.11      markus    147: static int last_was_cr;                /* Last character was a newline. */
1.197     djm       148: static int exit_status;                /* Used to store the command exit status. */
                    149: static int stdin_eof;          /* EOF has been encountered on stderr. */
1.11      markus    150: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                    151: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                    152: static Buffer stderr_buffer;   /* Buffer for stderr data. */
1.221     djm       153: static u_int buffer_high;      /* Soft max buffer size. */
1.11      markus    154: static int connection_in;      /* Connection to server (input). */
                    155: static int connection_out;     /* Connection to server (output). */
1.56      markus    156: static int need_rekeying;      /* Set to non-zero if rekeying is requested. */
1.221     djm       157: static int session_closed;     /* In SSH2: login session closed. */
1.274   ! djm       158: static u_int x11_refuse_time;  /* If >0, refuse x11 opens after this time. */
1.1       deraadt   159:
1.77      itojun    160: static void client_init_dispatch(void);
1.16      markus    161: int    session_ident = -1;
                    162:
1.214     andreas   163: int    session_resumed = 0;
                    164:
1.195     djm       165: /* Track escape per proto2 channel */
                    166: struct escape_filter_ctx {
                    167:        int escape_pending;
                    168:        int escape_char;
                    169: };
                    170:
                    171: /* Context for channel confirmation replies */
1.190     djm       172: struct channel_reply_ctx {
                    173:        const char *request_type;
1.234     djm       174:        int id;
                    175:        enum confirm_action action;
1.190     djm       176: };
                    177:
1.196     djm       178: /* Global request success/failure callbacks */
                    179: struct global_confirm {
                    180:        TAILQ_ENTRY(global_confirm) entry;
                    181:        global_confirm_cb *cb;
                    182:        void *ctx;
                    183:        int ref_count;
                    184: };
                    185: TAILQ_HEAD(global_confirms, global_confirm);
                    186: static struct global_confirms global_confirms =
                    187:     TAILQ_HEAD_INITIALIZER(global_confirms);
                    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 */
1.251     dtucker   268:                control_persist_exit_time = monotime() +
1.222     djm       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++) {
1.256     deraadt   284:                if (!isalnum((u_char)display[i]) &&
1.238     dtucker   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.274   ! djm       293: #define SSH_X11_PROTO          "MIT-MAGIC-COOKIE-1"
        !           294: #define X11_TIMEOUT_SLACK      60
1.138     djm       295: void
                    296: client_x11_get_proto(const char *display, const char *xauth_path,
1.221     djm       297:     u_int trusted, u_int timeout, char **_proto, char **_data)
1.138     djm       298: {
                    299:        char cmd[1024];
                    300:        char line[512];
                    301:        char xdisplay[512];
                    302:        static char proto[512], data[512];
                    303:        FILE *f;
                    304:        int got_data = 0, generated = 0, do_unlink = 0, i;
                    305:        char *xauthdir, *xauthfile;
                    306:        struct stat st;
1.274   ! djm       307:        u_int now, x11_timeout_real;
1.138     djm       308:
                    309:        xauthdir = xauthfile = NULL;
                    310:        *_proto = proto;
                    311:        *_data = data;
                    312:        proto[0] = data[0] = '\0';
                    313:
                    314:        if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
                    315:                debug("No xauth program.");
1.238     dtucker   316:        } else if (!client_x11_display_valid(display)) {
                    317:                logit("DISPLAY '%s' invalid, falling back to fake xauth data",
                    318:                    display);
1.138     djm       319:        } else {
                    320:                if (display == NULL) {
                    321:                        debug("x11_get_proto: DISPLAY not set");
                    322:                        return;
                    323:                }
                    324:                /*
                    325:                 * Handle FamilyLocal case where $DISPLAY does
                    326:                 * not match an authorization entry.  For this we
                    327:                 * just try "xauth list unix:displaynum.screennum".
                    328:                 * XXX: "localhost" match to determine FamilyLocal
                    329:                 *      is not perfect.
                    330:                 */
                    331:                if (strncmp(display, "localhost:", 10) == 0) {
                    332:                        snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
                    333:                            display + 10);
                    334:                        display = xdisplay;
                    335:                }
                    336:                if (trusted == 0) {
1.266     deraadt   337:                        xauthdir = xmalloc(PATH_MAX);
                    338:                        xauthfile = xmalloc(PATH_MAX);
                    339:                        mktemp_proto(xauthdir, PATH_MAX);
1.274   ! djm       340:                        /*
        !           341:                         * The authentication cookie should briefly outlive
        !           342:                         * ssh's willingness to forward X11 connections to
        !           343:                         * avoid nasty fail-open behaviour in the X server.
        !           344:                         */
        !           345:                        if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
        !           346:                                x11_timeout_real = UINT_MAX;
        !           347:                        else
        !           348:                                x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
1.138     djm       349:                        if (mkdtemp(xauthdir) != NULL) {
                    350:                                do_unlink = 1;
1.266     deraadt   351:                                snprintf(xauthfile, PATH_MAX, "%s/xauthfile",
1.138     djm       352:                                    xauthdir);
                    353:                                snprintf(cmd, sizeof(cmd),
                    354:                                    "%s -f %s generate %s " SSH_X11_PROTO
1.221     djm       355:                                    " untrusted timeout %u 2>" _PATH_DEVNULL,
1.274   ! djm       356:                                    xauth_path, xauthfile, display,
        !           357:                                    x11_timeout_real);
1.138     djm       358:                                debug2("x11_get_proto: %s", cmd);
1.221     djm       359:                                if (x11_refuse_time == 0) {
1.251     dtucker   360:                                        now = monotime() + 1;
1.221     djm       361:                                        if (UINT_MAX - timeout < now)
                    362:                                                x11_refuse_time = UINT_MAX;
                    363:                                        else
                    364:                                                x11_refuse_time = now + timeout;
1.274   ! djm       365:                                        channel_set_x11_refuse_time(
        !           366:                                            x11_refuse_time);
1.221     djm       367:                                }
1.274   ! djm       368:                                if (system(cmd) == 0)
        !           369:                                        generated = 1;
1.138     djm       370:                        }
                    371:                }
1.181     markus    372:
                    373:                /*
                    374:                 * When in untrusted mode, we read the cookie only if it was
                    375:                 * successfully generated as an untrusted one in the step
                    376:                 * above.
                    377:                 */
                    378:                if (trusted || generated) {
                    379:                        snprintf(cmd, sizeof(cmd),
                    380:                            "%s %s%s list %s 2>" _PATH_DEVNULL,
                    381:                            xauth_path,
                    382:                            generated ? "-f " : "" ,
                    383:                            generated ? xauthfile : "",
                    384:                            display);
                    385:                        debug2("x11_get_proto: %s", cmd);
                    386:                        f = popen(cmd, "r");
                    387:                        if (f && fgets(line, sizeof(line), f) &&
                    388:                            sscanf(line, "%*s %511s %511s", proto, data) == 2)
                    389:                                got_data = 1;
                    390:                        if (f)
                    391:                                pclose(f);
                    392:                } else
                    393:                        error("Warning: untrusted X11 forwarding setup failed: "
                    394:                            "xauth key data not generated");
1.138     djm       395:        }
                    396:
                    397:        if (do_unlink) {
                    398:                unlink(xauthfile);
                    399:                rmdir(xauthdir);
                    400:        }
1.250     djm       401:        free(xauthdir);
                    402:        free(xauthfile);
1.138     djm       403:
                    404:        /*
                    405:         * If we didn't get authentication data, just make up some
                    406:         * data.  The forwarding code will check the validity of the
                    407:         * response anyway, and substitute this data.  The X11
                    408:         * server, however, will ignore this fake data and use
                    409:         * whatever authentication mechanisms it was using otherwise
                    410:         * for the local connection.
                    411:         */
                    412:        if (!got_data) {
                    413:                u_int32_t rnd = 0;
                    414:
                    415:                logit("Warning: No xauth data; "
                    416:                    "using fake authentication data for X11 forwarding.");
                    417:                strlcpy(proto, SSH_X11_PROTO, sizeof proto);
                    418:                for (i = 0; i < 16; i++) {
                    419:                        if (i % 4 == 0)
                    420:                                rnd = arc4random();
                    421:                        snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
                    422:                            rnd & 0xff);
                    423:                        rnd >>= 8;
                    424:                }
                    425:        }
1.1       deraadt   426: }
                    427:
1.13      markus    428: /*
                    429:  * This is called when the interactive is entered.  This checks if there is
                    430:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    431:  * not appear to wake up when redirecting from /dev/null.
                    432:  */
1.1       deraadt   433:
1.77      itojun    434: static void
1.49      itojun    435: client_check_initial_eof_on_stdin(void)
1.1       deraadt   436: {
1.11      markus    437:        int len;
                    438:        char buf[1];
1.1       deraadt   439:
1.13      markus    440:        /*
                    441:         * If standard input is to be "redirected from /dev/null", we simply
                    442:         * mark that we have seen an EOF and send an EOF message to the
                    443:         * server. Otherwise, we try to read a single character; it appears
                    444:         * that for some files, such /dev/null, select() never wakes up for
                    445:         * read for this descriptor, which means that we never get EOF.  This
                    446:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    447:         */
1.11      markus    448:        if (stdin_null_flag) {
                    449:                /* Fake EOF on stdin. */
                    450:                debug("Sending eof.");
                    451:                stdin_eof = 1;
                    452:                packet_start(SSH_CMSG_EOF);
                    453:                packet_send();
                    454:        } else {
                    455:                enter_non_blocking();
                    456:
                    457:                /* Check for immediate EOF on stdin. */
                    458:                len = read(fileno(stdin), buf, 1);
                    459:                if (len == 0) {
1.197     djm       460:                        /*
                    461:                         * EOF.  Record that we have seen it and send
                    462:                         * EOF to server.
                    463:                         */
1.11      markus    464:                        debug("Sending eof.");
                    465:                        stdin_eof = 1;
                    466:                        packet_start(SSH_CMSG_EOF);
                    467:                        packet_send();
                    468:                } else if (len > 0) {
1.13      markus    469:                        /*
                    470:                         * Got data.  We must store the data in the buffer,
                    471:                         * and also process it as an escape character if
                    472:                         * appropriate.
                    473:                         */
1.195     djm       474:                        if ((u_char) buf[0] == escape_char1)
                    475:                                escape_pending1 = 1;
1.52      markus    476:                        else
1.11      markus    477:                                buffer_append(&stdin_buffer, buf, 1);
                    478:                }
                    479:                leave_non_blocking();
                    480:        }
1.1       deraadt   481: }
                    482:
                    483:
1.13      markus    484: /*
                    485:  * Make packets from buffered stdin data, and buffer them for sending to the
                    486:  * connection.
                    487:  */
1.1       deraadt   488:
1.77      itojun    489: static void
1.49      itojun    490: client_make_packets_from_stdin_data(void)
1.1       deraadt   491: {
1.42      markus    492:        u_int len;
1.1       deraadt   493:
1.11      markus    494:        /* Send buffered stdin data to the server. */
                    495:        while (buffer_len(&stdin_buffer) > 0 &&
1.90      deraadt   496:            packet_not_very_much_data_to_write()) {
1.11      markus    497:                len = buffer_len(&stdin_buffer);
                    498:                /* Keep the packets at reasonable size. */
                    499:                if (len > packet_get_maxsize())
                    500:                        len = packet_get_maxsize();
                    501:                packet_start(SSH_CMSG_STDIN_DATA);
                    502:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    503:                packet_send();
                    504:                buffer_consume(&stdin_buffer, len);
                    505:                /* If we have a pending EOF, send it now. */
                    506:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    507:                        packet_start(SSH_CMSG_EOF);
                    508:                        packet_send();
                    509:                }
1.1       deraadt   510:        }
                    511: }
                    512:
1.13      markus    513: /*
                    514:  * Checks if the client window has changed, and sends a packet about it to
                    515:  * the server if so.  The actual change is detected elsewhere (by a software
                    516:  * interrupt on Unix); this just checks the flag and sends a message if
                    517:  * appropriate.
                    518:  */
1.1       deraadt   519:
1.77      itojun    520: static void
1.49      itojun    521: client_check_window_change(void)
1.1       deraadt   522: {
1.16      markus    523:        struct winsize ws;
                    524:
                    525:        if (! received_window_change_signal)
                    526:                return;
                    527:        /** XXX race */
                    528:        received_window_change_signal = 0;
                    529:
1.37      markus    530:        debug2("client_check_window_change: changed");
1.16      markus    531:
                    532:        if (compat20) {
1.123     djm       533:                channel_send_window_changes();
1.16      markus    534:        } else {
1.123     djm       535:                if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
                    536:                        return;
1.16      markus    537:                packet_start(SSH_CMSG_WINDOW_SIZE);
1.158     deraadt   538:                packet_put_int((u_int)ws.ws_row);
                    539:                packet_put_int((u_int)ws.ws_col);
                    540:                packet_put_int((u_int)ws.ws_xpixel);
                    541:                packet_put_int((u_int)ws.ws_ypixel);
1.16      markus    542:                packet_send();
1.1       deraadt   543:        }
                    544: }
                    545:
1.264     markus    546: static int
1.117     markus    547: client_global_request_reply(int type, u_int32_t seq, void *ctxt)
                    548: {
1.196     djm       549:        struct global_confirm *gc;
                    550:
                    551:        if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
1.264     markus    552:                return 0;
1.196     djm       553:        if (gc->cb != NULL)
                    554:                gc->cb(type, seq, gc->ctx);
                    555:        if (--gc->ref_count <= 0) {
                    556:                TAILQ_REMOVE(&global_confirms, gc, entry);
1.257     tedu      557:                explicit_bzero(gc, sizeof(*gc));
1.250     djm       558:                free(gc);
1.196     djm       559:        }
                    560:
1.210     andreas   561:        packet_set_alive_timeouts(0);
1.264     markus    562:        return 0;
1.117     markus    563: }
                    564:
                    565: static void
                    566: server_alive_check(void)
                    567: {
1.210     andreas   568:        if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
1.228     djm       569:                logit("Timeout, server %s not responding.", host);
1.176     markus    570:                cleanup_exit(255);
                    571:        }
1.117     markus    572:        packet_start(SSH2_MSG_GLOBAL_REQUEST);
                    573:        packet_put_cstring("keepalive@openssh.com");
                    574:        packet_put_char(1);     /* boolean: want reply */
                    575:        packet_send();
1.196     djm       576:        /* Insert an empty placeholder to maintain ordering */
                    577:        client_register_global_confirm(NULL, NULL);
1.117     markus    578: }
                    579:
1.13      markus    580: /*
                    581:  * Waits until the client can do something (some data becomes available on
                    582:  * one of the file descriptors).
                    583:  */
1.77      itojun    584: static void
1.46      markus    585: client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
1.130     avsm      586:     int *maxfdp, u_int *nallocp, int rekeying)
1.11      markus    587: {
1.117     markus    588:        struct timeval tv, *tvp;
1.222     djm       589:        int timeout_secs;
1.251     dtucker   590:        time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
1.117     markus    591:        int ret;
                    592:
1.46      markus    593:        /* Add any selections by the channel mechanism. */
1.239     djm       594:        channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
                    595:            &minwait_secs, rekeying);
1.11      markus    596:
1.16      markus    597:        if (!compat20) {
1.17      markus    598:                /* Read from the connection, unless our buffers are full. */
1.16      markus    599:                if (buffer_len(&stdout_buffer) < buffer_high &&
                    600:                    buffer_len(&stderr_buffer) < buffer_high &&
                    601:                    channel_not_very_much_buffered_data())
1.46      markus    602:                        FD_SET(connection_in, *readsetp);
1.17      markus    603:                /*
                    604:                 * Read from stdin, unless we have seen EOF or have very much
                    605:                 * buffered data to send to the server.
                    606:                 */
                    607:                if (!stdin_eof && packet_not_very_much_data_to_write())
1.46      markus    608:                        FD_SET(fileno(stdin), *readsetp);
1.17      markus    609:
                    610:                /* Select stdout/stderr if have data in buffer. */
                    611:                if (buffer_len(&stdout_buffer) > 0)
1.46      markus    612:                        FD_SET(fileno(stdout), *writesetp);
1.17      markus    613:                if (buffer_len(&stderr_buffer) > 0)
1.46      markus    614:                        FD_SET(fileno(stderr), *writesetp);
1.16      markus    615:        } else {
1.71      markus    616:                /* channel_prepare_select could have closed the last channel */
1.84      markus    617:                if (session_closed && !channel_still_open() &&
                    618:                    !packet_have_data_to_write()) {
                    619:                        /* clear mask since we did not call select() */
1.87      markus    620:                        memset(*readsetp, 0, *nallocp);
                    621:                        memset(*writesetp, 0, *nallocp);
1.84      markus    622:                        return;
1.71      markus    623:                } else {
                    624:                        FD_SET(connection_in, *readsetp);
                    625:                }
1.16      markus    626:        }
1.11      markus    627:
                    628:        /* Select server connection if have data to write to the server. */
                    629:        if (packet_have_data_to_write())
1.46      markus    630:                FD_SET(connection_out, *writesetp);
1.11      markus    631:
1.13      markus    632:        /*
                    633:         * Wait for something to happen.  This will suspend the process until
                    634:         * some selected descriptor can be read, written, or has some other
1.222     djm       635:         * event pending, or a timeout expires.
1.13      markus    636:         */
1.11      markus    637:
1.222     djm       638:        timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
1.249     dtucker   639:        if (options.server_alive_interval > 0 && compat20) {
1.222     djm       640:                timeout_secs = options.server_alive_interval;
1.249     dtucker   641:                server_alive_time = now + options.server_alive_interval;
                    642:        }
                    643:        if (options.rekey_interval > 0 && compat20 && !rekeying)
                    644:                timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
1.222     djm       645:        set_control_persist_exit_time();
                    646:        if (control_persist_exit_time > 0) {
                    647:                timeout_secs = MIN(timeout_secs,
1.249     dtucker   648:                        control_persist_exit_time - now);
1.222     djm       649:                if (timeout_secs < 0)
                    650:                        timeout_secs = 0;
                    651:        }
1.239     djm       652:        if (minwait_secs != 0)
                    653:                timeout_secs = MIN(timeout_secs, (int)minwait_secs);
1.222     djm       654:        if (timeout_secs == INT_MAX)
1.117     markus    655:                tvp = NULL;
1.129     deraadt   656:        else {
1.222     djm       657:                tv.tv_sec = timeout_secs;
1.117     markus    658:                tv.tv_usec = 0;
                    659:                tvp = &tv;
                    660:        }
1.222     djm       661:
1.117     markus    662:        ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
                    663:        if (ret < 0) {
1.11      markus    664:                char buf[100];
1.51      markus    665:
                    666:                /*
                    667:                 * We have to clear the select masks, because we return.
                    668:                 * We have to return, because the mainloop checks for the flags
                    669:                 * set by the signal handlers.
                    670:                 */
1.87      markus    671:                memset(*readsetp, 0, *nallocp);
                    672:                memset(*writesetp, 0, *nallocp);
1.50      deraadt   673:
1.11      markus    674:                if (errno == EINTR)
                    675:                        return;
                    676:                /* Note: we might still have data in the buffers. */
                    677:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    678:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    679:                quit_pending = 1;
1.249     dtucker   680:        } else if (ret == 0) {
                    681:                /*
                    682:                 * Timeout.  Could have been either keepalive or rekeying.
                    683:                 * Keepalive we check here, rekeying is checked in clientloop.
                    684:                 */
1.251     dtucker   685:                if (server_alive_time != 0 && server_alive_time <= monotime())
1.249     dtucker   686:                        server_alive_check();
                    687:        }
                    688:
1.11      markus    689: }
                    690:
1.77      itojun    691: static void
1.31      markus    692: client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
1.1       deraadt   693: {
1.11      markus    694:        /* Flush stdout and stderr buffers. */
1.31      markus    695:        if (buffer_len(bout) > 0)
1.197     djm       696:                atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
                    697:                    buffer_len(bout));
1.31      markus    698:        if (buffer_len(berr) > 0)
1.197     djm       699:                atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
                    700:                    buffer_len(berr));
1.11      markus    701:
1.233     djm       702:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    703:
1.13      markus    704:        /*
                    705:         * Free (and clear) the buffer to reduce the amount of data that gets
                    706:         * written to swap.
                    707:         */
1.31      markus    708:        buffer_free(bin);
                    709:        buffer_free(bout);
                    710:        buffer_free(berr);
1.11      markus    711:
                    712:        /* Send the suspend signal to the program itself. */
                    713:        kill(getpid(), SIGTSTP);
                    714:
1.132     djm       715:        /* Reset window sizes in case they have changed */
                    716:        received_window_change_signal = 1;
1.11      markus    717:
                    718:        /* OK, we have been continued by the user. Reinitialize buffers. */
1.31      markus    719:        buffer_init(bin);
                    720:        buffer_init(bout);
                    721:        buffer_init(berr);
1.11      markus    722:
1.233     djm       723:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus    724: }
                    725:
1.77      itojun    726: static void
1.161     deraadt   727: client_process_net_input(fd_set *readset)
1.11      markus    728: {
1.212     andreas   729:        int len, cont = 0;
1.17      markus    730:        char buf[8192];
1.11      markus    731:
1.13      markus    732:        /*
                    733:         * Read input from the server, and add any such data to the buffer of
                    734:         * the packet subsystem.
                    735:         */
1.11      markus    736:        if (FD_ISSET(connection_in, readset)) {
                    737:                /* Read as much as possible. */
1.212     andreas   738:                len = roaming_read(connection_in, buf, sizeof(buf), &cont);
                    739:                if (len == 0 && cont == 0) {
1.197     djm       740:                        /*
                    741:                         * Received EOF.  The remote host has closed the
                    742:                         * connection.
                    743:                         */
                    744:                        snprintf(buf, sizeof buf,
                    745:                            "Connection to %.300s closed by remote host.\r\n",
                    746:                            host);
1.1       deraadt   747:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    748:                        quit_pending = 1;
                    749:                        return;
1.11      markus    750:                }
1.13      markus    751:                /*
                    752:                 * There is a kernel bug on Solaris that causes select to
                    753:                 * sometimes wake up even though there is no data available.
                    754:                 */
1.53      millert   755:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
1.11      markus    756:                        len = 0;
                    757:
                    758:                if (len < 0) {
1.197     djm       759:                        /*
                    760:                         * An error has encountered.  Perhaps there is a
                    761:                         * network problem.
                    762:                         */
                    763:                        snprintf(buf, sizeof buf,
                    764:                            "Read from remote host %.300s: %.100s\r\n",
                    765:                            host, strerror(errno));
1.11      markus    766:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    767:                        quit_pending = 1;
                    768:                        return;
                    769:                }
                    770:                packet_process_incoming(buf, len);
                    771:        }
1.17      markus    772: }
1.16      markus    773:
1.97      jakob     774: static void
1.190     djm       775: client_status_confirm(int type, Channel *c, void *ctx)
1.123     djm       776: {
1.190     djm       777:        struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
                    778:        char errmsg[256];
                    779:        int tochan;
                    780:
1.234     djm       781:        /*
                    782:         * If a TTY was explicitly requested, then a failure to allocate
                    783:         * one is fatal.
                    784:         */
                    785:        if (cr->action == CONFIRM_TTY &&
                    786:            (options.request_tty == REQUEST_TTY_FORCE ||
                    787:            options.request_tty == REQUEST_TTY_YES))
                    788:                cr->action = CONFIRM_CLOSE;
                    789:
1.190     djm       790:        /* XXX supress on mux _client_ quietmode */
                    791:        tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
1.217     djm       792:            c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
1.190     djm       793:
                    794:        if (type == SSH2_MSG_CHANNEL_SUCCESS) {
                    795:                debug2("%s request accepted on channel %d",
                    796:                    cr->request_type, c->self);
                    797:        } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
                    798:                if (tochan) {
                    799:                        snprintf(errmsg, sizeof(errmsg),
                    800:                            "%s request failed\r\n", cr->request_type);
                    801:                } else {
                    802:                        snprintf(errmsg, sizeof(errmsg),
                    803:                            "%s request failed on channel %d",
                    804:                            cr->request_type, c->self);
                    805:                }
                    806:                /* If error occurred on primary session channel, then exit */
1.234     djm       807:                if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
1.190     djm       808:                        fatal("%s", errmsg);
1.234     djm       809:                /*
                    810:                 * If error occurred on mux client, append to
                    811:                 * their stderr.
                    812:                 */
                    813:                if (tochan) {
                    814:                        buffer_append(&c->extended, errmsg,
                    815:                            strlen(errmsg));
                    816:                } else
1.190     djm       817:                        error("%s", errmsg);
1.234     djm       818:                if (cr->action == CONFIRM_TTY) {
                    819:                        /*
                    820:                         * If a TTY allocation error occurred, then arrange
                    821:                         * for the correct TTY to leave raw mode.
                    822:                         */
                    823:                        if (c->self == session_ident)
                    824:                                leave_raw_mode(0);
                    825:                        else
                    826:                                mux_tty_alloc_failed(c);
                    827:                } else if (cr->action == CONFIRM_CLOSE) {
1.190     djm       828:                        chan_read_failed(c);
                    829:                        chan_write_failed(c);
                    830:                }
                    831:        }
1.250     djm       832:        free(cr);
1.190     djm       833: }
                    834:
                    835: static void
                    836: client_abandon_status_confirm(Channel *c, void *ctx)
                    837: {
1.250     djm       838:        free(ctx);
1.190     djm       839: }
1.129     deraadt   840:
1.236     djm       841: void
1.234     djm       842: client_expect_confirm(int id, const char *request,
                    843:     enum confirm_action action)
1.190     djm       844: {
1.255     djm       845:        struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
1.123     djm       846:
1.190     djm       847:        cr->request_type = request;
1.234     djm       848:        cr->action = action;
1.123     djm       849:
1.190     djm       850:        channel_register_status_confirm(id, client_status_confirm,
                    851:            client_abandon_status_confirm, cr);
1.196     djm       852: }
                    853:
                    854: void
                    855: client_register_global_confirm(global_confirm_cb *cb, void *ctx)
                    856: {
1.201     djm       857:        struct global_confirm *gc, *last_gc;
1.196     djm       858:
                    859:        /* Coalesce identical callbacks */
1.201     djm       860:        last_gc = TAILQ_LAST(&global_confirms, global_confirms);
                    861:        if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
                    862:                if (++last_gc->ref_count >= INT_MAX)
                    863:                        fatal("%s: last_gc->ref_count = %d",
                    864:                            __func__, last_gc->ref_count);
1.196     djm       865:                return;
                    866:        }
                    867:
1.255     djm       868:        gc = xcalloc(1, sizeof(*gc));
1.196     djm       869:        gc->cb = cb;
                    870:        gc->ctx = ctx;
                    871:        gc->ref_count = 1;
                    872:        TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
1.123     djm       873: }
                    874:
                    875: static void
1.99      markus    876: process_cmdline(void)
1.97      jakob     877: {
                    878:        void (*handler)(int);
1.261     millert   879:        char *s, *cmd;
                    880:        int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
                    881:        struct Forward fwd;
1.97      jakob     882:
1.257     tedu      883:        memset(&fwd, 0, sizeof(fwd));
1.183     djm       884:
1.233     djm       885:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.101     markus    886:        handler = signal(SIGINT, SIG_IGN);
1.99      markus    887:        cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1.97      jakob     888:        if (s == NULL)
                    889:                goto out;
1.256     deraadt   890:        while (isspace((u_char)*s))
1.97      jakob     891:                s++;
1.121     djm       892:        if (*s == '-')
                    893:                s++;    /* Skip cmdline '-', if any */
1.120     dtucker   894:        if (*s == '\0')
1.97      jakob     895:                goto out;
1.121     djm       896:
1.122     djm       897:        if (*s == 'h' || *s == 'H' || *s == '?') {
1.121     djm       898:                logit("Commands:");
1.164     djm       899:                logit("      -L[bind_address:]port:host:hostport    "
                    900:                    "Request local forward");
                    901:                logit("      -R[bind_address:]port:host:hostport    "
                    902:                    "Request remote forward");
1.204     stevesk   903:                logit("      -D[bind_address:]port                  "
                    904:                    "Request dynamic forward");
1.237     markus    905:                logit("      -KL[bind_address:]port                 "
                    906:                    "Cancel local forward");
1.165     stevesk   907:                logit("      -KR[bind_address:]port                 "
1.164     djm       908:                    "Cancel remote forward");
1.237     markus    909:                logit("      -KD[bind_address:]port                 "
                    910:                    "Cancel dynamic forward");
1.146     reyk      911:                if (!options.permit_local_command)
                    912:                        goto out;
1.164     djm       913:                logit("      !args                                  "
                    914:                    "Execute local command");
1.146     reyk      915:                goto out;
                    916:        }
                    917:
                    918:        if (*s == '!' && options.permit_local_command) {
                    919:                s++;
                    920:                ssh_local_cmd(s);
1.121     djm       921:                goto out;
                    922:        }
                    923:
                    924:        if (*s == 'K') {
                    925:                delete = 1;
                    926:                s++;
                    927:        }
1.204     stevesk   928:        if (*s == 'L')
                    929:                local = 1;
                    930:        else if (*s == 'R')
                    931:                remote = 1;
                    932:        else if (*s == 'D')
                    933:                dynamic = 1;
                    934:        else {
1.109     itojun    935:                logit("Invalid command.");
1.97      jakob     936:                goto out;
                    937:        }
1.204     stevesk   938:
1.237     markus    939:        if (delete && !compat20) {
1.109     itojun    940:                logit("Not supported for SSH protocol version 1.");
1.97      jakob     941:                goto out;
                    942:        }
1.121     djm       943:
1.256     deraadt   944:        while (isspace((u_char)*++s))
1.179     tedu      945:                ;
1.97      jakob     946:
1.217     djm       947:        /* XXX update list of forwards in options */
1.121     djm       948:        if (delete) {
1.261     millert   949:                /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
                    950:                if (!parse_forward(&fwd, s, 1, 0)) {
                    951:                        logit("Bad forwarding close specification.");
1.121     djm       952:                        goto out;
                    953:                }
1.237     markus    954:                if (remote)
1.261     millert   955:                        ok = channel_request_rforward_cancel(&fwd) == 0;
1.237     markus    956:                else if (dynamic)
1.261     millert   957:                        ok = channel_cancel_lport_listener(&fwd,
                    958:                            0, &options.fwd_opts) > 0;
1.237     markus    959:                else
1.261     millert   960:                        ok = channel_cancel_lport_listener(&fwd,
                    961:                            CHANNEL_CANCEL_PORT_STATIC,
                    962:                            &options.fwd_opts) > 0;
1.237     markus    963:                if (!ok) {
                    964:                        logit("Unkown port forwarding.");
                    965:                        goto out;
                    966:                }
                    967:                logit("Canceled forwarding.");
1.121     djm       968:        } else {
1.209     djm       969:                if (!parse_forward(&fwd, s, dynamic, remote)) {
1.121     djm       970:                        logit("Bad forwarding specification.");
                    971:                        goto out;
                    972:                }
1.204     stevesk   973:                if (local || dynamic) {
1.261     millert   974:                        if (!channel_setup_local_fwd_listener(&fwd,
                    975:                            &options.fwd_opts)) {
1.121     djm       976:                                logit("Port forwarding failed.");
                    977:                                goto out;
                    978:                        }
1.135     djm       979:                } else {
1.261     millert   980:                        if (channel_request_remote_forwarding(&fwd) < 0) {
1.167     markus    981:                                logit("Port forwarding failed.");
                    982:                                goto out;
                    983:                        }
1.135     djm       984:                }
1.121     djm       985:                logit("Forwarding port.");
                    986:        }
                    987:
1.97      jakob     988: out:
                    989:        signal(SIGINT, handler);
1.233     djm       990:        enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.250     djm       991:        free(cmd);
                    992:        free(fwd.listen_host);
1.261     millert   993:        free(fwd.listen_path);
1.250     djm       994:        free(fwd.connect_host);
1.261     millert   995:        free(fwd.connect_path);
1.97      jakob     996: }
                    997:
1.244     dtucker   998: /* reasons to suppress output of an escape command in help output */
                    999: #define SUPPRESS_NEVER         0       /* never suppress, always show */
                   1000: #define SUPPRESS_PROTO1                1       /* don't show in protocol 1 sessions */
                   1001: #define SUPPRESS_MUXCLIENT     2       /* don't show in mux client sessions */
                   1002: #define SUPPRESS_MUXMASTER     4       /* don't show in mux master sessions */
                   1003: #define SUPPRESS_SYSLOG                8       /* don't show when logging to syslog */
                   1004: struct escape_help_text {
                   1005:        const char *cmd;
                   1006:        const char *text;
                   1007:        unsigned int flags;
                   1008: };
                   1009: static struct escape_help_text esc_txt[] = {
                   1010:     {".",  "terminate session", SUPPRESS_MUXMASTER},
                   1011:     {".",  "terminate connection (and any multiplexed sessions)",
                   1012:        SUPPRESS_MUXCLIENT},
                   1013:     {"B",  "send a BREAK to the remote system", SUPPRESS_PROTO1},
                   1014:     {"C",  "open a command line", SUPPRESS_MUXCLIENT},
                   1015:     {"R",  "request rekey", SUPPRESS_PROTO1},
1.246     dtucker  1016:     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1.244     dtucker  1017:     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
                   1018:     {"#",  "list forwarded connections", SUPPRESS_NEVER},
                   1019:     {"&",  "background ssh (when waiting for connections to terminate)",
                   1020:        SUPPRESS_MUXCLIENT},
                   1021:     {"?", "this message", SUPPRESS_NEVER},
                   1022: };
                   1023:
                   1024: static void
                   1025: print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
                   1026:     int using_stderr)
                   1027: {
                   1028:        unsigned int i, suppress_flags;
                   1029:        char string[1024];
                   1030:
                   1031:        snprintf(string, sizeof string, "%c?\r\n"
                   1032:            "Supported escape sequences:\r\n", escape_char);
                   1033:        buffer_append(b, string, strlen(string));
                   1034:
                   1035:        suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
                   1036:            (mux_client ? SUPPRESS_MUXCLIENT : 0) |
                   1037:            (mux_client ? 0 : SUPPRESS_MUXMASTER) |
                   1038:            (using_stderr ? 0 : SUPPRESS_SYSLOG);
                   1039:
                   1040:        for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
                   1041:                if (esc_txt[i].flags & suppress_flags)
                   1042:                        continue;
1.246     dtucker  1043:                snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1.244     dtucker  1044:                    escape_char, esc_txt[i].cmd, esc_txt[i].text);
                   1045:                buffer_append(b, string, strlen(string));
                   1046:        }
                   1047:
                   1048:        snprintf(string, sizeof string,
1.246     dtucker  1049:            " %c%c   - send the escape character by typing it twice\r\n"
1.244     dtucker  1050:            "(Note that escapes are only recognized immediately after "
                   1051:            "newline.)\r\n", escape_char, escape_char);
                   1052:        buffer_append(b, string, strlen(string));
                   1053: }
                   1054:
1.195     djm      1055: /*
                   1056:  * Process the characters one by one, call with c==NULL for proto1 case.
                   1057:  */
1.77      itojun   1058: static int
1.195     djm      1059: process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
                   1060:     char *buf, int len)
1.31      markus   1061: {
1.32      markus   1062:        char string[1024];
1.31      markus   1063:        pid_t pid;
                   1064:        int bytes = 0;
1.42      markus   1065:        u_int i;
                   1066:        u_char ch;
1.31      markus   1067:        char *s;
1.195     djm      1068:        int *escape_pendingp, escape_char;
                   1069:        struct escape_filter_ctx *efc;
1.31      markus   1070:
1.195     djm      1071:        if (c == NULL) {
                   1072:                escape_pendingp = &escape_pending1;
                   1073:                escape_char = escape_char1;
                   1074:        } else {
                   1075:                if (c->filter_ctx == NULL)
                   1076:                        return 0;
                   1077:                efc = (struct escape_filter_ctx *)c->filter_ctx;
                   1078:                escape_pendingp = &efc->escape_pending;
                   1079:                escape_char = efc->escape_char;
                   1080:        }
                   1081:
1.139     djm      1082:        if (len <= 0)
                   1083:                return (0);
                   1084:
                   1085:        for (i = 0; i < (u_int)len; i++) {
1.31      markus   1086:                /* Get one character at a time. */
                   1087:                ch = buf[i];
                   1088:
1.195     djm      1089:                if (*escape_pendingp) {
1.31      markus   1090:                        /* We have previously seen an escape character. */
                   1091:                        /* Clear the flag now. */
1.195     djm      1092:                        *escape_pendingp = 0;
1.31      markus   1093:
                   1094:                        /* Process the escaped character. */
                   1095:                        switch (ch) {
                   1096:                        case '.':
                   1097:                                /* Terminate the connection. */
1.195     djm      1098:                                snprintf(string, sizeof string, "%c.\r\n",
                   1099:                                    escape_char);
1.32      markus   1100:                                buffer_append(berr, string, strlen(string));
1.31      markus   1101:
1.217     djm      1102:                                if (c && c->ctl_chan != -1) {
1.195     djm      1103:                                        chan_read_failed(c);
                   1104:                                        chan_write_failed(c);
1.252     dtucker  1105:                                        if (c->detach_user)
                   1106:                                                c->detach_user(c->self, NULL);
1.253     dtucker  1107:                                        c->type = SSH_CHANNEL_ABANDONED;
                   1108:                                        buffer_clear(&c->input);
                   1109:                                        chan_ibuf_empty(c);
1.195     djm      1110:                                        return 0;
                   1111:                                } else
                   1112:                                        quit_pending = 1;
1.31      markus   1113:                                return -1;
                   1114:
                   1115:                        case 'Z' - 64:
1.195     djm      1116:                                /* XXX support this for mux clients */
1.217     djm      1117:                                if (c && c->ctl_chan != -1) {
1.245     dtucker  1118:                                        char b[16];
1.195     djm      1119:  noescape:
1.245     dtucker  1120:                                        if (ch == 'Z' - 64)
                   1121:                                                snprintf(b, sizeof b, "^Z");
                   1122:                                        else
                   1123:                                                snprintf(b, sizeof b, "%c", ch);
1.195     djm      1124:                                        snprintf(string, sizeof string,
1.245     dtucker  1125:                                            "%c%s escape not available to "
1.195     djm      1126:                                            "multiplexed sessions\r\n",
1.245     dtucker  1127:                                            escape_char, b);
1.195     djm      1128:                                        buffer_append(berr, string,
                   1129:                                            strlen(string));
                   1130:                                        continue;
                   1131:                                }
1.197     djm      1132:                                /* Suspend the program. Inform the user */
1.195     djm      1133:                                snprintf(string, sizeof string,
                   1134:                                    "%c^Z [suspend ssh]\r\n", escape_char);
1.32      markus   1135:                                buffer_append(berr, string, strlen(string));
1.31      markus   1136:
                   1137:                                /* Restore terminal modes and suspend. */
                   1138:                                client_suspend_self(bin, bout, berr);
                   1139:
                   1140:                                /* We have been continued. */
                   1141:                                continue;
                   1142:
1.111     markus   1143:                        case 'B':
                   1144:                                if (compat20) {
                   1145:                                        snprintf(string, sizeof string,
                   1146:                                            "%cB\r\n", escape_char);
                   1147:                                        buffer_append(berr, string,
                   1148:                                            strlen(string));
1.254     djm      1149:                                        channel_request_start(c->self,
1.111     markus   1150:                                            "break", 0);
                   1151:                                        packet_put_int(1000);
                   1152:                                        packet_send();
                   1153:                                }
                   1154:                                continue;
                   1155:
1.54      markus   1156:                        case 'R':
1.59      markus   1157:                                if (compat20) {
                   1158:                                        if (datafellows & SSH_BUG_NOREKEY)
1.197     djm      1159:                                                logit("Server does not "
                   1160:                                                    "support re-keying");
1.59      markus   1161:                                        else
                   1162:                                                need_rekeying = 1;
                   1163:                                }
1.54      markus   1164:                                continue;
                   1165:
1.242     dtucker  1166:                        case 'V':
                   1167:                                /* FALLTHROUGH */
                   1168:                        case 'v':
                   1169:                                if (c && c->ctl_chan != -1)
                   1170:                                        goto noescape;
                   1171:                                if (!log_is_on_stderr()) {
                   1172:                                        snprintf(string, sizeof string,
                   1173:                                            "%c%c [Logging to syslog]\r\n",
                   1174:                                             escape_char, ch);
                   1175:                                        buffer_append(berr, string,
                   1176:                                            strlen(string));
                   1177:                                        continue;
                   1178:                                }
                   1179:                                if (ch == 'V' && options.log_level >
                   1180:                                    SYSLOG_LEVEL_QUIET)
                   1181:                                        log_change_level(--options.log_level);
                   1182:                                if (ch == 'v' && options.log_level <
                   1183:                                    SYSLOG_LEVEL_DEBUG3)
                   1184:                                        log_change_level(++options.log_level);
                   1185:                                snprintf(string, sizeof string,
                   1186:                                    "%c%c [LogLevel %s]\r\n", escape_char, ch,
                   1187:                                    log_level_name(options.log_level));
                   1188:                                buffer_append(berr, string, strlen(string));
                   1189:                                continue;
                   1190:
1.31      markus   1191:                        case '&':
1.217     djm      1192:                                if (c && c->ctl_chan != -1)
1.195     djm      1193:                                        goto noescape;
1.31      markus   1194:                                /*
1.197     djm      1195:                                 * Detach the program (continue to serve
                   1196:                                 * connections, but put in background and no
                   1197:                                 * more new connections).
1.31      markus   1198:                                 */
                   1199:                                /* Restore tty modes. */
1.233     djm      1200:                                leave_raw_mode(
                   1201:                                    options.request_tty == REQUEST_TTY_FORCE);
1.31      markus   1202:
                   1203:                                /* Stop listening for new connections. */
1.86      markus   1204:                                channel_stop_listening();
1.31      markus   1205:
1.86      markus   1206:                                snprintf(string, sizeof string,
                   1207:                                    "%c& [backgrounded]\n", escape_char);
                   1208:                                buffer_append(berr, string, strlen(string));
1.31      markus   1209:
                   1210:                                /* Fork into background. */
                   1211:                                pid = fork();
                   1212:                                if (pid < 0) {
                   1213:                                        error("fork: %.100s", strerror(errno));
                   1214:                                        continue;
                   1215:                                }
                   1216:                                if (pid != 0) { /* This is the parent. */
                   1217:                                        /* The parent just exits. */
                   1218:                                        exit(0);
                   1219:                                }
                   1220:                                /* The child continues serving connections. */
1.86      markus   1221:                                if (compat20) {
                   1222:                                        buffer_append(bin, "\004", 1);
                   1223:                                        /* fake EOF on stdin */
                   1224:                                        return -1;
                   1225:                                } else if (!stdin_eof) {
                   1226:                                        /*
1.197     djm      1227:                                         * Sending SSH_CMSG_EOF alone does not
                   1228:                                         * always appear to be enough.  So we
                   1229:                                         * try to send an EOF character first.
1.86      markus   1230:                                         */
                   1231:                                        packet_start(SSH_CMSG_STDIN_DATA);
                   1232:                                        packet_put_string("\004", 1);
                   1233:                                        packet_send();
                   1234:                                        /* Close stdin. */
                   1235:                                        stdin_eof = 1;
                   1236:                                        if (buffer_len(bin) == 0) {
                   1237:                                                packet_start(SSH_CMSG_EOF);
                   1238:                                                packet_send();
                   1239:                                        }
                   1240:                                }
                   1241:                                continue;
1.31      markus   1242:
                   1243:                        case '?':
1.244     dtucker  1244:                                print_escape_help(berr, escape_char, compat20,
                   1245:                                    (c && c->ctl_chan != -1),
                   1246:                                    log_is_on_stderr());
1.31      markus   1247:                                continue;
                   1248:
                   1249:                        case '#':
1.195     djm      1250:                                snprintf(string, sizeof string, "%c#\r\n",
                   1251:                                    escape_char);
1.32      markus   1252:                                buffer_append(berr, string, strlen(string));
1.31      markus   1253:                                s = channel_open_message();
                   1254:                                buffer_append(berr, s, strlen(s));
1.250     djm      1255:                                free(s);
1.97      jakob    1256:                                continue;
                   1257:
                   1258:                        case 'C':
1.217     djm      1259:                                if (c && c->ctl_chan != -1)
1.206     djm      1260:                                        goto noescape;
1.99      markus   1261:                                process_cmdline();
1.31      markus   1262:                                continue;
                   1263:
                   1264:                        default:
                   1265:                                if (ch != escape_char) {
                   1266:                                        buffer_put_char(bin, escape_char);
                   1267:                                        bytes++;
                   1268:                                }
                   1269:                                /* Escaped characters fall through here */
                   1270:                                break;
                   1271:                        }
                   1272:                } else {
                   1273:                        /*
1.197     djm      1274:                         * The previous character was not an escape char.
                   1275:                         * Check if this is an escape.
1.31      markus   1276:                         */
                   1277:                        if (last_was_cr && ch == escape_char) {
1.197     djm      1278:                                /*
                   1279:                                 * It is. Set the flag and continue to
                   1280:                                 * next character.
                   1281:                                 */
1.195     djm      1282:                                *escape_pendingp = 1;
1.31      markus   1283:                                continue;
                   1284:                        }
                   1285:                }
                   1286:
                   1287:                /*
                   1288:                 * Normal character.  Record whether it was a newline,
                   1289:                 * and append it to the buffer.
                   1290:                 */
                   1291:                last_was_cr = (ch == '\r' || ch == '\n');
                   1292:                buffer_put_char(bin, ch);
                   1293:                bytes++;
                   1294:        }
                   1295:        return bytes;
                   1296: }
                   1297:
1.77      itojun   1298: static void
1.161     deraadt  1299: client_process_input(fd_set *readset)
1.17      markus   1300: {
1.21      deraadt  1301:        int len;
1.31      markus   1302:        char buf[8192];
1.16      markus   1303:
1.11      markus   1304:        /* Read input from stdin. */
                   1305:        if (FD_ISSET(fileno(stdin), readset)) {
                   1306:                /* Read as much as possible. */
                   1307:                len = read(fileno(stdin), buf, sizeof(buf));
1.64      markus   1308:                if (len < 0 && (errno == EAGAIN || errno == EINTR))
                   1309:                        return;         /* we'll try again later */
1.11      markus   1310:                if (len <= 0) {
1.13      markus   1311:                        /*
                   1312:                         * Received EOF or error.  They are treated
                   1313:                         * similarly, except that an error message is printed
                   1314:                         * if it was an error condition.
                   1315:                         */
1.11      markus   1316:                        if (len < 0) {
1.197     djm      1317:                                snprintf(buf, sizeof buf, "read: %.100s\r\n",
                   1318:                                    strerror(errno));
1.11      markus   1319:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1320:                        }
                   1321:                        /* Mark that we have seen EOF. */
                   1322:                        stdin_eof = 1;
1.13      markus   1323:                        /*
                   1324:                         * Send an EOF message to the server unless there is
                   1325:                         * data in the buffer.  If there is data in the
                   1326:                         * buffer, no message will be sent now.  Code
                   1327:                         * elsewhere will send the EOF when the buffer
                   1328:                         * becomes empty if stdin_eof is set.
                   1329:                         */
1.11      markus   1330:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt  1331:                                packet_start(SSH_CMSG_EOF);
                   1332:                                packet_send();
1.11      markus   1333:                        }
1.195     djm      1334:                } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1.13      markus   1335:                        /*
                   1336:                         * Normal successful read, and no escape character.
                   1337:                         * Just append the data to buffer.
                   1338:                         */
1.11      markus   1339:                        buffer_append(&stdin_buffer, buf, len);
                   1340:                } else {
1.13      markus   1341:                        /*
1.197     djm      1342:                         * Normal, successful read.  But we have an escape
                   1343:                         * character and have to process the characters one
                   1344:                         * by one.
1.13      markus   1345:                         */
1.195     djm      1346:                        if (process_escapes(NULL, &stdin_buffer,
                   1347:                            &stdout_buffer, &stderr_buffer, buf, len) == -1)
1.31      markus   1348:                                return;
1.11      markus   1349:                }
                   1350:        }
                   1351: }
                   1352:
1.77      itojun   1353: static void
1.161     deraadt  1354: client_process_output(fd_set *writeset)
1.11      markus   1355: {
                   1356:        int len;
                   1357:        char buf[100];
1.1       deraadt  1358:
1.11      markus   1359:        /* Write buffered output to stdout. */
                   1360:        if (FD_ISSET(fileno(stdout), writeset)) {
                   1361:                /* Write as much data as possible. */
                   1362:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt  1363:                    buffer_len(&stdout_buffer));
1.11      markus   1364:                if (len <= 0) {
1.64      markus   1365:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1366:                                len = 0;
                   1367:                        else {
1.13      markus   1368:                                /*
                   1369:                                 * An error or EOF was encountered.  Put an
                   1370:                                 * error message to stderr buffer.
                   1371:                                 */
1.197     djm      1372:                                snprintf(buf, sizeof buf,
                   1373:                                    "write stdout: %.50s\r\n", strerror(errno));
1.11      markus   1374:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1375:                                quit_pending = 1;
                   1376:                                return;
                   1377:                        }
                   1378:                }
                   1379:                /* Consume printed data from the buffer. */
                   1380:                buffer_consume(&stdout_buffer, len);
                   1381:        }
                   1382:        /* Write buffered output to stderr. */
                   1383:        if (FD_ISSET(fileno(stderr), writeset)) {
                   1384:                /* Write as much data as possible. */
                   1385:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt  1386:                    buffer_len(&stderr_buffer));
1.11      markus   1387:                if (len <= 0) {
1.64      markus   1388:                        if (errno == EINTR || errno == EAGAIN)
1.11      markus   1389:                                len = 0;
                   1390:                        else {
1.197     djm      1391:                                /*
                   1392:                                 * EOF or error, but can't even print
                   1393:                                 * error message.
                   1394:                                 */
1.11      markus   1395:                                quit_pending = 1;
                   1396:                                return;
                   1397:                        }
                   1398:                }
                   1399:                /* Consume printed characters from the buffer. */
                   1400:                buffer_consume(&stderr_buffer, len);
                   1401:        }
1.1       deraadt  1402: }
                   1403:
1.13      markus   1404: /*
1.15      markus   1405:  * Get packets from the connection input buffer, and process them as long as
                   1406:  * there are packets available.
                   1407:  *
                   1408:  * Any unknown packets received during the actual
                   1409:  * session cause the session to terminate.  This is
                   1410:  * intended to make debugging easier since no
                   1411:  * confirmations are sent.  Any compatible protocol
                   1412:  * extensions must be negotiated during the
                   1413:  * preparatory phase.
                   1414:  */
                   1415:
1.77      itojun   1416: static void
1.49      itojun   1417: client_process_buffered_input_packets(void)
1.15      markus   1418: {
1.265     markus   1419:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
1.15      markus   1420: }
                   1421:
1.31      markus   1422: /* scan buf[] for '~' before sending data to the peer */
1.30      markus   1423:
1.195     djm      1424: /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
                   1425: void *
                   1426: client_new_escape_filter_ctx(int escape_char)
                   1427: {
                   1428:        struct escape_filter_ctx *ret;
                   1429:
1.255     djm      1430:        ret = xcalloc(1, sizeof(*ret));
1.195     djm      1431:        ret->escape_pending = 0;
                   1432:        ret->escape_char = escape_char;
                   1433:        return (void *)ret;
                   1434: }
                   1435:
1.198     djm      1436: /* Free the escape filter context on channel free */
                   1437: void
                   1438: client_filter_cleanup(int cid, void *ctx)
                   1439: {
1.250     djm      1440:        free(ctx);
1.198     djm      1441: }
                   1442:
1.195     djm      1443: int
                   1444: client_simple_escape_filter(Channel *c, char *buf, int len)
1.30      markus   1445: {
1.190     djm      1446:        if (c->extended_usage != CHAN_EXTENDED_WRITE)
                   1447:                return 0;
                   1448:
1.195     djm      1449:        return process_escapes(c, &c->input, &c->output, &c->extended,
                   1450:            buf, len);
1.30      markus   1451: }
                   1452:
1.77      itojun   1453: static void
1.60      markus   1454: client_channel_closed(int id, void *arg)
                   1455: {
1.83      markus   1456:        channel_cancel_cleanup(id);
1.60      markus   1457:        session_closed = 1;
1.233     djm      1458:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.60      markus   1459: }
                   1460:
1.15      markus   1461: /*
1.13      markus   1462:  * Implements the interactive session with the server.  This is called after
                   1463:  * the user has been authenticated, and a command has been started on the
1.72      stevesk  1464:  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
                   1465:  * used as an escape character for terminating or suspending the session.
1.13      markus   1466:  */
1.1       deraadt  1467:
1.20      markus   1468: int
1.30      markus   1469: client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1.1       deraadt  1470: {
1.46      markus   1471:        fd_set *readset = NULL, *writeset = NULL;
1.11      markus   1472:        double start_time, total_time;
1.265     markus   1473:        int r, max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1.200     markus   1474:        u_int64_t ibytes, obytes;
1.130     avsm     1475:        u_int nalloc = 0;
1.11      markus   1476:        char buf[100];
                   1477:
                   1478:        debug("Entering interactive session.");
                   1479:
                   1480:        start_time = get_current_time();
                   1481:
                   1482:        /* Initialize variables. */
1.195     djm      1483:        escape_pending1 = 0;
1.11      markus   1484:        last_was_cr = 1;
                   1485:        exit_status = -1;
                   1486:        stdin_eof = 0;
                   1487:        buffer_high = 64 * 1024;
                   1488:        connection_in = packet_get_connection_in();
                   1489:        connection_out = packet_get_connection_out();
1.46      markus   1490:        max_fd = MAX(connection_in, connection_out);
                   1491:
                   1492:        if (!compat20) {
1.63      markus   1493:                /* enable nonblocking unless tty */
                   1494:                if (!isatty(fileno(stdin)))
                   1495:                        set_nonblock(fileno(stdin));
                   1496:                if (!isatty(fileno(stdout)))
                   1497:                        set_nonblock(fileno(stdout));
                   1498:                if (!isatty(fileno(stderr)))
                   1499:                        set_nonblock(fileno(stderr));
1.46      markus   1500:                max_fd = MAX(max_fd, fileno(stdin));
                   1501:                max_fd = MAX(max_fd, fileno(stdout));
                   1502:                max_fd = MAX(max_fd, fileno(stderr));
                   1503:        }
1.11      markus   1504:        quit_pending = 0;
1.195     djm      1505:        escape_char1 = escape_char_arg;
1.11      markus   1506:
                   1507:        /* Initialize buffers. */
                   1508:        buffer_init(&stdin_buffer);
                   1509:        buffer_init(&stdout_buffer);
                   1510:        buffer_init(&stderr_buffer);
                   1511:
1.15      markus   1512:        client_init_dispatch();
                   1513:
1.105     markus   1514:        /*
                   1515:         * Set signal handlers, (e.g. to restore non-blocking mode)
                   1516:         * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
                   1517:         */
1.131     djm      1518:        if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
                   1519:                signal(SIGHUP, signal_handler);
1.105     markus   1520:        if (signal(SIGINT, SIG_IGN) != SIG_IGN)
                   1521:                signal(SIGINT, signal_handler);
                   1522:        if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
                   1523:                signal(SIGQUIT, signal_handler);
                   1524:        if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
                   1525:                signal(SIGTERM, signal_handler);
1.132     djm      1526:        signal(SIGWINCH, window_change_handler);
1.11      markus   1527:
                   1528:        if (have_pty)
1.233     djm      1529:                enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.11      markus   1530:
1.48      markus   1531:        if (compat20) {
                   1532:                session_ident = ssh2_chan_id;
1.232     djm      1533:                if (session_ident != -1) {
                   1534:                        if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
                   1535:                                channel_register_filter(session_ident,
                   1536:                                    client_simple_escape_filter, NULL,
                   1537:                                    client_filter_cleanup,
                   1538:                                    client_new_escape_filter_ctx(
                   1539:                                    escape_char_arg));
                   1540:                        }
1.60      markus   1541:                        channel_register_cleanup(session_ident,
1.143     djm      1542:                            client_channel_closed, 0);
1.232     djm      1543:                }
1.48      markus   1544:        } else {
                   1545:                /* Check if we should immediately send eof on stdin. */
1.16      markus   1546:                client_check_initial_eof_on_stdin();
1.48      markus   1547:        }
1.30      markus   1548:
1.11      markus   1549:        /* Main loop of the client for the interactive session mode. */
                   1550:        while (!quit_pending) {
                   1551:
1.13      markus   1552:                /* Process buffered packets sent by the server. */
1.11      markus   1553:                client_process_buffered_input_packets();
                   1554:
1.60      markus   1555:                if (compat20 && session_closed && !channel_still_open())
                   1556:                        break;
                   1557:
1.263     markus   1558:                rekeying = (active_state->kex != NULL && !active_state->kex->done);
1.16      markus   1559:
1.56      markus   1560:                if (rekeying) {
                   1561:                        debug("rekeying in progress");
                   1562:                } else {
                   1563:                        /*
                   1564:                         * Make packets of buffered stdin data, and buffer
                   1565:                         * them for sending to the server.
                   1566:                         */
                   1567:                        if (!compat20)
                   1568:                                client_make_packets_from_stdin_data();
1.11      markus   1569:
1.56      markus   1570:                        /*
                   1571:                         * Make packets from buffered channel data, and
                   1572:                         * enqueue them for sending to the server.
                   1573:                         */
                   1574:                        if (packet_not_very_much_data_to_write())
                   1575:                                channel_output_poll();
1.11      markus   1576:
1.56      markus   1577:                        /*
                   1578:                         * Check if the window size has changed, and buffer a
                   1579:                         * message about it to the server if so.
                   1580:                         */
                   1581:                        client_check_window_change();
1.11      markus   1582:
1.56      markus   1583:                        if (quit_pending)
                   1584:                                break;
                   1585:                }
1.13      markus   1586:                /*
                   1587:                 * Wait until we have something to do (something becomes
                   1588:                 * available on one of the descriptors).
                   1589:                 */
1.81      markus   1590:                max_fd2 = max_fd;
1.56      markus   1591:                client_wait_until_can_do_something(&readset, &writeset,
1.81      markus   1592:                    &max_fd2, &nalloc, rekeying);
1.11      markus   1593:
                   1594:                if (quit_pending)
                   1595:                        break;
                   1596:
1.56      markus   1597:                /* Do channel operations unless rekeying in progress. */
                   1598:                if (!rekeying) {
                   1599:                        channel_after_select(readset, writeset);
1.108     markus   1600:                        if (need_rekeying || packet_need_rekeying()) {
                   1601:                                debug("need rekeying");
1.263     markus   1602:                                active_state->kex->done = 0;
1.265     markus   1603:                                if ((r = kex_send_kexinit(active_state)) != 0)
                   1604:                                        fatal("%s: kex_send_kexinit: %s",
                   1605:                                            __func__, ssh_err(r));
1.56      markus   1606:                                need_rekeying = 0;
                   1607:                        }
                   1608:                }
1.11      markus   1609:
1.17      markus   1610:                /* Buffer input from the connection.  */
1.46      markus   1611:                client_process_net_input(readset);
1.17      markus   1612:
                   1613:                if (quit_pending)
                   1614:                        break;
1.11      markus   1615:
1.17      markus   1616:                if (!compat20) {
                   1617:                        /* Buffer data from stdin */
1.46      markus   1618:                        client_process_input(readset);
1.17      markus   1619:                        /*
                   1620:                         * Process output to stdout and stderr.  Output to
                   1621:                         * the connection is processed elsewhere (above).
                   1622:                         */
1.46      markus   1623:                        client_process_output(writeset);
1.214     andreas  1624:                }
                   1625:
                   1626:                if (session_resumed) {
                   1627:                        connection_in = packet_get_connection_in();
                   1628:                        connection_out = packet_get_connection_out();
                   1629:                        max_fd = MAX(max_fd, connection_out);
                   1630:                        max_fd = MAX(max_fd, connection_in);
                   1631:                        session_resumed = 0;
1.17      markus   1632:                }
1.11      markus   1633:
1.197     djm      1634:                /*
                   1635:                 * Send as much buffered packet data as possible to the
                   1636:                 * sender.
                   1637:                 */
1.46      markus   1638:                if (FD_ISSET(connection_out, writeset))
1.11      markus   1639:                        packet_write_poll();
1.222     djm      1640:
                   1641:                /*
                   1642:                 * If we are a backgrounded control master, and the
                   1643:                 * timeout has expired without any active client
                   1644:                 * connections, then quit.
                   1645:                 */
                   1646:                if (control_persist_exit_time > 0) {
1.251     dtucker  1647:                        if (monotime() >= control_persist_exit_time) {
1.222     djm      1648:                                debug("ControlPersist timeout expired");
                   1649:                                break;
                   1650:                        }
                   1651:                }
1.11      markus   1652:        }
1.250     djm      1653:        free(readset);
                   1654:        free(writeset);
1.11      markus   1655:
                   1656:        /* Terminate the session. */
                   1657:
                   1658:        /* Stop watching for window change. */
1.132     djm      1659:        signal(SIGWINCH, SIG_DFL);
1.211     andreas  1660:
1.213     stevesk  1661:        if (compat20) {
                   1662:                packet_start(SSH2_MSG_DISCONNECT);
                   1663:                packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
                   1664:                packet_put_cstring("disconnected by user");
1.219     djm      1665:                packet_put_cstring(""); /* language tag */
1.213     stevesk  1666:                packet_send();
                   1667:                packet_write_wait();
                   1668:        }
1.11      markus   1669:
1.76      markus   1670:        channel_free_all();
1.11      markus   1671:
1.75      markus   1672:        if (have_pty)
1.233     djm      1673:                leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.75      markus   1674:
                   1675:        /* restore blocking io */
                   1676:        if (!isatty(fileno(stdin)))
                   1677:                unset_nonblock(fileno(stdin));
                   1678:        if (!isatty(fileno(stdout)))
                   1679:                unset_nonblock(fileno(stdout));
                   1680:        if (!isatty(fileno(stderr)))
                   1681:                unset_nonblock(fileno(stderr));
1.116     dtucker  1682:
                   1683:        /*
                   1684:         * If there was no shell or command requested, there will be no remote
                   1685:         * exit status to be returned.  In that case, clear error code if the
                   1686:         * connection was deliberately terminated at this end.
                   1687:         */
                   1688:        if (no_shell_flag && received_signal == SIGTERM) {
                   1689:                received_signal = 0;
                   1690:                exit_status = 0;
                   1691:        }
1.75      markus   1692:
1.113     markus   1693:        if (received_signal)
1.89      itojun   1694:                fatal("Killed by signal %d.", (int) received_signal);
1.75      markus   1695:
1.13      markus   1696:        /*
                   1697:         * In interactive mode (with pseudo tty) display a message indicating
                   1698:         * that the connection has been closed.
                   1699:         */
1.11      markus   1700:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1.197     djm      1701:                snprintf(buf, sizeof buf,
                   1702:                    "Connection to %.64s closed.\r\n", host);
1.11      markus   1703:                buffer_append(&stderr_buffer, buf, strlen(buf));
                   1704:        }
1.70      markus   1705:
1.11      markus   1706:        /* Output any buffered data for stdout. */
1.231     djm      1707:        if (buffer_len(&stdout_buffer) > 0) {
1.230     djm      1708:                len = atomicio(vwrite, fileno(stdout),
                   1709:                    buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1.231     djm      1710:                if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1.11      markus   1711:                        error("Write failed flushing stdout buffer.");
1.231     djm      1712:                else
                   1713:                        buffer_consume(&stdout_buffer, len);
1.11      markus   1714:        }
                   1715:
                   1716:        /* Output any buffered data for stderr. */
1.231     djm      1717:        if (buffer_len(&stderr_buffer) > 0) {
1.230     djm      1718:                len = atomicio(vwrite, fileno(stderr),
                   1719:                    buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1.231     djm      1720:                if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1.11      markus   1721:                        error("Write failed flushing stderr buffer.");
1.231     djm      1722:                else
                   1723:                        buffer_consume(&stderr_buffer, len);
1.11      markus   1724:        }
                   1725:
                   1726:        /* Clear and free any buffers. */
                   1727:        memset(buf, 0, sizeof(buf));
                   1728:        buffer_free(&stdin_buffer);
                   1729:        buffer_free(&stdout_buffer);
                   1730:        buffer_free(&stderr_buffer);
                   1731:
                   1732:        /* Report bytes transferred, and transfer rates. */
                   1733:        total_time = get_current_time() - start_time;
1.263     markus   1734:        packet_get_bytes(&ibytes, &obytes);
1.200     markus   1735:        verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1.229     djm      1736:            (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1.11      markus   1737:        if (total_time > 0)
1.200     markus   1738:                verbose("Bytes per second: sent %.1f, received %.1f",
                   1739:                    obytes / total_time, ibytes / total_time);
1.11      markus   1740:        /* Return the exit status of the program. */
                   1741:        debug("Exit status %d", exit_status);
                   1742:        return exit_status;
1.15      markus   1743: }
                   1744:
                   1745: /*********/
                   1746:
1.264     markus   1747: static int
1.94      markus   1748: client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1749: {
1.42      markus   1750:        u_int data_len;
1.15      markus   1751:        char *data = packet_get_string(&data_len);
1.93      markus   1752:        packet_check_eom();
1.15      markus   1753:        buffer_append(&stdout_buffer, data, data_len);
1.258     djm      1754:        explicit_bzero(data, data_len);
1.250     djm      1755:        free(data);
1.264     markus   1756:        return 0;
1.15      markus   1757: }
1.264     markus   1758: static int
1.94      markus   1759: client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1.15      markus   1760: {
1.42      markus   1761:        u_int data_len;
1.15      markus   1762:        char *data = packet_get_string(&data_len);
1.93      markus   1763:        packet_check_eom();
1.15      markus   1764:        buffer_append(&stderr_buffer, data, data_len);
1.258     djm      1765:        explicit_bzero(data, data_len);
1.250     djm      1766:        free(data);
1.264     markus   1767:        return 0;
1.15      markus   1768: }
1.264     markus   1769: static int
1.94      markus   1770: client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1.15      markus   1771: {
                   1772:        exit_status = packet_get_int();
1.93      markus   1773:        packet_check_eom();
1.15      markus   1774:        /* Acknowledge the exit. */
                   1775:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                   1776:        packet_send();
                   1777:        /*
                   1778:         * Must wait for packet to be sent since we are
                   1779:         * exiting the loop.
                   1780:         */
                   1781:        packet_write_wait();
                   1782:        /* Flag that we want to exit. */
                   1783:        quit_pending = 1;
1.264     markus   1784:        return 0;
1.15      markus   1785: }
1.267     djm      1786:
1.264     markus   1787: static int
1.115     markus   1788: client_input_agent_open(int type, u_int32_t seq, void *ctxt)
                   1789: {
                   1790:        Channel *c = NULL;
1.262     djm      1791:        int r, remote_id, sock;
1.115     markus   1792:
                   1793:        /* Read the remote channel number from the message. */
                   1794:        remote_id = packet_get_int();
                   1795:        packet_check_eom();
                   1796:
                   1797:        /*
                   1798:         * Get a connection to the local authentication agent (this may again
                   1799:         * get forwarded).
                   1800:         */
1.262     djm      1801:        if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
                   1802:            r != SSH_ERR_AGENT_NOT_PRESENT)
                   1803:                debug("%s: ssh_get_authentication_socket: %s",
                   1804:                    __func__, ssh_err(r));
                   1805:
1.115     markus   1806:
                   1807:        /*
                   1808:         * If we could not connect the agent, send an error message back to
                   1809:         * the server. This should never happen unless the agent dies,
                   1810:         * because authentication forwarding is only enabled if we have an
                   1811:         * agent.
                   1812:         */
                   1813:        if (sock >= 0) {
                   1814:                c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
                   1815:                    -1, 0, 0, 0, "authentication agent connection", 1);
                   1816:                c->remote_id = remote_id;
                   1817:                c->force_drain = 1;
                   1818:        }
                   1819:        if (c == NULL) {
                   1820:                packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
                   1821:                packet_put_int(remote_id);
                   1822:        } else {
                   1823:                /* Send a confirmation to the remote host. */
                   1824:                debug("Forwarding authentication connection.");
                   1825:                packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
                   1826:                packet_put_int(remote_id);
                   1827:                packet_put_int(c->self);
                   1828:        }
                   1829:        packet_send();
1.264     markus   1830:        return 0;
1.115     markus   1831: }
1.15      markus   1832:
1.77      itojun   1833: static Channel *
1.40      markus   1834: client_request_forwarded_tcpip(const char *request_type, int rchan)
                   1835: {
1.103     deraadt  1836:        Channel *c = NULL;
1.40      markus   1837:        char *listen_address, *originator_address;
1.208     djm      1838:        u_short listen_port, originator_port;
1.40      markus   1839:
                   1840:        /* Get rest of the packet */
                   1841:        listen_address = packet_get_string(NULL);
                   1842:        listen_port = packet_get_int();
                   1843:        originator_address = packet_get_string(NULL);
                   1844:        originator_port = packet_get_int();
1.93      markus   1845:        packet_check_eom();
1.40      markus   1846:
1.261     millert  1847:        debug("%s: listen %s port %d, originator %s port %d", __func__,
                   1848:            listen_address, listen_port, originator_address, originator_port);
1.191     djm      1849:
1.260     markus   1850:        c = channel_connect_by_listen_address(listen_address, listen_port,
1.191     djm      1851:            "forwarded-tcpip", originator_address);
1.40      markus   1852:
1.250     djm      1853:        free(originator_address);
                   1854:        free(listen_address);
1.40      markus   1855:        return c;
                   1856: }
                   1857:
1.103     deraadt  1858: static Channel *
1.261     millert  1859: client_request_forwarded_streamlocal(const char *request_type, int rchan)
                   1860: {
                   1861:        Channel *c = NULL;
                   1862:        char *listen_path;
                   1863:
                   1864:        /* Get the remote path. */
                   1865:        listen_path = packet_get_string(NULL);
                   1866:        /* XXX: Skip reserved field for now. */
                   1867:        if (packet_get_string_ptr(NULL) == NULL)
                   1868:                fatal("%s: packet_get_string_ptr failed", __func__);
                   1869:        packet_check_eom();
                   1870:
                   1871:        debug("%s: %s", __func__, listen_path);
                   1872:
                   1873:        c = channel_connect_by_listen_path(listen_path,
                   1874:            "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
                   1875:        free(listen_path);
                   1876:        return c;
                   1877: }
                   1878:
                   1879: static Channel *
1.40      markus   1880: client_request_x11(const char *request_type, int rchan)
                   1881: {
                   1882:        Channel *c = NULL;
                   1883:        char *originator;
1.208     djm      1884:        u_short originator_port;
1.67      markus   1885:        int sock;
1.40      markus   1886:
                   1887:        if (!options.forward_x11) {
                   1888:                error("Warning: ssh server tried X11 forwarding.");
1.197     djm      1889:                error("Warning: this is probably a break-in attempt by a "
                   1890:                    "malicious server.");
1.221     djm      1891:                return NULL;
                   1892:        }
1.274   ! djm      1893:        if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1.221     djm      1894:                verbose("Rejected X11 connection after ForwardX11Timeout "
                   1895:                    "expired");
1.40      markus   1896:                return NULL;
                   1897:        }
                   1898:        originator = packet_get_string(NULL);
                   1899:        if (datafellows & SSH_BUG_X11FWD) {
                   1900:                debug2("buggy server: x11 request w/o originator_port");
                   1901:                originator_port = 0;
                   1902:        } else {
                   1903:                originator_port = packet_get_int();
                   1904:        }
1.93      markus   1905:        packet_check_eom();
1.40      markus   1906:        /* XXX check permission */
1.47      markus   1907:        debug("client_request_x11: request from %s %d", originator,
                   1908:            originator_port);
1.250     djm      1909:        free(originator);
1.40      markus   1910:        sock = x11_connect_display();
1.67      markus   1911:        if (sock < 0)
                   1912:                return NULL;
                   1913:        c = channel_new("x11",
                   1914:            SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1.110     markus   1915:            CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1.82      markus   1916:        c->force_drain = 1;
1.40      markus   1917:        return c;
                   1918: }
                   1919:
1.103     deraadt  1920: static Channel *
1.40      markus   1921: client_request_agent(const char *request_type, int rchan)
                   1922: {
                   1923:        Channel *c = NULL;
1.262     djm      1924:        int r, sock;
1.40      markus   1925:
                   1926:        if (!options.forward_agent) {
                   1927:                error("Warning: ssh server tried agent forwarding.");
1.197     djm      1928:                error("Warning: this is probably a break-in attempt by a "
                   1929:                    "malicious server.");
1.40      markus   1930:                return NULL;
                   1931:        }
1.262     djm      1932:        if ((r = ssh_get_authentication_socket(&sock)) != 0) {
                   1933:                if (r != SSH_ERR_AGENT_NOT_PRESENT)
                   1934:                        debug("%s: ssh_get_authentication_socket: %s",
                   1935:                            __func__, ssh_err(r));
1.67      markus   1936:                return NULL;
1.262     djm      1937:        }
1.67      markus   1938:        c = channel_new("authentication agent connection",
                   1939:            SSH_CHANNEL_OPEN, sock, sock, -1,
1.185     dtucker  1940:            CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1.110     markus   1941:            "authentication agent connection", 1);
1.82      markus   1942:        c->force_drain = 1;
1.40      markus   1943:        return c;
1.180     djm      1944: }
                   1945:
                   1946: int
                   1947: client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
                   1948: {
                   1949:        Channel *c;
                   1950:        int fd;
                   1951:
                   1952:        if (tun_mode == SSH_TUNMODE_NO)
                   1953:                return 0;
                   1954:
                   1955:        if (!compat20) {
1.207     stevesk  1956:                error("Tunnel forwarding is not supported for protocol 1");
1.180     djm      1957:                return -1;
                   1958:        }
                   1959:
                   1960:        debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
                   1961:
                   1962:        /* Open local tunnel device */
                   1963:        if ((fd = tun_open(local_tun, tun_mode)) == -1) {
                   1964:                error("Tunnel device open failed.");
                   1965:                return -1;
                   1966:        }
                   1967:
                   1968:        c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
                   1969:            CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
                   1970:        c->datagram = 1;
                   1971:
                   1972:        packet_start(SSH2_MSG_CHANNEL_OPEN);
                   1973:        packet_put_cstring("tun@openssh.com");
                   1974:        packet_put_int(c->self);
                   1975:        packet_put_int(c->local_window_max);
                   1976:        packet_put_int(c->local_maxpacket);
                   1977:        packet_put_int(tun_mode);
                   1978:        packet_put_int(remote_tun);
                   1979:        packet_send();
                   1980:
                   1981:        return 0;
1.40      markus   1982: }
                   1983:
1.22      markus   1984: /* XXXX move to generic input handler */
1.264     markus   1985: static int
1.94      markus   1986: client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1.22      markus   1987: {
                   1988:        Channel *c = NULL;
                   1989:        char *ctype;
                   1990:        int rchan;
1.102     markus   1991:        u_int rmaxpack, rwindow, len;
1.22      markus   1992:
                   1993:        ctype = packet_get_string(&len);
                   1994:        rchan = packet_get_int();
                   1995:        rwindow = packet_get_int();
                   1996:        rmaxpack = packet_get_int();
                   1997:
1.24      markus   1998:        debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1.22      markus   1999:            ctype, rchan, rwindow, rmaxpack);
                   2000:
1.40      markus   2001:        if (strcmp(ctype, "forwarded-tcpip") == 0) {
                   2002:                c = client_request_forwarded_tcpip(ctype, rchan);
1.261     millert  2003:        } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
                   2004:                c = client_request_forwarded_streamlocal(ctype, rchan);
1.40      markus   2005:        } else if (strcmp(ctype, "x11") == 0) {
                   2006:                c = client_request_x11(ctype, rchan);
                   2007:        } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
                   2008:                c = client_request_agent(ctype, rchan);
1.22      markus   2009:        }
                   2010: /* XXX duplicate : */
                   2011:        if (c != NULL) {
                   2012:                debug("confirm %s", ctype);
                   2013:                c->remote_id = rchan;
                   2014:                c->remote_window = rwindow;
                   2015:                c->remote_maxpacket = rmaxpack;
1.69      markus   2016:                if (c->type != SSH_CHANNEL_CONNECTING) {
                   2017:                        packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
                   2018:                        packet_put_int(c->remote_id);
                   2019:                        packet_put_int(c->self);
                   2020:                        packet_put_int(c->local_window);
                   2021:                        packet_put_int(c->local_maxpacket);
                   2022:                        packet_send();
                   2023:                }
1.22      markus   2024:        } else {
                   2025:                debug("failure %s", ctype);
                   2026:                packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
                   2027:                packet_put_int(rchan);
                   2028:                packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1.66      markus   2029:                if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1.69      markus   2030:                        packet_put_cstring("open failed");
1.66      markus   2031:                        packet_put_cstring("");
                   2032:                }
1.22      markus   2033:                packet_send();
                   2034:        }
1.250     djm      2035:        free(ctype);
1.264     markus   2036:        return 0;
1.22      markus   2037: }
1.267     djm      2038:
1.264     markus   2039: static int
1.94      markus   2040: client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1.48      markus   2041: {
                   2042:        Channel *c = NULL;
1.123     djm      2043:        int exitval, id, reply, success = 0;
1.48      markus   2044:        char *rtype;
                   2045:
                   2046:        id = packet_get_int();
                   2047:        rtype = packet_get_string(NULL);
                   2048:        reply = packet_get_char();
                   2049:
                   2050:        debug("client_input_channel_req: channel %d rtype %s reply %d",
                   2051:            id, rtype, reply);
                   2052:
1.128     djm      2053:        if (id == -1) {
                   2054:                error("client_input_channel_req: request for channel -1");
                   2055:        } else if ((c = channel_lookup(id)) == NULL) {
1.197     djm      2056:                error("client_input_channel_req: channel %d: "
                   2057:                    "unknown channel", id);
1.193     markus   2058:        } else if (strcmp(rtype, "eow@openssh.com") == 0) {
                   2059:                packet_check_eom();
                   2060:                chan_rcvd_eow(c);
1.48      markus   2061:        } else if (strcmp(rtype, "exit-status") == 0) {
1.123     djm      2062:                exitval = packet_get_int();
1.217     djm      2063:                if (c->ctl_chan != -1) {
                   2064:                        mux_exit_message(c, exitval);
1.215     djm      2065:                        success = 1;
                   2066:                } else if (id == session_ident) {
                   2067:                        /* Record exit value of local session */
1.123     djm      2068:                        success = 1;
                   2069:                        exit_status = exitval;
1.215     djm      2070:                } else {
1.218     djm      2071:                        /* Probably for a mux channel that has already closed */
                   2072:                        debug("%s: no sink for exit-status on channel %d",
                   2073:                            __func__, id);
1.123     djm      2074:                }
1.93      markus   2075:                packet_check_eom();
1.48      markus   2076:        }
1.259     djm      2077:        if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
1.48      markus   2078:                packet_start(success ?
                   2079:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1.205     markus   2080:                packet_put_int(c->remote_id);
1.48      markus   2081:                packet_send();
                   2082:        }
1.250     djm      2083:        free(rtype);
1.264     markus   2084:        return 0;
1.48      markus   2085: }
1.267     djm      2086:
1.269     djm      2087: struct hostkeys_update_ctx {
                   2088:        /* The hostname and (optionally) IP address string for the server */
                   2089:        char *host_str, *ip_str;
                   2090:
                   2091:        /*
                   2092:         * Keys received from the server and a flag for each indicating
                   2093:         * whether they already exist in known_hosts.
                   2094:         * keys_seen is filled in by hostkeys_find() and later (for new
                   2095:         * keys) by client_global_hostkeys_private_confirm().
                   2096:         */
                   2097:        struct sshkey **keys;
                   2098:        int *keys_seen;
                   2099:        size_t nkeys;
                   2100:
                   2101:        size_t nnew;
                   2102:
                   2103:        /*
                   2104:         * Keys that are in known_hosts, but were not present in the update
                   2105:         * from the server (i.e. scheduled to be deleted).
                   2106:         * Filled in by hostkeys_find().
                   2107:         */
                   2108:        struct sshkey **old_keys;
                   2109:        size_t nold;
                   2110: };
                   2111:
                   2112: static void
                   2113: hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
                   2114: {
                   2115:        size_t i;
                   2116:
                   2117:        if (ctx == NULL)
                   2118:                return;
                   2119:        for (i = 0; i < ctx->nkeys; i++)
                   2120:                sshkey_free(ctx->keys[i]);
                   2121:        free(ctx->keys);
                   2122:        free(ctx->keys_seen);
                   2123:        for (i = 0; i < ctx->nold; i++)
                   2124:                sshkey_free(ctx->old_keys[i]);
                   2125:        free(ctx->old_keys);
                   2126:        free(ctx->host_str);
                   2127:        free(ctx->ip_str);
                   2128:        free(ctx);
                   2129: }
                   2130:
                   2131: static int
                   2132: hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
                   2133: {
                   2134:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2135:        size_t i;
                   2136:        struct sshkey **tmp;
                   2137:
                   2138:        if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
                   2139:            l->key->type == KEY_RSA1)
                   2140:                return 0;
                   2141:
                   2142:        /* Mark off keys we've already seen for this host */
                   2143:        for (i = 0; i < ctx->nkeys; i++) {
                   2144:                if (sshkey_equal(l->key, ctx->keys[i])) {
                   2145:                        debug3("%s: found %s key at %s:%ld", __func__,
                   2146:                            sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
                   2147:                        ctx->keys_seen[i] = 1;
                   2148:                        return 0;
                   2149:                }
                   2150:        }
                   2151:        /* This line contained a key that not offered by the server */
                   2152:        debug3("%s: deprecated %s key at %s:%ld", __func__,
                   2153:            sshkey_ssh_name(l->key), l->path, l->linenum);
                   2154:        if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
                   2155:            sizeof(*ctx->old_keys))) == NULL)
                   2156:                fatal("%s: reallocarray failed nold = %zu",
                   2157:                    __func__, ctx->nold);
                   2158:        ctx->old_keys = tmp;
                   2159:        ctx->old_keys[ctx->nold++] = l->key;
                   2160:        l->key = NULL;
                   2161:
                   2162:        return 0;
                   2163: }
                   2164:
                   2165: static void
                   2166: update_known_hosts(struct hostkeys_update_ctx *ctx)
                   2167: {
1.271     djm      2168:        int r, was_raw = 0;
                   2169:        int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
1.269     djm      2170:            SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
                   2171:        char *fp, *response;
                   2172:        size_t i;
                   2173:
                   2174:        for (i = 0; i < ctx->nkeys; i++) {
                   2175:                if (ctx->keys_seen[i] != 2)
                   2176:                        continue;
                   2177:                if ((fp = sshkey_fingerprint(ctx->keys[i],
                   2178:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
                   2179:                        fatal("%s: sshkey_fingerprint failed", __func__);
                   2180:                do_log2(loglevel, "Learned new hostkey: %s %s",
                   2181:                    sshkey_type(ctx->keys[i]), fp);
                   2182:                free(fp);
                   2183:        }
                   2184:        for (i = 0; i < ctx->nold; i++) {
                   2185:                if ((fp = sshkey_fingerprint(ctx->old_keys[i],
                   2186:                    options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
                   2187:                        fatal("%s: sshkey_fingerprint failed", __func__);
                   2188:                do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
                   2189:                    sshkey_type(ctx->old_keys[i]), fp);
                   2190:                free(fp);
                   2191:        }
                   2192:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
1.271     djm      2193:                if (get_saved_tio() != NULL) {
                   2194:                        leave_raw_mode(1);
                   2195:                        was_raw = 1;
                   2196:                }
1.269     djm      2197:                response = NULL;
                   2198:                for (i = 0; !quit_pending && i < 3; i++) {
                   2199:                        free(response);
                   2200:                        response = read_passphrase("Accept updated hostkeys? "
                   2201:                            "(yes/no): ", RP_ECHO);
                   2202:                        if (strcasecmp(response, "yes") == 0)
                   2203:                                break;
                   2204:                        else if (quit_pending || response == NULL ||
                   2205:                            strcasecmp(response, "no") == 0) {
                   2206:                                options.update_hostkeys = 0;
                   2207:                                break;
                   2208:                        } else {
                   2209:                                do_log2(loglevel, "Please enter "
                   2210:                                    "\"yes\" or \"no\"");
                   2211:                        }
                   2212:                }
                   2213:                if (quit_pending || i >= 3 || response == NULL)
                   2214:                        options.update_hostkeys = 0;
                   2215:                free(response);
1.271     djm      2216:                if (was_raw)
                   2217:                        enter_raw_mode(1);
1.269     djm      2218:        }
                   2219:
                   2220:        /*
                   2221:         * Now that all the keys are verified, we can go ahead and replace
                   2222:         * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
                   2223:         * cancel the operation).
                   2224:         */
                   2225:        if (options.update_hostkeys != 0 &&
                   2226:            (r = hostfile_replace_entries(options.user_hostfiles[0],
                   2227:            ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
                   2228:            options.hash_known_hosts, 0,
                   2229:            options.fingerprint_hash)) != 0)
                   2230:                error("%s: hostfile_replace_entries failed: %s",
                   2231:                    __func__, ssh_err(r));
                   2232: }
                   2233:
                   2234: static void
                   2235: client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
                   2236: {
                   2237:        struct ssh *ssh = active_state; /* XXX */
                   2238:        struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
                   2239:        size_t i, ndone;
                   2240:        struct sshbuf *signdata;
                   2241:        int r;
                   2242:        const u_char *sig;
                   2243:        size_t siglen;
                   2244:
                   2245:        if (ctx->nnew == 0)
                   2246:                fatal("%s: ctx->nnew == 0", __func__); /* sanity */
                   2247:        if (type != SSH2_MSG_REQUEST_SUCCESS) {
                   2248:                error("Server failed to confirm ownership of "
                   2249:                    "private host keys");
                   2250:                hostkeys_update_ctx_free(ctx);
                   2251:                return;
                   2252:        }
                   2253:        if ((signdata = sshbuf_new()) == NULL)
                   2254:                fatal("%s: sshbuf_new failed", __func__);
                   2255:        /* Don't want to accidentally accept an unbound signature */
                   2256:        if (ssh->kex->session_id_len == 0)
                   2257:                fatal("%s: ssh->kex->session_id_len == 0", __func__);
                   2258:        /*
                   2259:         * Expect a signature for each of the ctx->nnew private keys we
                   2260:         * haven't seen before. They will be in the same order as the
                   2261:         * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
                   2262:         */
                   2263:        for (ndone = i = 0; i < ctx->nkeys; i++) {
                   2264:                if (ctx->keys_seen[i])
                   2265:                        continue;
                   2266:                /* Prepare data to be signed: session ID, unique string, key */
                   2267:                sshbuf_reset(signdata);
1.270     djm      2268:                if ( (r = sshbuf_put_cstring(signdata,
                   2269:                    "hostkeys-prove-00@openssh.com")) != 0 ||
                   2270:                    (r = sshbuf_put_string(signdata, ssh->kex->session_id,
1.269     djm      2271:                    ssh->kex->session_id_len)) != 0 ||
                   2272:                    (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
                   2273:                        fatal("%s: failed to prepare signature: %s",
                   2274:                            __func__, ssh_err(r));
                   2275:                /* Extract and verify signature */
                   2276:                if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
                   2277:                        error("%s: couldn't parse message: %s",
                   2278:                            __func__, ssh_err(r));
                   2279:                        goto out;
                   2280:                }
                   2281:                if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
                   2282:                    sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
                   2283:                        error("%s: server gave bad signature for %s key %zu",
                   2284:                            __func__, sshkey_type(ctx->keys[i]), i);
                   2285:                        goto out;
                   2286:                }
                   2287:                /* Key is good. Mark it as 'seen' */
                   2288:                ctx->keys_seen[i] = 2;
                   2289:                ndone++;
                   2290:        }
                   2291:        if (ndone != ctx->nnew)
                   2292:                fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
                   2293:                    ndone, ctx->nnew);  /* Shouldn't happen */
                   2294:        ssh_packet_check_eom(ssh);
                   2295:
                   2296:        /* Make the edits to known_hosts */
                   2297:        update_known_hosts(ctx);
                   2298:  out:
                   2299:        hostkeys_update_ctx_free(ctx);
                   2300: }
                   2301:
1.267     djm      2302: /*
1.270     djm      2303:  * Handle hostkeys-00@openssh.com global request to inform the client of all
1.267     djm      2304:  * the server's hostkeys. The keys are checked against the user's
                   2305:  * HostkeyAlgorithms preference before they are accepted.
                   2306:  */
                   2307: static int
                   2308: client_input_hostkeys(void)
                   2309: {
1.269     djm      2310:        struct ssh *ssh = active_state; /* XXX */
1.267     djm      2311:        const u_char *blob = NULL;
1.269     djm      2312:        size_t i, len = 0;
1.267     djm      2313:        struct sshbuf *buf = NULL;
1.269     djm      2314:        struct sshkey *key = NULL, **tmp;
                   2315:        int r;
                   2316:        char *fp;
1.267     djm      2317:        static int hostkeys_seen = 0; /* XXX use struct ssh */
1.268     djm      2318:        extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
1.272     djm      2319:        struct hostkeys_update_ctx *ctx = NULL;
1.267     djm      2320:
                   2321:        if (hostkeys_seen)
                   2322:                fatal("%s: server already sent hostkeys", __func__);
1.269     djm      2323:        if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
                   2324:            options.batch_mode)
                   2325:                return 1; /* won't ask in batchmode, so don't even try */
1.267     djm      2326:        if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
                   2327:                return 1;
1.272     djm      2328:
                   2329:        ctx = xcalloc(1, sizeof(*ctx));
1.269     djm      2330:        while (ssh_packet_remaining(ssh) > 0) {
1.267     djm      2331:                sshkey_free(key);
                   2332:                key = NULL;
1.269     djm      2333:                if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
                   2334:                        error("%s: couldn't parse message: %s",
                   2335:                            __func__, ssh_err(r));
                   2336:                        goto out;
                   2337:                }
1.270     djm      2338:                if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
                   2339:                        error("%s: parse key: %s", __func__, ssh_err(r));
                   2340:                        goto out;
                   2341:                }
1.267     djm      2342:                fp = sshkey_fingerprint(key, options.fingerprint_hash,
                   2343:                    SSH_FP_DEFAULT);
                   2344:                debug3("%s: received %s key %s", __func__,
                   2345:                    sshkey_type(key), fp);
                   2346:                free(fp);
                   2347:                /* Check that the key is accepted in HostkeyAlgorithms */
                   2348:                if (options.hostkeyalgorithms != NULL &&
                   2349:                    match_pattern_list(sshkey_ssh_name(key),
1.273     djm      2350:                    options.hostkeyalgorithms, 0) != 1) {
1.267     djm      2351:                        debug3("%s: %s key not permitted by HostkeyAlgorithms",
                   2352:                            __func__, sshkey_ssh_name(key));
                   2353:                        continue;
                   2354:                }
1.269     djm      2355:                /* Skip certs */
                   2356:                if (sshkey_is_cert(key)) {
                   2357:                        debug3("%s: %s key is a certificate; skipping",
                   2358:                            __func__, sshkey_ssh_name(key));
                   2359:                        continue;
                   2360:                }
                   2361:                /* Ensure keys are unique */
                   2362:                for (i = 0; i < ctx->nkeys; i++) {
                   2363:                        if (sshkey_equal(key, ctx->keys[i])) {
                   2364:                                error("%s: received duplicated %s host key",
                   2365:                                    __func__, sshkey_ssh_name(key));
                   2366:                                goto out;
                   2367:                        }
                   2368:                }
                   2369:                /* Key is good, record it */
                   2370:                if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
                   2371:                    sizeof(*ctx->keys))) == NULL)
                   2372:                        fatal("%s: reallocarray failed nkeys = %zu",
                   2373:                            __func__, ctx->nkeys);
                   2374:                ctx->keys = tmp;
                   2375:                ctx->keys[ctx->nkeys++] = key;
1.267     djm      2376:                key = NULL;
                   2377:        }
                   2378:
1.269     djm      2379:        if (ctx->nkeys == 0) {
1.270     djm      2380:                debug("%s: server sent no hostkeys", __func__);
1.267     djm      2381:                goto out;
                   2382:        }
1.270     djm      2383:
1.269     djm      2384:        if ((ctx->keys_seen = calloc(ctx->nkeys,
                   2385:            sizeof(*ctx->keys_seen))) == NULL)
                   2386:                fatal("%s: calloc failed", __func__);
1.267     djm      2387:
1.268     djm      2388:        get_hostfile_hostname_ipaddr(host,
                   2389:            options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
1.269     djm      2390:            options.port, &ctx->host_str,
                   2391:            options.check_host_ip ? &ctx->ip_str : NULL);
1.268     djm      2392:
1.269     djm      2393:        /* Find which keys we already know about. */
                   2394:        if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
                   2395:            ctx, ctx->host_str, ctx->ip_str,
                   2396:            HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
                   2397:                error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
1.267     djm      2398:                goto out;
                   2399:        }
                   2400:
1.269     djm      2401:        /* Figure out if we have any new keys to add */
                   2402:        ctx->nnew = 0;
                   2403:        for (i = 0; i < ctx->nkeys; i++) {
                   2404:                if (!ctx->keys_seen[i])
                   2405:                        ctx->nnew++;
                   2406:        }
                   2407:
                   2408:        debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
                   2409:            __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
                   2410:
                   2411:        if (ctx->nnew == 0 && ctx->nold != 0) {
                   2412:                /* We have some keys to remove. Just do it. */
                   2413:                update_known_hosts(ctx);
                   2414:        } else if (ctx->nnew != 0) {
                   2415:                /*
                   2416:                 * We have received hitherto-unseen keys from the server.
                   2417:                 * Ask the server to confirm ownership of the private halves.
                   2418:                 */
                   2419:                debug3("%s: asking server to prove ownership for %zu keys",
                   2420:                    __func__, ctx->nnew);
                   2421:                if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
                   2422:                    (r = sshpkt_put_cstring(ssh,
1.270     djm      2423:                    "hostkeys-prove-00@openssh.com")) != 0 ||
1.269     djm      2424:                    (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
                   2425:                        fatal("%s: cannot prepare packet: %s",
                   2426:                            __func__, ssh_err(r));
                   2427:                if ((buf = sshbuf_new()) == NULL)
                   2428:                        fatal("%s: sshbuf_new", __func__);
                   2429:                for (i = 0; i < ctx->nkeys; i++) {
                   2430:                        if (ctx->keys_seen[i])
                   2431:                                continue;
                   2432:                        sshbuf_reset(buf);
                   2433:                        if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
                   2434:                                fatal("%s: sshkey_putb: %s",
                   2435:                                    __func__, ssh_err(r));
                   2436:                        if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
                   2437:                                fatal("%s: sshpkt_put_string: %s",
                   2438:                                    __func__, ssh_err(r));
                   2439:                }
                   2440:                if ((r = sshpkt_send(ssh)) != 0)
                   2441:                        fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
                   2442:                client_register_global_confirm(
                   2443:                    client_global_hostkeys_private_confirm, ctx);
                   2444:                ctx = NULL;  /* will be freed in callback */
                   2445:        }
                   2446:
1.267     djm      2447:        /* Success */
                   2448:  out:
1.269     djm      2449:        hostkeys_update_ctx_free(ctx);
1.267     djm      2450:        sshkey_free(key);
                   2451:        sshbuf_free(buf);
1.269     djm      2452:        /*
                   2453:         * NB. Return success for all cases. The server doesn't need to know
                   2454:         * what the client does with its hosts file.
                   2455:         */
                   2456:        return 1;
1.267     djm      2457: }
                   2458:
1.264     markus   2459: static int
1.95      markus   2460: client_input_global_request(int type, u_int32_t seq, void *ctxt)
                   2461: {
                   2462:        char *rtype;
                   2463:        int want_reply;
                   2464:        int success = 0;
                   2465:
1.267     djm      2466:        rtype = packet_get_cstring(NULL);
1.95      markus   2467:        want_reply = packet_get_char();
1.117     markus   2468:        debug("client_input_global_request: rtype %s want_reply %d",
                   2469:            rtype, want_reply);
1.270     djm      2470:        if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
1.267     djm      2471:                success = client_input_hostkeys();
1.95      markus   2472:        if (want_reply) {
                   2473:                packet_start(success ?
                   2474:                    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
                   2475:                packet_send();
                   2476:                packet_write_wait();
                   2477:        }
1.250     djm      2478:        free(rtype);
1.264     markus   2479:        return 0;
1.95      markus   2480: }
1.22      markus   2481:
1.123     djm      2482: void
1.129     deraadt  2483: client_session2_setup(int id, int want_tty, int want_subsystem,
1.190     djm      2484:     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1.123     djm      2485: {
                   2486:        int len;
1.132     djm      2487:        Channel *c = NULL;
1.123     djm      2488:
                   2489:        debug2("%s: id %d", __func__, id);
                   2490:
1.132     djm      2491:        if ((c = channel_lookup(id)) == NULL)
                   2492:                fatal("client_session2_setup: channel %d: unknown channel", id);
1.224     djm      2493:
                   2494:        packet_set_interactive(want_tty,
                   2495:            options.ip_qos_interactive, options.ip_qos_bulk);
1.132     djm      2496:
1.123     djm      2497:        if (want_tty) {
                   2498:                struct winsize ws;
                   2499:
                   2500:                /* Store window size in the packet. */
                   2501:                if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
                   2502:                        memset(&ws, 0, sizeof(ws));
                   2503:
1.190     djm      2504:                channel_request_start(id, "pty-req", 1);
1.234     djm      2505:                client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
1.123     djm      2506:                packet_put_cstring(term != NULL ? term : "");
1.158     deraadt  2507:                packet_put_int((u_int)ws.ws_col);
                   2508:                packet_put_int((u_int)ws.ws_row);
                   2509:                packet_put_int((u_int)ws.ws_xpixel);
                   2510:                packet_put_int((u_int)ws.ws_ypixel);
1.194     djm      2511:                if (tiop == NULL)
                   2512:                        tiop = get_saved_tio();
                   2513:                tty_make_modes(-1, tiop);
1.123     djm      2514:                packet_send();
                   2515:                /* XXX wait for reply */
1.132     djm      2516:                c->client_tty = 1;
1.123     djm      2517:        }
                   2518:
                   2519:        /* Transfer any environment variables from client to server */
1.126     djm      2520:        if (options.num_send_env != 0 && env != NULL) {
1.123     djm      2521:                int i, j, matched;
                   2522:                char *name, *val;
                   2523:
                   2524:                debug("Sending environment.");
1.126     djm      2525:                for (i = 0; env[i] != NULL; i++) {
1.123     djm      2526:                        /* Split */
1.126     djm      2527:                        name = xstrdup(env[i]);
1.123     djm      2528:                        if ((val = strchr(name, '=')) == NULL) {
1.250     djm      2529:                                free(name);
1.123     djm      2530:                                continue;
                   2531:                        }
                   2532:                        *val++ = '\0';
                   2533:
                   2534:                        matched = 0;
                   2535:                        for (j = 0; j < options.num_send_env; j++) {
                   2536:                                if (match_pattern(name, options.send_env[j])) {
                   2537:                                        matched = 1;
                   2538:                                        break;
                   2539:                                }
                   2540:                        }
                   2541:                        if (!matched) {
                   2542:                                debug3("Ignored env %s", name);
1.250     djm      2543:                                free(name);
1.123     djm      2544:                                continue;
                   2545:                        }
                   2546:
                   2547:                        debug("Sending env %s = %s", name, val);
                   2548:                        channel_request_start(id, "env", 0);
                   2549:                        packet_put_cstring(name);
                   2550:                        packet_put_cstring(val);
                   2551:                        packet_send();
1.250     djm      2552:                        free(name);
1.123     djm      2553:                }
                   2554:        }
                   2555:
                   2556:        len = buffer_len(cmd);
                   2557:        if (len > 0) {
                   2558:                if (len > 900)
                   2559:                        len = 900;
                   2560:                if (want_subsystem) {
1.190     djm      2561:                        debug("Sending subsystem: %.*s",
                   2562:                            len, (u_char*)buffer_ptr(cmd));
                   2563:                        channel_request_start(id, "subsystem", 1);
1.234     djm      2564:                        client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
1.123     djm      2565:                } else {
1.190     djm      2566:                        debug("Sending command: %.*s",
                   2567:                            len, (u_char*)buffer_ptr(cmd));
                   2568:                        channel_request_start(id, "exec", 1);
1.234     djm      2569:                        client_expect_confirm(id, "exec", CONFIRM_CLOSE);
1.123     djm      2570:                }
                   2571:                packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
                   2572:                packet_send();
                   2573:        } else {
1.190     djm      2574:                channel_request_start(id, "shell", 1);
1.234     djm      2575:                client_expect_confirm(id, "shell", CONFIRM_CLOSE);
1.123     djm      2576:                packet_send();
                   2577:        }
                   2578: }
                   2579:
1.77      itojun   2580: static void
1.49      itojun   2581: client_init_dispatch_20(void)
1.16      markus   2582: {
1.55      markus   2583:        dispatch_init(&dispatch_protocol_error);
1.100     markus   2584:
1.16      markus   2585:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
                   2586:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
                   2587:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
                   2588:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1.22      markus   2589:        dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1.16      markus   2590:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2591:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1.48      markus   2592:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1.16      markus   2593:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1.189     djm      2594:        dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
                   2595:        dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
1.95      markus   2596:        dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1.55      markus   2597:
                   2598:        /* rekeying */
                   2599:        dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1.100     markus   2600:
                   2601:        /* global request reply messages */
                   2602:        dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
                   2603:        dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1.16      markus   2604: }
1.197     djm      2605:
1.77      itojun   2606: static void
1.49      itojun   2607: client_init_dispatch_13(void)
1.15      markus   2608: {
                   2609:        dispatch_init(NULL);
                   2610:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                   2611:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                   2612:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                   2613:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                   2614:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                   2615:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                   2616:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                   2617:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                   2618:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1.39      markus   2619:
                   2620:        dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1.115     markus   2621:            &client_input_agent_open : &deny_input_open);
1.39      markus   2622:        dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
                   2623:            &x11_input_open : &deny_input_open);
1.15      markus   2624: }
1.197     djm      2625:
1.77      itojun   2626: static void
1.49      itojun   2627: client_init_dispatch_15(void)
1.15      markus   2628: {
                   2629:        client_init_dispatch_13();
                   2630:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                   2631:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                   2632: }
1.197     djm      2633:
1.79      stevesk  2634: static void
1.49      itojun   2635: client_init_dispatch(void)
1.15      markus   2636: {
1.16      markus   2637:        if (compat20)
                   2638:                client_init_dispatch_20();
                   2639:        else if (compat13)
1.15      markus   2640:                client_init_dispatch_13();
                   2641:        else
                   2642:                client_init_dispatch_15();
1.232     djm      2643: }
                   2644:
                   2645: void
                   2646: client_stop_mux(void)
                   2647: {
                   2648:        if (options.control_path != NULL && muxserver_sock != -1)
                   2649:                unlink(options.control_path);
                   2650:        /*
1.247     dtucker  2651:         * If we are in persist mode, or don't have a shell, signal that we
                   2652:         * should close when all active channels are closed.
1.232     djm      2653:         */
1.247     dtucker  2654:        if (options.control_persist || no_shell_flag) {
1.232     djm      2655:                session_closed = 1;
1.235     djm      2656:                setproctitle("[stopped mux]");
                   2657:        }
1.113     markus   2658: }
                   2659:
                   2660: /* client specific fatal cleanup */
                   2661: void
1.114     markus   2662: cleanup_exit(int i)
1.113     markus   2663: {
1.233     djm      2664:        leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1.113     markus   2665:        leave_non_blocking();
1.192     djm      2666:        if (options.control_path != NULL && muxserver_sock != -1)
1.123     djm      2667:                unlink(options.control_path);
1.223     djm      2668:        ssh_kill_proxy_command();
1.114     markus   2669:        _exit(i);
1.1       deraadt  2670: }