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

1.1       deraadt     1: /*
1.12      deraadt     2:  *
                      3:  * clientloop.c
                      4:  *
                      5:  * Author: Tatu Ylonen <ylo@cs.hut.fi>
                      6:  *
                      7:  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
                      8:  *                    All rights reserved
                      9:  *
                     10:  *
                     11:  * Created: Sat Sep 23 12:23:57 1995 ylo
                     12:  *
                     13:  * The main loop for the interactive session (client side).
                     14:  *
1.16    ! markus     15:  * SSH2 support added by Markus Friedl.
1.12      deraadt    16:  */
1.1       deraadt    17:
                     18: #include "includes.h"
1.16    ! markus     19: RCSID("$Id: clientloop.c,v 1.12 2000/03/31 09:40:42 markus Exp $");
1.1       deraadt    20:
                     21: #include "xmalloc.h"
                     22: #include "ssh.h"
                     23: #include "packet.h"
                     24: #include "buffer.h"
                     25: #include "authfd.h"
1.8       markus     26: #include "readconf.h"
1.1       deraadt    27:
1.16    ! markus     28: #include "ssh2.h"
1.15      markus     29: #include "compat.h"
                     30: #include "channels.h"
                     31: #include "dispatch.h"
                     32:
                     33:
1.1       deraadt    34: /* Flag indicating that stdin should be redirected from /dev/null. */
                     35: extern int stdin_null_flag;
                     36:
1.13      markus     37: /*
                     38:  * Name of the host we are connecting to.  This is the name given on the
                     39:  * command line, or the HostName specified for the user-supplied name in a
                     40:  * configuration file.
                     41:  */
1.1       deraadt    42: extern char *host;
                     43:
1.13      markus     44: /*
                     45:  * Flag to indicate that we have received a window change signal which has
                     46:  * not yet been processed.  This will cause a message indicating the new
                     47:  * window size to be sent to the server a little later.  This is volatile
                     48:  * because this is updated in a signal handler.
                     49:  */
1.1       deraadt    50: static volatile int received_window_change_signal = 0;
                     51:
                     52: /* Terminal modes, as saved by enter_raw_mode. */
                     53: static struct termios saved_tio;
                     54:
1.13      markus     55: /*
                     56:  * Flag indicating whether we are in raw mode.  This is used by
                     57:  * enter_raw_mode and leave_raw_mode.
                     58:  */
1.1       deraadt    59: static int in_raw_mode = 0;
                     60:
                     61: /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
                     62: static int in_non_blocking_mode = 0;
                     63:
                     64: /* Common data for the client loop code. */
1.11      markus     65: static int escape_pending;     /* Last character was the escape character */
                     66: static int last_was_cr;                /* Last character was a newline. */
                     67: static int exit_status;                /* Used to store the exit status of the command. */
                     68: static int stdin_eof;          /* EOF has been encountered on standard error. */
                     69: static Buffer stdin_buffer;    /* Buffer for stdin data. */
                     70: static Buffer stdout_buffer;   /* Buffer for stdout data. */
                     71: static Buffer stderr_buffer;   /* Buffer for stderr data. */
                     72: static unsigned int buffer_high;/* Soft max buffer size. */
                     73: static int max_fd;             /* Maximum file descriptor number in select(). */
                     74: static int connection_in;      /* Connection to server (input). */
                     75: static int connection_out;     /* Connection to server (output). */
1.1       deraadt    76: static unsigned long stdin_bytes, stdout_bytes, stderr_bytes;
1.11      markus     77: static int quit_pending;       /* Set to non-zero to quit the client loop. */
                     78: static int escape_char;                /* Escape character. */
1.1       deraadt    79:
1.16    ! markus     80:
        !            81: void   client_init_dispatch(void);
        !            82: int    session_ident = -1;
        !            83:
1.13      markus     84: /* Returns the user\'s terminal to normal mode if it had been put in raw mode. */
1.1       deraadt    85:
1.11      markus     86: void
                     87: leave_raw_mode()
1.1       deraadt    88: {
1.11      markus     89:        if (!in_raw_mode)
                     90:                return;
                     91:        in_raw_mode = 0;
                     92:        if (tcsetattr(fileno(stdin), TCSADRAIN, &saved_tio) < 0)
                     93:                perror("tcsetattr");
1.1       deraadt    94:
1.11      markus     95:        fatal_remove_cleanup((void (*) (void *)) leave_raw_mode, NULL);
1.1       deraadt    96: }
                     97:
                     98: /* Puts the user\'s terminal in raw mode. */
                     99:
1.11      markus    100: void
                    101: enter_raw_mode()
1.1       deraadt   102: {
1.11      markus    103:        struct termios tio;
1.1       deraadt   104:
1.11      markus    105:        if (tcgetattr(fileno(stdin), &tio) < 0)
                    106:                perror("tcgetattr");
                    107:        saved_tio = tio;
                    108:        tio.c_iflag |= IGNPAR;
                    109:        tio.c_iflag &= ~(ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF);
                    110:        tio.c_lflag &= ~(ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL);
1.1       deraadt   111: #ifdef IEXTEN
1.11      markus    112:        tio.c_lflag &= ~IEXTEN;
                    113: #endif                         /* IEXTEN */
                    114:        tio.c_oflag &= ~OPOST;
                    115:        tio.c_cc[VMIN] = 1;
                    116:        tio.c_cc[VTIME] = 0;
                    117:        if (tcsetattr(fileno(stdin), TCSADRAIN, &tio) < 0)
                    118:                perror("tcsetattr");
                    119:        in_raw_mode = 1;
1.1       deraadt   120:
1.11      markus    121:        fatal_add_cleanup((void (*) (void *)) leave_raw_mode, NULL);
                    122: }
