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

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