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

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