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

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