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

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