1.1       deraadt   123:
                    124: /* Restores stdin to blocking mode. */
                    125:
1.11      markus    126: void
                    127: leave_non_blocking()
1.1       deraadt   128: {
1.11      markus    129:        if (in_non_blocking_mode) {
                    130:                (void) fcntl(fileno(stdin), F_SETFL, 0);
                    131:                in_non_blocking_mode = 0;
                    132:                fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
                    133:        }
1.1       deraadt   134: }
                    135:
1.11      markus    136: /* Puts stdin terminal in non-blocking mode. */
                    137:
                    138: void
                    139: enter_non_blocking()
1.1       deraadt   140: {
1.11      markus    141:        in_non_blocking_mode = 1;
                    142:        (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
                    143:        fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
1.1       deraadt   144: }
                    145:
1.13      markus    146: /*
                    147:  * Signal handler for the window change signal (SIGWINCH).  This just sets a
                    148:  * flag indicating that the window has changed.
                    149:  */
1.1       deraadt   150:
1.11      markus    151: void
                    152: window_change_handler(int sig)
1.1       deraadt   153: {
1.11      markus    154:        received_window_change_signal = 1;
                    155:        signal(SIGWINCH, window_change_handler);
1.1       deraadt   156: }
                    157:
1.13      markus    158: /*
                    159:  * Signal handler for signals that cause the program to terminate.  These
                    160:  * signals must be trapped to restore terminal modes.
                    161:  */
1.1       deraadt   162:
1.11      markus    163: void
                    164: signal_handler(int sig)
1.1       deraadt   165: {
1.11      markus    166:        if (in_raw_mode)
                    167:                leave_raw_mode();
                    168:        if (in_non_blocking_mode)
                    169:                leave_non_blocking();
                    170:        channel_stop_listening();
                    171:        packet_close();
                    172:        fatal("Killed by signal %d.", sig);
1.1       deraadt   173: }
                    174:
1.13      markus    175: /*
                    176:  * Returns current time in seconds from Jan 1, 1970 with the maximum
                    177:  * available resolution.
                    178:  */
1.1       deraadt   179:
1.11      markus    180: double
                    181: get_current_time()
1.1       deraadt   182: {
1.11      markus    183:        struct timeval tv;
                    184:        gettimeofday(&tv, NULL);
                    185:        return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
1.1       deraadt   186: }
                    187:
1.13      markus    188: /*
                    189:  * This is called when the interactive is entered.  This checks if there is
                    190:  * an EOF coming on stdin.  We must check this explicitly, as select() does
                    191:  * not appear to wake up when redirecting from /dev/null.
                    192:  */
1.1       deraadt   193:
1.11      markus    194: void
                    195: client_check_initial_eof_on_stdin()
1.1       deraadt   196: {
1.11      markus    197:        int len;
                    198:        char buf[1];
1.1       deraadt   199:
1.13      markus    200:        /*
                    201:         * If standard input is to be "redirected from /dev/null", we simply
                    202:         * mark that we have seen an EOF and send an EOF message to the
                    203:         * server. Otherwise, we try to read a single character; it appears
                    204:         * that for some files, such /dev/null, select() never wakes up for
                    205:         * read for this descriptor, which means that we never get EOF.  This
                    206:         * way we will get the EOF if stdin comes from /dev/null or similar.
                    207:         */
1.11      markus    208:        if (stdin_null_flag) {
                    209:                /* Fake EOF on stdin. */
                    210:                debug("Sending eof.");
                    211:                stdin_eof = 1;
                    212:                packet_start(SSH_CMSG_EOF);
                    213:                packet_send();
                    214:        } else {
                    215:                enter_non_blocking();
                    216:
                    217:                /* Check for immediate EOF on stdin. */
                    218:                len = read(fileno(stdin), buf, 1);
                    219:                if (len == 0) {
1.13      markus    220:                        /* EOF.  Record that we have seen it and send EOF to server. */
1.11      markus    221:                        debug("Sending eof.");
                    222:                        stdin_eof = 1;
                    223:                        packet_start(SSH_CMSG_EOF);
                    224:                        packet_send();
                    225:                } else if (len > 0) {
1.13      markus    226:                        /*
                    227:                         * Got data.  We must store the data in the buffer,
                    228:                         * and also process it as an escape character if
                    229:                         * appropriate.
                    230:                         */
1.11      markus    231:                        if ((unsigned char) buf[0] == escape_char)
                    232:                                escape_pending = 1;
                    233:                        else {
                    234:                                buffer_append(&stdin_buffer, buf, 1);
                    235:                                stdin_bytes += 1;
                    236:                        }
                    237:                }
                    238:                leave_non_blocking();
                    239:        }
1.1       deraadt   240: }
                    241:
                    242:
1.13      markus    243: /*
                    244:  * Make packets from buffered stdin data, and buffer them for sending to the
                    245:  * connection.
                    246:  */
1.1       deraadt   247:
1.11      markus    248: void
                    249: client_make_packets_from_stdin_data()
1.1       deraadt   250: {
1.11      markus    251:        unsigned int len;
1.1       deraadt   252:
1.11      markus    253:        /* Send buffered stdin data to the server. */
                    254:        while (buffer_len(&stdin_buffer) > 0 &&
                    255:               packet_not_very_much_data_to_write()) {
                    256:                len = buffer_len(&stdin_buffer);
                    257:                /* Keep the packets at reasonable size. */
                    258:                if (len > packet_get_maxsize())
                    259:                        len = packet_get_maxsize();
                    260:                packet_start(SSH_CMSG_STDIN_DATA);
                    261:                packet_put_string(buffer_ptr(&stdin_buffer), len);
                    262:                packet_send();
                    263:                buffer_consume(&stdin_buffer, len);
                    264:                /* If we have a pending EOF, send it now. */
                    265:                if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
                    266:                        packet_start(SSH_CMSG_EOF);
                    267:                        packet_send();
                    268:                }
1.1       deraadt   269:        }
                    270: }
                    271:
