5 * Author: Tatu Ylonen <ylo@cs.hut.fi>
7 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
11 * Created: Sat Sep 23 12:23:57 1995 ylo
13 * The main loop for the interactive session (client side).
27 /* Flag indicating that stdin should be redirected from /dev/null. */
28 extern int stdin_null_flag;
30 /* Name of the host we are connecting to. This is the name given on the
31 command line, or the HostName specified for the user-supplied name
32 in a configuration file. */
35 /* Flag to indicate that we have received a window change signal which has
36 not yet been processed. This will cause a message indicating the new
37 window size to be sent to the server a little later. This is volatile
38 because this is updated in a signal handler. */
39 static volatile int received_window_change_signal = 0;
41 /* Terminal modes, as saved by enter_raw_mode. */
42 static struct termios saved_tio;
44 /* Flag indicating whether we are in raw mode. This is used by enter_raw_mode
45 and leave_raw_mode. */
46 static int in_raw_mode = 0;
48 /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
49 static int in_non_blocking_mode = 0;
51 /* Common data for the client loop code. */
52 static int escape_pending; /* Last character was the escape character */
53 static int last_was_cr; /* Last character was a newline. */
54 static int exit_status; /* Used to store the exit status of the command. */
55 static int stdin_eof; /* EOF has been encountered on standard error. */
56 static Buffer stdin_buffer; /* Buffer for stdin data. */
57 static Buffer stdout_buffer; /* Buffer for stdout data. */
58 static Buffer stderr_buffer; /* Buffer for stderr data. */
59 static unsigned int buffer_high;/* Soft max buffer size. */
60 static int max_fd; /* Maximum file descriptor number in select(). */
61 static int connection_in; /* Connection to server (input). */
62 static int connection_out; /* Connection to server (output). */
63 static unsigned long stdin_bytes, stdout_bytes, stderr_bytes;
64 static int quit_pending; /* Set to non-zero to quit the client loop. */
65 static int escape_char; /* Escape character. */
67 /* Returns the user\'s terminal to normal mode if it had been put in raw
76 if (tcsetattr(fileno(stdin), TCSADRAIN, &saved_tio) < 0)
79 fatal_remove_cleanup((void (*) (void *)) leave_raw_mode, NULL);
82 /* Puts the user\'s terminal in raw mode. */
89 if (tcgetattr(fileno(stdin), &tio) < 0)
92 tio.c_iflag |= IGNPAR;
93 tio.c_iflag &= ~(ISTRIP | INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF);
94 tio.c_lflag &= ~(ISIG | ICANON | ECHO | ECHOE | ECHOK | ECHONL);
96 tio.c_lflag &= ~IEXTEN;
98 tio.c_oflag &= ~OPOST;
101 if (tcsetattr(fileno(stdin), TCSADRAIN, &tio) < 0)
105 fatal_add_cleanup((void (*) (void *)) leave_raw_mode, NULL);
108 /* Restores stdin to blocking mode. */
113 if (in_non_blocking_mode) {
114 (void) fcntl(fileno(stdin), F_SETFL, 0);
115 in_non_blocking_mode = 0;
116 fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
120 /* Puts stdin terminal in non-blocking mode. */
125 in_non_blocking_mode = 1;
126 (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
127 fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
130 /* Signal handler for the window change signal (SIGWINCH). This just
131 sets a flag indicating that the window has changed. */
134 window_change_handler(int sig)
136 received_window_change_signal = 1;
137 signal(SIGWINCH, window_change_handler);
140 /* Signal handler for signals that cause the program to terminate. These
141 signals must be trapped to restore terminal modes. */
144 signal_handler(int sig)
148 if (in_non_blocking_mode)
149 leave_non_blocking();
150 channel_stop_listening();
152 fatal("Killed by signal %d.", sig);
155 /* Returns current time in seconds from Jan 1, 1970 with the maximum available
162 gettimeofday(&tv, NULL);
163 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
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. */
171 client_check_initial_eof_on_stdin()
176 /* If standard input is to be "redirected from /dev/null", we
177 simply mark that we have seen an EOF and send an EOF message to
178 the server. Otherwise, we try to read a single character; it
179 appears that for some files, such /dev/null, select() never
180 wakes up for read for this descriptor, which means that we
181 never get EOF. This way we will get the EOF if stdin comes
182 from /dev/null or similar. */
183 if (stdin_null_flag) {
184 /* Fake EOF on stdin. */
185 debug("Sending eof.");
187 packet_start(SSH_CMSG_EOF);
190 /* Enter non-blocking mode for stdin. */
191 enter_non_blocking();
193 /* Check for immediate EOF on stdin. */
194 len = read(fileno(stdin), buf, 1);
196 /* EOF. Record that we have seen it and send EOF
198 debug("Sending eof.");
200 packet_start(SSH_CMSG_EOF);
202 } else if (len > 0) {
203 /* Got data. We must store the data in the
204 buffer, and also process it as an escape
205 character if appropriate. */
206 if ((unsigned char) buf[0] == escape_char)
209 buffer_append(&stdin_buffer, buf, 1);
213 /* Leave non-blocking mode. */
214 leave_non_blocking();
218 /* Get packets from the connection input buffer, and process them as long
219 as there are packets available. */
222 client_process_buffered_input_packets()
226 unsigned int data_len;
229 /* Process any buffered packets from the server. */
230 while (!quit_pending &&
231 (type = packet_read_poll(&payload_len)) != SSH_MSG_NONE) {
234 case SSH_SMSG_STDOUT_DATA:
235 data = packet_get_string(&data_len);
236 packet_integrity_check(payload_len, 4 + data_len, type);
237 buffer_append(&stdout_buffer, data, data_len);
238 stdout_bytes += data_len;
239 memset(data, 0, data_len);
243 case SSH_SMSG_STDERR_DATA:
244 data = packet_get_string(&data_len);
245 packet_integrity_check(payload_len, 4 + data_len, type);
246 buffer_append(&stderr_buffer, data, data_len);
247 stdout_bytes += data_len;
248 memset(data, 0, data_len);
252 case SSH_SMSG_EXITSTATUS:
253 packet_integrity_check(payload_len, 4, type);
254 exit_status = packet_get_int();
255 /* Acknowledge the exit. */
256 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
258 /* Must wait for packet to be sent since we are
261 /* Flag that we want to exit. */
265 case SSH_SMSG_X11_OPEN:
266 x11_input_open(payload_len);
269 case SSH_MSG_PORT_OPEN:
270 channel_input_port_open(payload_len);
273 case SSH_SMSG_AGENT_OPEN:
274 packet_integrity_check(payload_len, 4, type);
275 auth_input_open_request();
278 case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
279 packet_integrity_check(payload_len, 4 + 4, type);
280 channel_input_open_confirmation();
283 case SSH_MSG_CHANNEL_OPEN_FAILURE:
284 packet_integrity_check(payload_len, 4, type);
285 channel_input_open_failure();
288 case SSH_MSG_CHANNEL_DATA:
289 channel_input_data(payload_len);
292 case SSH_MSG_CHANNEL_CLOSE:
293 packet_integrity_check(payload_len, 4, type);
294 channel_input_close();
297 case SSH_MSG_CHANNEL_CLOSE_CONFIRMATION:
298 packet_integrity_check(payload_len, 4, type);
299 channel_input_close_confirmation();
303 /* Any unknown packets received during the actual
304 session cause the session to terminate. This
305 is intended to make debugging easier since no
306 confirmations are sent. Any compatible
307 protocol extensions must be negotiated during
308 the preparatory phase. */
309 packet_disconnect("Protocol error during session: type %d",
315 /* Make packets from buffered stdin data, and buffer them for sending to
319 client_make_packets_from_stdin_data()
323 /* Send buffered stdin data to the server. */
324 while (buffer_len(&stdin_buffer) > 0 &&
325 packet_not_very_much_data_to_write()) {
326 len = buffer_len(&stdin_buffer);
327 /* Keep the packets at reasonable size. */
328 if (len > packet_get_maxsize())
329 len = packet_get_maxsize();
330 packet_start(SSH_CMSG_STDIN_DATA);
331 packet_put_string(buffer_ptr(&stdin_buffer), len);
333 buffer_consume(&stdin_buffer, len);
334 /* If we have a pending EOF, send it now. */
335 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
336 packet_start(SSH_CMSG_EOF);
342 /* Checks if the client window has changed, and sends a packet about it to
343 the server if so. The actual change is detected elsewhere (by a software
344 interrupt on Unix); this just checks the flag and sends a message if
348 client_check_window_change()
350 /* Send possible window change message to the server. */
351 if (received_window_change_signal) {
354 /* Clear the window change indicator. */
355 received_window_change_signal = 0;
357 /* Read new window size. */
358 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) >= 0) {
359 /* Successful, send the packet now. */
360 packet_start(SSH_CMSG_WINDOW_SIZE);
361 packet_put_int(ws.ws_row);
362 packet_put_int(ws.ws_col);
363 packet_put_int(ws.ws_xpixel);
364 packet_put_int(ws.ws_ypixel);
370 /* Waits until the client can do something (some data becomes available on
371 one of the file descriptors). */
374 client_wait_until_can_do_something(fd_set * readset, fd_set * writeset)
376 /* Initialize select masks. */
379 /* Read from the connection, unless our buffers are full. */
380 if (buffer_len(&stdout_buffer) < buffer_high &&
381 buffer_len(&stderr_buffer) < buffer_high &&
382 channel_not_very_much_buffered_data())
383 FD_SET(connection_in, readset);
385 /* Read from stdin, unless we have seen EOF or have very much
386 buffered data to send to the server. */
387 if (!stdin_eof && packet_not_very_much_data_to_write())
388 FD_SET(fileno(stdin), readset);
392 /* Add any selections by the channel mechanism. */
393 channel_prepare_select(readset, writeset);
395 /* Select server connection if have data to write to the server. */
396 if (packet_have_data_to_write())
397 FD_SET(connection_out, writeset);
399 /* Select stdout if have data in buffer. */
400 if (buffer_len(&stdout_buffer) > 0)
401 FD_SET(fileno(stdout), writeset);
403 /* Select stderr if have data in buffer. */
404 if (buffer_len(&stderr_buffer) > 0)
405 FD_SET(fileno(stderr), writeset);
407 /* Update maximum file descriptor number, if appropriate. */
408 if (channel_max_fd() > max_fd)
409 max_fd = channel_max_fd();
411 /* Wait for something to happen. This will suspend the process
412 until some selected descriptor can be read, written, or has
413 some other event pending.
414 Note: if you want to implement SSH_MSG_IGNORE messages to fool
415 traffic analysis, this might be the place to do it:
416 just have a random timeout for the select, and send a random
417 SSH_MSG_IGNORE packet when the timeout expires. */
419 if (select(max_fd + 1, readset, writeset, NULL, NULL) < 0) {
421 /* Some systems fail to clear these automatically. */
426 /* Note: we might still have data in the buffers. */
427 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
428 buffer_append(&stderr_buffer, buf, strlen(buf));
429 stderr_bytes += strlen(buf);
435 client_suspend_self()
437 struct winsize oldws, newws;
439 /* Flush stdout and stderr buffers. */
440 if (buffer_len(&stdout_buffer) > 0)
441 write(fileno(stdout),
442 buffer_ptr(&stdout_buffer),
443 buffer_len(&stdout_buffer));
444 if (buffer_len(&stderr_buffer) > 0)
445 write(fileno(stderr),
446 buffer_ptr(&stderr_buffer),
447 buffer_len(&stderr_buffer));
449 /* Leave raw mode. */
452 /* Free (and clear) the buffer to reduce the amount of data that
453 gets written to swap. */
454 buffer_free(&stdin_buffer);
455 buffer_free(&stdout_buffer);
456 buffer_free(&stderr_buffer);
458 /* Save old window size. */
459 ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
461 /* Send the suspend signal to the program itself. */
462 kill(getpid(), SIGTSTP);
464 /* Check if the window size has changed. */
465 if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
466 (oldws.ws_row != newws.ws_row ||
467 oldws.ws_col != newws.ws_col ||
468 oldws.ws_xpixel != newws.ws_xpixel ||
469 oldws.ws_ypixel != newws.ws_ypixel))
470 received_window_change_signal = 1;
472 /* OK, we have been continued by the user. Reinitialize buffers. */
473 buffer_init(&stdin_buffer);
474 buffer_init(&stdout_buffer);
475 buffer_init(&stderr_buffer);
477 /* Re-enter raw mode. */
482 client_process_input(fd_set * readset)
487 /* Read input from the server, and add any such data to the buffer
488 of the packet subsystem. */
489 if (FD_ISSET(connection_in, readset)) {
490 /* Read as much as possible. */
491 len = read(connection_in, buf, sizeof(buf));
493 /* Received EOF. The remote host has closed the connection. */
494 snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
496 buffer_append(&stderr_buffer, buf, strlen(buf));
497 stderr_bytes += strlen(buf);
501 /* There is a kernel bug on Solaris that causes select to
502 sometimes wake up even though there is no data
504 if (len < 0 && errno == EAGAIN)
508 /* An error has encountered. Perhaps there is a network problem. */
509 snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
510 host, strerror(errno));
511 buffer_append(&stderr_buffer, buf, strlen(buf));
512 stderr_bytes += strlen(buf);
516 packet_process_incoming(buf, len);
518 /* Read input from stdin. */
519 if (FD_ISSET(fileno(stdin), readset)) {
520 /* Read as much as possible. */
521 len = read(fileno(stdin), buf, sizeof(buf));
523 /* Received EOF or error. They are treated
524 similarly, except that an error message is
525 printed if it was an error condition. */
527 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
528 buffer_append(&stderr_buffer, buf, strlen(buf));
529 stderr_bytes += strlen(buf);
531 /* Mark that we have seen EOF. */
533 /* Send an EOF message to the server unless there
534 is data in the buffer. If there is data in the
535 buffer, no message will be sent now. Code
536 elsewhere will send the EOF when the buffer
537 becomes empty if stdin_eof is set. */
538 if (buffer_len(&stdin_buffer) == 0) {
539 packet_start(SSH_CMSG_EOF);
542 } else if (escape_char == -1) {
543 /* Normal successful read, and no escape
544 character. Just append the data to buffer. */
545 buffer_append(&stdin_buffer, buf, len);
548 /* Normal, successful read. But we have an escape
549 character and have to process the characters
552 for (i = 0; i < len; i++) {
554 /* Get one character at a time. */
557 /* Check if we have a pending escape
559 if (escape_pending) {
560 /* We have previously seen an escape character. */
561 /* Clear the flag now. */
563 /* Process the escaped character. */
566 /* Terminate the connection. */
567 snprintf(buf, sizeof buf, "%c.\r\n", escape_char);
568 buffer_append(&stderr_buffer, buf, strlen(buf));
569 stderr_bytes += strlen(buf);
574 /* Suspend the program. */
575 /* Print a message to that effect to the user. */
576 snprintf(buf, sizeof buf, "%c^Z\r\n", escape_char);
577 buffer_append(&stderr_buffer, buf, strlen(buf));
578 stderr_bytes += strlen(buf);
580 /* Restore terminal modes and suspend. */
581 client_suspend_self();
583 /* We have been continued. */
587 /* Detach the program (continue to serve connections,
588 but put in background and no more new connections). */
590 /* Sending SSH_CMSG_EOF alone does not always appear
591 to be enough. So we try to send an EOF character
593 packet_start(SSH_CMSG_STDIN_DATA);
594 packet_put_string("\004", 1);
598 if (buffer_len(&stdin_buffer) == 0) {
599 packet_start(SSH_CMSG_EOF);
603 /* Restore tty modes. */
606 /* Stop listening for new connections. */
607 channel_stop_listening();
609 printf("%c& [backgrounded]\n", escape_char);
611 /* Fork into background. */
614 error("fork: %.100s", strerror(errno));
617 if (pid != 0) { /* This is the parent. */
618 /* The parent just exits. */
621 /* The child continues serving connections. */
625 snprintf(buf, sizeof buf,
627 Supported escape sequences:\r\n\
628 ~. - terminate connection\r\n\
629 ~^Z - suspend ssh\r\n\
630 ~# - list forwarded connections\r\n\
631 ~& - background ssh (when waiting for connections to terminate)\r\n\
632 ~? - this message\r\n\
633 ~~ - send the escape character by typing it twice\r\n\
634 (Note that escapes are only recognized immediately after newline.)\r\n",
636 buffer_append(&stderr_buffer, buf, strlen(buf));
640 snprintf(buf, sizeof buf, "%c#\r\n", escape_char);
641 buffer_append(&stderr_buffer, buf, strlen(buf));
642 s = channel_open_message();
643 buffer_append(&stderr_buffer, s, strlen(s));
648 if (ch != escape_char) {
649 /* Escape character followed by non-special character.
650 Append both to the input buffer. */
651 buf[0] = escape_char;
653 buffer_append(&stdin_buffer, buf, 2);
657 /* Note that escape character typed twice
658 falls through here; the latter gets processed
659 as a normal character below. */
663 /* The previous character was not an escape char. Check if this
665 if (last_was_cr && ch == escape_char) {
666 /* It is. Set the flag and continue to next character. */
672 /* Normal character. Record whether it was a newline, and append it to the
674 last_was_cr = (ch == '\r' || ch == '\n');
676 buffer_append(&stdin_buffer, buf, 1);
685 client_process_output(fd_set * writeset)
690 /* Write buffered output to stdout. */
691 if (FD_ISSET(fileno(stdout), writeset)) {
692 /* Write as much data as possible. */
693 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
694 buffer_len(&stdout_buffer));
699 /* An error or EOF was encountered. Put
700 an error message to stderr buffer. */
701 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
702 buffer_append(&stderr_buffer, buf, strlen(buf));
703 stderr_bytes += strlen(buf);
708 /* Consume printed data from the buffer. */
709 buffer_consume(&stdout_buffer, len);
711 /* Write buffered output to stderr. */
712 if (FD_ISSET(fileno(stderr), writeset)) {
713 /* Write as much data as possible. */
714 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
715 buffer_len(&stderr_buffer));
720 /* EOF or error, but can't even print
726 /* Consume printed characters from the buffer. */
727 buffer_consume(&stderr_buffer, len);
731 /* Implements the interactive session with the server. This is called
732 after the user has been authenticated, and a command has been
733 started on the remote host. If escape_char != -1, it is the character
734 used as an escape character for terminating or suspending the
738 client_loop(int have_pty, int escape_char_arg)
740 extern Options options;
741 double start_time, total_time;
745 debug("Entering interactive session.");
747 start_time = get_current_time();
749 /* Initialize variables. */
754 buffer_high = 64 * 1024;
755 connection_in = packet_get_connection_in();
756 connection_out = packet_get_connection_out();
757 max_fd = connection_in;
758 if (connection_out > max_fd)
759 max_fd = connection_out;
764 escape_char = escape_char_arg;
766 /* Initialize buffers. */
767 buffer_init(&stdin_buffer);
768 buffer_init(&stdout_buffer);
769 buffer_init(&stderr_buffer);
771 /* Set signal handlers to restore non-blocking mode. */
772 signal(SIGINT, signal_handler);
773 signal(SIGQUIT, signal_handler);
774 signal(SIGTERM, signal_handler);
775 signal(SIGPIPE, SIG_IGN);
777 signal(SIGWINCH, window_change_handler);
779 /* Enter raw mode if have a pseudo terminal. */
783 /* Check if we should immediately send of on stdin. */
784 client_check_initial_eof_on_stdin();
786 /* Main loop of the client for the interactive session mode. */
787 while (!quit_pending) {
788 fd_set readset, writeset;
790 /* Precess buffered packets sent by the server. */
791 client_process_buffered_input_packets();
793 /* Make packets of buffered stdin data, and buffer them
794 for sending to the server. */
795 client_make_packets_from_stdin_data();
797 /* Make packets from buffered channel data, and buffer
798 them for sending to the server. */
799 if (packet_not_very_much_data_to_write())
800 channel_output_poll();
802 /* Check if the window size has changed, and buffer a
803 message about it to the server if so. */
804 client_check_window_change();
809 /* Wait until we have something to do (something becomes
810 available on one of the descriptors). */
811 client_wait_until_can_do_something(&readset, &writeset);
816 /* Do channel operations. */
817 channel_after_select(&readset, &writeset);
819 /* Process input from the connection and from stdin.
820 Buffer any data that is available. */
821 client_process_input(&readset);
823 /* Process output to stdout and stderr. Output to the
824 connection is processed elsewhere (above). */
825 client_process_output(&writeset);
827 /* Send as much buffered packet data as possible to the
829 if (FD_ISSET(connection_out, &writeset))
833 /* Terminate the session. */
835 /* Stop watching for window change. */
837 signal(SIGWINCH, SIG_DFL);
839 /* Stop listening for connections. */
840 channel_stop_listening();
842 /* In interactive mode (with pseudo tty) display a message
843 indicating that the connection has been closed. */
844 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
845 snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
846 buffer_append(&stderr_buffer, buf, strlen(buf));
847 stderr_bytes += strlen(buf);
849 /* Output any buffered data for stdout. */
850 while (buffer_len(&stdout_buffer) > 0) {
851 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
852 buffer_len(&stdout_buffer));
854 error("Write failed flushing stdout buffer.");
857 buffer_consume(&stdout_buffer, len);
860 /* Output any buffered data for stderr. */
861 while (buffer_len(&stderr_buffer) > 0) {
862 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
863 buffer_len(&stderr_buffer));
865 error("Write failed flushing stderr buffer.");
868 buffer_consume(&stderr_buffer, len);
871 /* Leave raw mode. */
875 /* Clear and free any buffers. */
876 memset(buf, 0, sizeof(buf));
877 buffer_free(&stdin_buffer);
878 buffer_free(&stdout_buffer);
879 buffer_free(&stderr_buffer);
881 /* Report bytes transferred, and transfer rates. */
882 total_time = get_current_time() - start_time;
883 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
884 stdin_bytes, stdout_bytes, stderr_bytes, total_time);
886 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
887 stdin_bytes / total_time, stdout_bytes / total_time,
888 stderr_bytes / total_time);
890 /* Return the exit status of the program. */
891 debug("Exit status %d", exit_status);