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

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