1.13      markus    272: /*
                    273:  * Checks if the client window has changed, and sends a packet about it to
                    274:  * the server if so.  The actual change is detected elsewhere (by a software
                    275:  * interrupt on Unix); this just checks the flag and sends a message if
                    276:  * appropriate.
                    277:  */
1.1       deraadt   278:
1.11      markus    279: void
                    280: client_check_window_change()
1.1       deraadt   281: {
1.16    ! markus    282:        struct winsize ws;
        !           283:
        !           284:        if (! received_window_change_signal)
        !           285:                return;
        !           286:        /** XXX race */
        !           287:        received_window_change_signal = 0;
        !           288:
        !           289:        if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
        !           290:                return;
        !           291:
        !           292:        debug("client_check_window_change: changed");
        !           293:
        !           294:        if (compat20) {
        !           295:                channel_request_start(session_ident, "window-change", 0);
        !           296:                packet_put_int(ws.ws_col);
        !           297:                packet_put_int(ws.ws_row);
        !           298:                packet_put_int(ws.ws_xpixel);
        !           299:                packet_put_int(ws.ws_ypixel);
        !           300:                packet_send();
        !           301:        } else {
        !           302:                packet_start(SSH_CMSG_WINDOW_SIZE);
        !           303:                packet_put_int(ws.ws_row);
        !           304:                packet_put_int(ws.ws_col);
        !           305:                packet_put_int(ws.ws_xpixel);
        !           306:                packet_put_int(ws.ws_ypixel);
        !           307:                packet_send();
1.1       deraadt   308:        }
                    309: }
                    310:
1.13      markus    311: /*
                    312:  * Waits until the client can do something (some data becomes available on
                    313:  * one of the file descriptors).
                    314:  */
1.1       deraadt   315:
1.11      markus    316: void
                    317: client_wait_until_can_do_something(fd_set * readset, fd_set * writeset)
                    318: {
1.16    ! markus    319:        /*debug("client_wait_until_can_do_something"); */
        !           320:
1.11      markus    321:        /* Initialize select masks. */
                    322:        FD_ZERO(readset);
                    323:
                    324:        /* Read from the connection, unless our buffers are full. */
1.16    ! markus    325:        if (!compat20) {
        !           326:                if (buffer_len(&stdout_buffer) < buffer_high &&
        !           327:                    buffer_len(&stderr_buffer) < buffer_high &&
        !           328:                    channel_not_very_much_buffered_data())
        !           329:                        FD_SET(connection_in, readset);
        !           330:        } else {
1.11      markus    331:                FD_SET(connection_in, readset);
1.16    ! markus    332:        }
1.11      markus    333:
1.13      markus    334:        /*
                    335:         * Read from stdin, unless we have seen EOF or have very much
                    336:         * buffered data to send to the server.
                    337:         */
1.16    ! markus    338:        if (!compat20)
        !           339:                if (!stdin_eof && packet_not_very_much_data_to_write())
        !           340:                        FD_SET(fileno(stdin), readset);
1.11      markus    341:
                    342:        FD_ZERO(writeset);
                    343:
                    344:        /* Add any selections by the channel mechanism. */
                    345:        channel_prepare_select(readset, writeset);
                    346:
                    347:        /* Select server connection if have data to write to the server. */
                    348:        if (packet_have_data_to_write())
                    349:                FD_SET(connection_out, writeset);
                    350:
1.16    ! markus    351:        if (!compat20) {
        !           352:                /* Select stdout if have data in buffer. */
        !           353:                if (buffer_len(&stdout_buffer) > 0)
        !           354:                        FD_SET(fileno(stdout), writeset);
        !           355:
        !           356:                /* Select stderr if have data in buffer. */
        !           357:                if (buffer_len(&stderr_buffer) > 0)
        !           358:                        FD_SET(fileno(stderr), writeset);
        !           359:        }
1.11      markus    360:
1.16    ! markus    361: /* move UP XXX */
1.11      markus    362:        /* Update maximum file descriptor number, if appropriate. */
                    363:        if (channel_max_fd() > max_fd)
                    364:                max_fd = channel_max_fd();
                    365:
1.13      markus    366:        /*
                    367:         * Wait for something to happen.  This will suspend the process until
                    368:         * some selected descriptor can be read, written, or has some other
                    369:         * event pending. Note: if you want to implement SSH_MSG_IGNORE
                    370:         * messages to fool traffic analysis, this might be the place to do
                    371:         * it: just have a random timeout for the select, and send a random
                    372:         * SSH_MSG_IGNORE packet when the timeout expires.
                    373:         */
1.11      markus    374:
                    375:        if (select(max_fd + 1, readset, writeset, NULL, NULL) < 0) {
                    376:                char buf[100];
                    377:                /* Some systems fail to clear these automatically. */
                    378:                FD_ZERO(readset);
                    379:                FD_ZERO(writeset);
                    380:                if (errno == EINTR)
                    381:                        return;
                    382:                /* Note: we might still have data in the buffers. */
                    383:                snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
                    384:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    385:                stderr_bytes += strlen(buf);
                    386:                quit_pending = 1;
                    387:        }
                    388: }
                    389:
                    390: void
                    391: client_suspend_self()
