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

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