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

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