1.1       deraadt   392: {
1.11      markus    393:        struct winsize oldws, newws;
                    394:
                    395:        /* Flush stdout and stderr buffers. */
                    396:        if (buffer_len(&stdout_buffer) > 0)
1.14      deraadt   397:                atomicio(write, fileno(stdout), buffer_ptr(&stdout_buffer),
                    398:                    buffer_len(&stdout_buffer));
1.11      markus    399:        if (buffer_len(&stderr_buffer) > 0)
1.14      deraadt   400:                atomicio(write, fileno(stderr), buffer_ptr(&stderr_buffer),
                    401:                    buffer_len(&stderr_buffer));
1.11      markus    402:
                    403:        leave_raw_mode();
                    404:
1.13      markus    405:        /*
                    406:         * Free (and clear) the buffer to reduce the amount of data that gets
                    407:         * written to swap.
                    408:         */
1.11      markus    409:        buffer_free(&stdin_buffer);
                    410:        buffer_free(&stdout_buffer);
                    411:        buffer_free(&stderr_buffer);
                    412:
                    413:        /* Save old window size. */
                    414:        ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
                    415:
                    416:        /* Send the suspend signal to the program itself. */
                    417:        kill(getpid(), SIGTSTP);
                    418:
                    419:        /* Check if the window size has changed. */
                    420:        if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
                    421:            (oldws.ws_row != newws.ws_row ||
                    422:             oldws.ws_col != newws.ws_col ||
                    423:             oldws.ws_xpixel != newws.ws_xpixel ||
                    424:             oldws.ws_ypixel != newws.ws_ypixel))
                    425:                received_window_change_signal = 1;
                    426:
                    427:        /* OK, we have been continued by the user. Reinitialize buffers. */
                    428:        buffer_init(&stdin_buffer);
                    429:        buffer_init(&stdout_buffer);
                    430:        buffer_init(&stderr_buffer);
                    431:
                    432:        enter_raw_mode();
                    433: }
                    434:
                    435: void
                    436: client_process_input(fd_set * readset)
                    437: {
                    438:        int len, pid;
                    439:        char buf[8192], *s;
                    440:
1.13      markus    441:        /*
                    442:         * Read input from the server, and add any such data to the buffer of
                    443:         * the packet subsystem.
                    444:         */
1.11      markus    445:        if (FD_ISSET(connection_in, readset)) {
                    446:                /* Read as much as possible. */
                    447:                len = read(connection_in, buf, sizeof(buf));
1.16    ! markus    448: /*debug("read connection_in len %d", len); XXX */
1.11      markus    449:                if (len == 0) {
                    450:                        /* Received EOF.  The remote host has closed the connection. */
                    451:                        snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
                    452:                                 host);
1.1       deraadt   453:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    454:                        stderr_bytes += strlen(buf);
                    455:                        quit_pending = 1;
                    456:                        return;
1.11      markus    457:                }
1.13      markus    458:                /*
                    459:                 * There is a kernel bug on Solaris that causes select to
                    460:                 * sometimes wake up even though there is no data available.
                    461:                 */
1.11      markus    462:                if (len < 0 && errno == EAGAIN)
                    463:                        len = 0;
                    464:
                    465:                if (len < 0) {
                    466:                        /* An error has encountered.  Perhaps there is a network problem. */
                    467:                        snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
                    468:                                 host, strerror(errno));
                    469:                        buffer_append(&stderr_buffer, buf, strlen(buf));
                    470:                        stderr_bytes += strlen(buf);
                    471:                        quit_pending = 1;
                    472:                        return;
                    473:                }
                    474:                packet_process_incoming(buf, len);
                    475:        }
1.16    ! markus    476:
        !           477:        if (compat20)
        !           478:                return;
        !           479:
