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

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