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

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