1.11      markus    480:        /* Read input from stdin. */
                    481:        if (FD_ISSET(fileno(stdin), readset)) {
                    482:                /* Read as much as possible. */
                    483:                len = read(fileno(stdin), buf, sizeof(buf));
                    484:                if (len <= 0) {
1.13      markus    485:                        /*
                    486:                         * Received EOF or error.  They are treated
                    487:                         * similarly, except that an error message is printed
                    488:                         * if it was an error condition.
                    489:                         */
1.11      markus    490:                        if (len < 0) {
                    491:                                snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
                    492:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    493:                                stderr_bytes += strlen(buf);
                    494:                        }
                    495:                        /* Mark that we have seen EOF. */
                    496:                        stdin_eof = 1;
1.13      markus    497:                        /*
                    498:                         * Send an EOF message to the server unless there is
                    499:                         * data in the buffer.  If there is data in the
                    500:                         * buffer, no message will be sent now.  Code
                    501:                         * elsewhere will send the EOF when the buffer
                    502:                         * becomes empty if stdin_eof is set.
                    503:                         */
1.11      markus    504:                        if (buffer_len(&stdin_buffer) == 0) {
1.1       deraadt   505:                                packet_start(SSH_CMSG_EOF);
                    506:                                packet_send();
1.11      markus    507:                        }
                    508:                } else if (escape_char == -1) {
1.13      markus    509:                        /*
                    510:                         * Normal successful read, and no escape character.
                    511:                         * Just append the data to buffer.
                    512:                         */
1.11      markus    513:                        buffer_append(&stdin_buffer, buf, len);
                    514:                        stdin_bytes += len;
                    515:                } else {
1.13      markus    516:                        /*
                    517:                         * Normal, successful read.  But we have an escape character
                    518:                         * and have to process the characters one by one.
                    519:                         */
1.11      markus    520:                        unsigned int i;
                    521:                        for (i = 0; i < len; i++) {
                    522:                                unsigned char ch;
                    523:                                /* Get one character at a time. */
                    524:                                ch = buf[i];
                    525:
                    526:                                if (escape_pending) {
                    527:                                        /* We have previously seen an escape character. */
                    528:                                        /* Clear the flag now. */
                    529:                                        escape_pending = 0;
                    530:                                        /* Process the escaped character. */
                    531:                                        switch (ch) {
                    532:                                        case '.':
                    533:                                                /* Terminate the connection. */
                    534:                                                snprintf(buf, sizeof buf, "%c.\r\n", escape_char);
                    535:                                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    536:                                                stderr_bytes += strlen(buf);
                    537:                                                quit_pending = 1;
                    538:                                                return;
                    539:
                    540:                                        case 'Z' - 64:
                    541:                                                /* Suspend the program. */
                    542:                                                /* Print a message to that effect to the user. */
                    543:                                                snprintf(buf, sizeof buf, "%c^Z\r\n", escape_char);
                    544:                                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    545:                                                stderr_bytes += strlen(buf);
                    546:
                    547:                                                /* Restore terminal modes and suspend. */
                    548:                                                client_suspend_self();
                    549:
                    550:                                                /* We have been continued. */
                    551:                                                continue;
                    552:
                    553:                                        case '&':
1.13      markus    554:                                                /*
                    555:                                                 * Detach the program (continue to serve connections,
                    556:                                                 * but put in background and no more new connections).
                    557:                                                 */
1.11      markus    558:                                                if (!stdin_eof) {
1.13      markus    559:                                                        /*
                    560:                                                         * Sending SSH_CMSG_EOF alone does not always appear
                    561:                                                         * to be enough.  So we try to send an EOF character
                    562:                                                         * first.
                    563:                                                         */
1.11      markus    564:                                                        packet_start(SSH_CMSG_STDIN_DATA);
                    565:                                                        packet_put_string("\004", 1);
                    566:                                                        packet_send();
                    567:                                                        /* Close stdin. */
                    568:                                                        stdin_eof = 1;
                    569:                                                        if (buffer_len(&stdin_buffer) == 0) {
                    570:                                                                packet_start(SSH_CMSG_EOF);
                    571:                                                                packet_send();
                    572:                                                        }
                    573:                                                }
                    574:                                                /* Restore tty modes. */
                    575:                                                leave_raw_mode();
                    576:
                    577:                                                /* Stop listening for new connections. */
                    578:                                                channel_stop_listening();
                    579:
                    580:                                                printf("%c& [backgrounded]\n", escape_char);
                    581:
                    582:                                                /* Fork into background. */
                    583:                                                pid = fork();
                    584:                                                if (pid < 0) {
                    585:                                                        error("fork: %.100s", strerror(errno));
                    586:                                                        continue;
                    587:                                                }
                    588:                                                if (pid != 0) { /* This is the parent. */
                    589:                                                        /* The parent just exits. */
                    590:                                                        exit(0);
                    591:                                                }
                    592:                                                /* The child continues serving connections. */
                    593:                                                continue;
                    594:
                    595:                                        case '?':
                    596:                                                snprintf(buf, sizeof buf,
                    597: "%c?\r\n\
1.1       deraadt   598: Supported escape sequences:\r\n\
                    599: ~.  - terminate connection\r\n\
                    600: ~^Z - suspend ssh\r\n\
                    601: ~#  - list forwarded connections\r\n\
                    602: ~&  - background ssh (when waiting for connections to terminate)\r\n\
                    603: ~?  - this message\r\n\
                    604: ~~  - send the escape character by typing it twice\r\n\
                    605: (Note that escapes are only recognized immediately after newline.)\r\n",
1.11      markus    606:                                                         escape_char);
                    607:                                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    608:                                                continue;
                    609:
                    610:                                        case '#':
                    611:                                                snprintf(buf, sizeof buf, "%c#\r\n", escape_char);
                    612:                                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    613:                                                s = channel_open_message();
                    614:                                                buffer_append(&stderr_buffer, s, strlen(s));
                    615:                                                xfree(s);
                    616:                                                continue;
                    617:
                    618:                                        default:
                    619:                                                if (ch != escape_char) {
1.13      markus    620:                                                        /*
                    621:                                                         * Escape character followed by non-special character.
                    622:                                                         * Append both to the input buffer.
                    623:                                                         */
1.11      markus    624:                                                        buf[0] = escape_char;
                    625:                                                        buf[1] = ch;
                    626:                                                        buffer_append(&stdin_buffer, buf, 2);
                    627:                                                        stdin_bytes += 2;
                    628:                                                        continue;
                    629:                                                }
1.13      markus    630:                                                /*
                    631:                                                 * Note that escape character typed twice
                    632:                                                 * falls through here; the latter gets processed
                    633:                                                 * as a normal character below.
                    634:                                                 */
1.11      markus    635:                                                break;
                    636:                                        }
                    637:                                } else {
1.13      markus    638:                                        /*
                    639:                                         * The previous character was not an escape char. Check if this
                    640:                                         * is an escape.
                    641:                                         */
1.11      markus    642:                                        if (last_was_cr && ch == escape_char) {
                    643:                                                /* It is. Set the flag and continue to next character. */
                    644:                                                escape_pending = 1;
                    645:                                                continue;
                    646:                                        }
                    647:                                }
                    648:
1.13      markus    649:                                /*
                    650:                                 * Normal character.  Record whether it was a newline,
                    651:                                 * and append it to the buffer.
                    652:                                 */
1.11      markus    653:                                last_was_cr = (ch == '\r' || ch == '\n');
                    654:                                buf[0] = ch;
                    655:                                buffer_append(&stdin_buffer, buf, 1);
                    656:                                stdin_bytes += 1;
                    657:                                continue;
                    658:                        }
                    659:                }
                    660:        }
                    661: }
                    662:
                    663: void
                    664: client_process_output(fd_set * writeset)
                    665: {
                    666:        int len;
                    667:        char buf[100];
1.1       deraadt   668:
1.11      markus    669:        /* Write buffered output to stdout. */
                    670:        if (FD_ISSET(fileno(stdout), writeset)) {
                    671:                /* Write as much data as possible. */
                    672:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt   673:                    buffer_len(&stdout_buffer));
1.11      markus    674:                if (len <= 0) {
                    675:                        if (errno == EAGAIN)
                    676:                                len = 0;
                    677:                        else {
1.13      markus    678:                                /*
                    679:                                 * An error or EOF was encountered.  Put an
                    680:                                 * error message to stderr buffer.
                    681:                                 */
1.11      markus    682:                                snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
                    683:                                buffer_append(&stderr_buffer, buf, strlen(buf));
                    684:                                stderr_bytes += strlen(buf);
                    685:                                quit_pending = 1;
                    686:                                return;
                    687:                        }
                    688:                }
                    689:                /* Consume printed data from the buffer. */
                    690:                buffer_consume(&stdout_buffer, len);
                    691:        }
                    692:        /* Write buffered output to stderr. */
                    693:        if (FD_ISSET(fileno(stderr), writeset)) {
                    694:                /* Write as much data as possible. */
                    695:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt   696:                    buffer_len(&stderr_buffer));
1.11      markus    697:                if (len <= 0) {
                    698:                        if (errno == EAGAIN)
                    699:                                len = 0;
                    700:                        else {
1.13      markus    701:                                /* EOF or error, but can't even print error message. */
1.11      markus    702:                                quit_pending = 1;
                    703:                                return;
                    704:                        }
                    705:                }
                    706:                /* Consume printed characters from the buffer. */
                    707:                buffer_consume(&stderr_buffer, len);
                    708:        }
1.1       deraadt   709: }
                    710:
1.13      markus    711: /*
1.15      markus    712:  * Get packets from the connection input buffer, and process them as long as
                    713:  * there are packets available.
                    714:  *
                    715:  * Any unknown packets received during the actual
                    716:  * session cause the session to terminate.  This is
                    717:  * intended to make debugging easier since no
                    718:  * confirmations are sent.  Any compatible protocol
                    719:  * extensions must be negotiated during the
                    720:  * preparatory phase.
                    721:  */
                    722:
                    723: void
                    724: client_process_buffered_input_packets()
                    725: {
                    726:        dispatch_run(DISPATCH_NONBLOCK, &quit_pending);
                    727: }
                    728:
                    729: /*
1.13      markus    730:  * Implements the interactive session with the server.  This is called after
                    731:  * the user has been authenticated, and a command has been started on the
                    732:  * remote host.  If escape_char != -1, it is the character used as an escape
                    733:  * character for terminating or suspending the session.
                    734:  */
1.1       deraadt   735:
1.11      markus    736: int
                    737: client_loop(int have_pty, int escape_char_arg)
1.1       deraadt   738: {
1.11      markus    739:        extern Options options;
                    740:        double start_time, total_time;
                    741:        int len;
                    742:        char buf[100];
                    743:
                    744:        debug("Entering interactive session.");
                    745:
                    746:        start_time = get_current_time();
                    747:
                    748:        /* Initialize variables. */
                    749:        escape_pending = 0;
                    750:        last_was_cr = 1;
                    751:        exit_status = -1;
                    752:        stdin_eof = 0;
                    753:        buffer_high = 64 * 1024;
                    754:        connection_in = packet_get_connection_in();
                    755:        connection_out = packet_get_connection_out();
                    756:        max_fd = connection_in;
                    757:        if (connection_out > max_fd)
                    758:                max_fd = connection_out;
                    759:        stdin_bytes = 0;
                    760:        stdout_bytes = 0;
                    761:        stderr_bytes = 0;
                    762:        quit_pending = 0;
                    763:        escape_char = escape_char_arg;
                    764:
                    765:        /* Initialize buffers. */
                    766:        buffer_init(&stdin_buffer);
                    767:        buffer_init(&stdout_buffer);
                    768:        buffer_init(&stderr_buffer);
                    769:
1.15      markus    770:        client_init_dispatch();
                    771:
1.11      markus    772:        /* Set signal handlers to restore non-blocking mode.  */
                    773:        signal(SIGINT, signal_handler);
                    774:        signal(SIGQUIT, signal_handler);
                    775:        signal(SIGTERM, signal_handler);
                    776:        signal(SIGPIPE, SIG_IGN);
                    777:        if (have_pty)
                    778:                signal(SIGWINCH, window_change_handler);
                    779:
                    780:        if (have_pty)
                    781:                enter_raw_mode();
                    782:
                    783:        /* Check if we should immediately send of on stdin. */
1.16    ! markus    784:        if(!compat20)
        !           785:                client_check_initial_eof_on_stdin();
1.11      markus    786:
                    787:        /* Main loop of the client for the interactive session mode. */
                    788:        while (!quit_pending) {
                    789:                fd_set readset, writeset;
                    790:
1.13      markus    791:                /* Process buffered packets sent by the server. */
1.11      markus    792:                client_process_buffered_input_packets();
                    793:
1.16    ! markus    794:                if (compat20 && !channel_still_open()) {
        !           795:                        debug("!channel_still_open.");
        !           796:                        break;
        !           797:                }
        !           798:
1.13      markus    799:                /*
                    800:                 * Make packets of buffered stdin data, and buffer them for
                    801:                 * sending to the server.
                    802:                 */
1.16    ! markus    803:                if(!compat20)
        !           804:                        client_make_packets_from_stdin_data();
1.11      markus    805:
1.13      markus    806:                /*
                    807:                 * Make packets from buffered channel data, and buffer them
                    808:                 * for sending to the server.
                    809:                 */
1.11      markus    810:                if (packet_not_very_much_data_to_write())
                    811:                        channel_output_poll();
                    812:
1.13      markus    813:                /*
                    814:                 * Check if the window size has changed, and buffer a message
                    815:                 * about it to the server if so.
                    816:                 */
1.11      markus    817:                client_check_window_change();
                    818:
                    819:                if (quit_pending)
                    820:                        break;
                    821:
1.13      markus    822:                /*
                    823:                 * Wait until we have something to do (something becomes
                    824:                 * available on one of the descriptors).
                    825:                 */
1.11      markus    826:                client_wait_until_can_do_something(&readset, &writeset);
                    827:
                    828:                if (quit_pending)
                    829:                        break;
                    830:
                    831:                /* Do channel operations. */
                    832:                channel_after_select(&readset, &writeset);
                    833:
1.13      markus    834:                /*
                    835:                 * Process input from the connection and from stdin. Buffer
                    836:                 * any data that is available.
                    837:                 */
1.11      markus    838:                client_process_input(&readset);
                    839:
1.13      markus    840:                /*
                    841:                 * Process output to stdout and stderr.   Output to the
                    842:                 * connection is processed elsewhere (above).
                    843:                 */
1.16    ! markus    844:                if(!compat20)
        !           845:                        client_process_output(&writeset);
1.11      markus    846:
1.13      markus    847:                /* Send as much buffered packet data as possible to the sender. */
1.11      markus    848:                if (FD_ISSET(connection_out, &writeset))
                    849:                        packet_write_poll();
                    850:        }
                    851:
                    852:        /* Terminate the session. */
                    853:
                    854:        /* Stop watching for window change. */
                    855:        if (have_pty)
                    856:                signal(SIGWINCH, SIG_DFL);
                    857:
                    858:        /* Stop listening for connections. */
                    859:        channel_stop_listening();
                    860:
1.13      markus    861:        /*
                    862:         * In interactive mode (with pseudo tty) display a message indicating
                    863:         * that the connection has been closed.
                    864:         */
1.11      markus    865:        if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
                    866:                snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
                    867:                buffer_append(&stderr_buffer, buf, strlen(buf));
                    868:                stderr_bytes += strlen(buf);
                    869:        }
                    870:        /* Output any buffered data for stdout. */
                    871:        while (buffer_len(&stdout_buffer) > 0) {
                    872:                len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1.14      deraadt   873:                    buffer_len(&stdout_buffer));
1.11      markus    874:                if (len <= 0) {
                    875:                        error("Write failed flushing stdout buffer.");
                    876:                        break;
                    877:                }
                    878:                buffer_consume(&stdout_buffer, len);
                    879:        }
                    880:
                    881:        /* Output any buffered data for stderr. */
                    882:        while (buffer_len(&stderr_buffer) > 0) {
                    883:                len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1.14      deraadt   884:                    buffer_len(&stderr_buffer));
1.11      markus    885:                if (len <= 0) {
                    886:                        error("Write failed flushing stderr buffer.");
                    887:                        break;
                    888:                }
                    889:                buffer_consume(&stderr_buffer, len);
                    890:        }
                    891:
                    892:        if (have_pty)
                    893:                leave_raw_mode();
                    894:
                    895:        /* Clear and free any buffers. */
                    896:        memset(buf, 0, sizeof(buf));
                    897:        buffer_free(&stdin_buffer);
                    898:        buffer_free(&stdout_buffer);
                    899:        buffer_free(&stderr_buffer);
                    900:
                    901:        /* Report bytes transferred, and transfer rates. */
                    902:        total_time = get_current_time() - start_time;
                    903:        debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
                    904:              stdin_bytes, stdout_bytes, stderr_bytes, total_time);
                    905:        if (total_time > 0)
                    906:                debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
                    907:                      stdin_bytes / total_time, stdout_bytes / total_time,
                    908:                      stderr_bytes / total_time);
                    909:
                    910:        /* Return the exit status of the program. */
                    911:        debug("Exit status %d", exit_status);
                    912:        return exit_status;
1.15      markus    913: }
                    914:
                    915: /*********/
                    916:
                    917: void
                    918: client_input_stdout_data(int type, int plen)
                    919: {
                    920:        unsigned int data_len;
                    921:        char *data = packet_get_string(&data_len);
                    922:        packet_integrity_check(plen, 4 + data_len, type);
                    923:        buffer_append(&stdout_buffer, data, data_len);
                    924:        stdout_bytes += data_len;
                    925:        memset(data, 0, data_len);
                    926:        xfree(data);
                    927: }
                    928: void
                    929: client_input_stderr_data(int type, int plen)
                    930: {
                    931:        unsigned int data_len;
                    932:        char *data = packet_get_string(&data_len);
                    933:        packet_integrity_check(plen, 4 + data_len, type);
                    934:        buffer_append(&stderr_buffer, data, data_len);
                    935:        stdout_bytes += data_len;
                    936:        memset(data, 0, data_len);
                    937:        xfree(data);
                    938: }
                    939: void
                    940: client_input_exit_status(int type, int plen)
                    941: {
                    942:        packet_integrity_check(plen, 4, type);
                    943:        exit_status = packet_get_int();
                    944:        /* Acknowledge the exit. */
                    945:        packet_start(SSH_CMSG_EXIT_CONFIRMATION);
                    946:        packet_send();
                    947:        /*
                    948:         * Must wait for packet to be sent since we are
                    949:         * exiting the loop.
                    950:         */
                    951:        packet_write_wait();
                    952:        /* Flag that we want to exit. */
                    953:        quit_pending = 1;
                    954: }
                    955:
                    956: void
1.16    ! markus    957: client_init_dispatch_20()
        !           958: {
        !           959:        dispatch_init(&dispatch_protocol_error);
        !           960:        dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
        !           961:        dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
        !           962:        dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
        !           963:        dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
        !           964:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
        !           965:        dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
        !           966:        dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &channel_input_channel_request);
        !           967:        dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
        !           968: }
        !           969: void
1.15      markus    970: client_init_dispatch_13()
                    971: {
                    972:        dispatch_init(NULL);
                    973:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
                    974:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
                    975:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                    976:        dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
                    977:        dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
                    978:        dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
                    979:        dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
                    980:        dispatch_set(SSH_SMSG_AGENT_OPEN, &auth_input_open_request);
                    981:        dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
                    982:        dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
                    983:        dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
                    984:        dispatch_set(SSH_SMSG_X11_OPEN, &x11_input_open);
                    985: }
                    986: void
                    987: client_init_dispatch_15()
                    988: {
                    989:        client_init_dispatch_13();
                    990:        dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
                    991:        dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
                    992: }
                    993: void
                    994: client_init_dispatch()
                    995: {
1.16    ! markus    996:        if (compat20)
        !           997:                client_init_dispatch_20();
        !           998:        else if (compat13)
1.15      markus    999:                client_init_dispatch_13();
                   1000:        else
                   1001:                client_init_dispatch_15();
1.16    ! markus   1002: }
        !          1003:
        !          1004: void
        !          1005: client_input_channel_req(int id, void *arg)
        !          1006: {
        !          1007:        Channel *c = NULL;
        !          1008:        unsigned int len;
        !          1009:        int success = 0;
        !          1010:        int reply;
        !          1011:        char *rtype;
        !          1012:
        !          1013:        rtype = packet_get_string(&len);
        !          1014:        reply = packet_get_char();
        !          1015:
        !          1016:        log("session_input_channel_req: rtype %s reply %d", rtype, reply);
        !          1017:
        !          1018:        c = channel_lookup(id);
        !          1019:        if (c == NULL)
        !          1020:                fatal("session_input_channel_req: channel %d: bad channel", id);
        !          1021:
        !          1022:        if (session_ident == -1) {
        !          1023:                error("client_input_channel_req: no channel %d", id);
        !          1024:        } else if (id != session_ident) {
        !          1025:                error("client_input_channel_req: bad channel %d != %d",
        !          1026:                    id, session_ident);
        !          1027:        } else if (strcmp(rtype, "exit-status") == 0) {
        !          1028:                success = 1;
        !          1029:                exit_status = packet_get_int();
        !          1030:        }
        !          1031:        if (reply) {
        !          1032:                packet_start(success ?
        !          1033:                    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
        !          1034:                packet_put_int(c->remote_id);
        !          1035:                packet_send();
        !          1036:        }
        !          1037:        xfree(rtype);
        !          1038: }
        !          1039:
        !          1040: void
        !          1041: client_set_session_ident(int id)
        !          1042: {
        !          1043:        debug("client_set_session_ident: id %d", id);
        !          1044:        session_ident = id;
        !          1045:        channel_register_callback(id, SSH2_MSG_CHANNEL_REQUEST,
        !          1046:            client_input_channel_req, (void *)0);
1.1       deraadt  1047: }