2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * The main loop for the interactive session (client side).
7 * As far as I am concerned, the code I have written for this software
8 * can be used freely for any purpose. Any derived versions of this
9 * software must be clearly marked as such, and if the derived work is
10 * incompatible with the protocol description in the RFC file, it must be
11 * called by a name other than "ssh" or "Secure Shell".
14 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
25 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
26 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
31 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
32 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 * SSH2 support added by Markus Friedl.
38 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
49 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
50 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
51 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
52 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
53 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
55 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
56 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
58 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62 RCSID("$OpenBSD: clientloop.c,v 1.120 2004/05/20 10:58:05 dtucker Exp $");
79 #include "clientloop.h"
86 extern Options options;
88 /* Flag indicating that stdin should be redirected from /dev/null. */
89 extern int stdin_null_flag;
91 /* Flag indicating that no shell has been requested */
92 extern int no_shell_flag;
95 * Name of the host we are connecting to. This is the name given on the
96 * command line, or the HostName specified for the user-supplied name in a
102 * Flag to indicate that we have received a window change signal which has
103 * not yet been processed. This will cause a message indicating the new
104 * window size to be sent to the server a little later. This is volatile
105 * because this is updated in a signal handler.
107 static volatile sig_atomic_t received_window_change_signal = 0;
108 static volatile sig_atomic_t received_signal = 0;
110 /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
111 static int in_non_blocking_mode = 0;
113 /* Common data for the client loop code. */
114 static int quit_pending; /* Set to non-zero to quit the client loop. */
115 static int escape_char; /* Escape character. */
116 static int escape_pending; /* Last character was the escape character */
117 static int last_was_cr; /* Last character was a newline. */
118 static int exit_status; /* Used to store the exit status of the command. */
119 static int stdin_eof; /* EOF has been encountered on standard error. */
120 static Buffer stdin_buffer; /* Buffer for stdin data. */
121 static Buffer stdout_buffer; /* Buffer for stdout data. */
122 static Buffer stderr_buffer; /* Buffer for stderr data. */
123 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
124 static u_int buffer_high;/* Soft max buffer size. */
125 static int connection_in; /* Connection to server (input). */
126 static int connection_out; /* Connection to server (output). */
127 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
128 static int session_closed = 0; /* In SSH2: login session closed. */
129 static int server_alive_timeouts = 0;
131 static void client_init_dispatch(void);
132 int session_ident = -1;
137 /* Restores stdin to blocking mode. */
140 leave_non_blocking(void)
142 if (in_non_blocking_mode) {
143 (void) fcntl(fileno(stdin), F_SETFL, 0);
144 in_non_blocking_mode = 0;
148 /* Puts stdin terminal in non-blocking mode. */
151 enter_non_blocking(void)
153 in_non_blocking_mode = 1;
154 (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
158 * Signal handler for the window change signal (SIGWINCH). This just sets a
159 * flag indicating that the window has changed.
163 window_change_handler(int sig)
165 received_window_change_signal = 1;
166 signal(SIGWINCH, window_change_handler);
170 * Signal handler for signals that cause the program to terminate. These
171 * signals must be trapped to restore terminal modes.
175 signal_handler(int sig)
177 received_signal = sig;
182 * Returns current time in seconds from Jan 1, 1970 with the maximum
183 * available resolution.
187 get_current_time(void)
190 gettimeofday(&tv, NULL);
191 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
195 * This is called when the interactive is entered. This checks if there is
196 * an EOF coming on stdin. We must check this explicitly, as select() does
197 * not appear to wake up when redirecting from /dev/null.
201 client_check_initial_eof_on_stdin(void)
207 * If standard input is to be "redirected from /dev/null", we simply
208 * mark that we have seen an EOF and send an EOF message to the
209 * server. Otherwise, we try to read a single character; it appears
210 * that for some files, such /dev/null, select() never wakes up for
211 * read for this descriptor, which means that we never get EOF. This
212 * way we will get the EOF if stdin comes from /dev/null or similar.
214 if (stdin_null_flag) {
215 /* Fake EOF on stdin. */
216 debug("Sending eof.");
218 packet_start(SSH_CMSG_EOF);
221 enter_non_blocking();
223 /* Check for immediate EOF on stdin. */
224 len = read(fileno(stdin), buf, 1);
226 /* EOF. Record that we have seen it and send EOF to server. */
227 debug("Sending eof.");
229 packet_start(SSH_CMSG_EOF);
231 } else if (len > 0) {
233 * Got data. We must store the data in the buffer,
234 * and also process it as an escape character if
237 if ((u_char) buf[0] == escape_char)
240 buffer_append(&stdin_buffer, buf, 1);
242 leave_non_blocking();
248 * Make packets from buffered stdin data, and buffer them for sending to the
253 client_make_packets_from_stdin_data(void)
257 /* Send buffered stdin data to the server. */
258 while (buffer_len(&stdin_buffer) > 0 &&
259 packet_not_very_much_data_to_write()) {
260 len = buffer_len(&stdin_buffer);
261 /* Keep the packets at reasonable size. */
262 if (len > packet_get_maxsize())
263 len = packet_get_maxsize();
264 packet_start(SSH_CMSG_STDIN_DATA);
265 packet_put_string(buffer_ptr(&stdin_buffer), len);
267 buffer_consume(&stdin_buffer, len);
269 /* If we have a pending EOF, send it now. */
270 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
271 packet_start(SSH_CMSG_EOF);
278 * Checks if the client window has changed, and sends a packet about it to
279 * the server if so. The actual change is detected elsewhere (by a software
280 * interrupt on Unix); this just checks the flag and sends a message if
285 client_check_window_change(void)
289 if (! received_window_change_signal)
292 received_window_change_signal = 0;
294 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
297 debug2("client_check_window_change: changed");
300 channel_request_start(session_ident, "window-change", 0);
301 packet_put_int(ws.ws_col);
302 packet_put_int(ws.ws_row);
303 packet_put_int(ws.ws_xpixel);
304 packet_put_int(ws.ws_ypixel);
307 packet_start(SSH_CMSG_WINDOW_SIZE);
308 packet_put_int(ws.ws_row);
309 packet_put_int(ws.ws_col);
310 packet_put_int(ws.ws_xpixel);
311 packet_put_int(ws.ws_ypixel);
317 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
319 server_alive_timeouts = 0;
320 client_global_request_reply_fwd(type, seq, ctxt);
324 server_alive_check(void)
326 if (++server_alive_timeouts > options.server_alive_count_max)
327 packet_disconnect("Timeout, server not responding.");
328 packet_start(SSH2_MSG_GLOBAL_REQUEST);
329 packet_put_cstring("keepalive@openssh.com");
330 packet_put_char(1); /* boolean: want reply */
335 * Waits until the client can do something (some data becomes available on
336 * one of the file descriptors).
340 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
341 int *maxfdp, int *nallocp, int rekeying)
343 struct timeval tv, *tvp;
346 /* Add any selections by the channel mechanism. */
347 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
350 /* Read from the connection, unless our buffers are full. */
351 if (buffer_len(&stdout_buffer) < buffer_high &&
352 buffer_len(&stderr_buffer) < buffer_high &&
353 channel_not_very_much_buffered_data())
354 FD_SET(connection_in, *readsetp);
356 * Read from stdin, unless we have seen EOF or have very much
357 * buffered data to send to the server.
359 if (!stdin_eof && packet_not_very_much_data_to_write())
360 FD_SET(fileno(stdin), *readsetp);
362 /* Select stdout/stderr if have data in buffer. */
363 if (buffer_len(&stdout_buffer) > 0)
364 FD_SET(fileno(stdout), *writesetp);
365 if (buffer_len(&stderr_buffer) > 0)
366 FD_SET(fileno(stderr), *writesetp);
368 /* channel_prepare_select could have closed the last channel */
369 if (session_closed && !channel_still_open() &&
370 !packet_have_data_to_write()) {
371 /* clear mask since we did not call select() */
372 memset(*readsetp, 0, *nallocp);
373 memset(*writesetp, 0, *nallocp);
376 FD_SET(connection_in, *readsetp);
380 /* Select server connection if have data to write to the server. */
381 if (packet_have_data_to_write())
382 FD_SET(connection_out, *writesetp);
385 * Wait for something to happen. This will suspend the process until
386 * some selected descriptor can be read, written, or has some other
390 if (options.server_alive_interval == 0 || !compat20)
393 tv.tv_sec = options.server_alive_interval;
397 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
402 * We have to clear the select masks, because we return.
403 * We have to return, because the mainloop checks for the flags
404 * set by the signal handlers.
406 memset(*readsetp, 0, *nallocp);
407 memset(*writesetp, 0, *nallocp);
411 /* Note: we might still have data in the buffers. */
412 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
413 buffer_append(&stderr_buffer, buf, strlen(buf));
416 server_alive_check();
420 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
422 struct winsize oldws, newws;
424 /* Flush stdout and stderr buffers. */
425 if (buffer_len(bout) > 0)
426 atomicio(vwrite, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
427 if (buffer_len(berr) > 0)
428 atomicio(vwrite, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
433 * Free (and clear) the buffer to reduce the amount of data that gets
440 /* Save old window size. */
441 ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
443 /* Send the suspend signal to the program itself. */
444 kill(getpid(), SIGTSTP);
446 /* Check if the window size has changed. */
447 if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
448 (oldws.ws_row != newws.ws_row ||
449 oldws.ws_col != newws.ws_col ||
450 oldws.ws_xpixel != newws.ws_xpixel ||
451 oldws.ws_ypixel != newws.ws_ypixel))
452 received_window_change_signal = 1;
454 /* OK, we have been continued by the user. Reinitialize buffers. */
463 client_process_net_input(fd_set * readset)
469 * Read input from the server, and add any such data to the buffer of
470 * the packet subsystem.
472 if (FD_ISSET(connection_in, readset)) {
473 /* Read as much as possible. */
474 len = read(connection_in, buf, sizeof(buf));
476 /* Received EOF. The remote host has closed the connection. */
477 snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
479 buffer_append(&stderr_buffer, buf, strlen(buf));
484 * There is a kernel bug on Solaris that causes select to
485 * sometimes wake up even though there is no data available.
487 if (len < 0 && (errno == EAGAIN || errno == EINTR))
491 /* An error has encountered. Perhaps there is a network problem. */
492 snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
493 host, strerror(errno));
494 buffer_append(&stderr_buffer, buf, strlen(buf));
498 packet_process_incoming(buf, len);
503 process_cmdline(void)
505 void (*handler)(int);
507 u_short fwd_port, fwd_host_port;
508 char buf[1024], sfwd_port[6], sfwd_host_port[6];
512 handler = signal(SIGINT, SIG_IGN);
513 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
516 while (*s && isspace(*s))
520 if (strlen(s) < 2 || s[0] != '-' || !(s[1] == 'L' || s[1] == 'R')) {
521 logit("Invalid command.");
526 if (!local && !compat20) {
527 logit("Not supported for SSH protocol version 1.");
531 while (*s && isspace(*s))
534 if (sscanf(s, "%5[0-9]:%255[^:]:%5[0-9]",
535 sfwd_port, buf, sfwd_host_port) != 3 &&
536 sscanf(s, "%5[0-9]/%255[^/]/%5[0-9]",
537 sfwd_port, buf, sfwd_host_port) != 3) {
538 logit("Bad forwarding specification.");
541 if ((fwd_port = a2port(sfwd_port)) == 0 ||
542 (fwd_host_port = a2port(sfwd_host_port)) == 0) {
543 logit("Bad forwarding port(s).");
547 if (channel_setup_local_fwd_listener(fwd_port, buf,
548 fwd_host_port, options.gateway_ports) < 0) {
549 logit("Port forwarding failed.");
553 channel_request_remote_forwarding(fwd_port, buf,
555 logit("Forwarding port.");
557 signal(SIGINT, handler);
563 /* process the characters one by one */
565 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
574 for (i = 0; i < len; i++) {
575 /* Get one character at a time. */
578 if (escape_pending) {
579 /* We have previously seen an escape character. */
580 /* Clear the flag now. */
583 /* Process the escaped character. */
586 /* Terminate the connection. */
587 snprintf(string, sizeof string, "%c.\r\n", escape_char);
588 buffer_append(berr, string, strlen(string));
594 /* Suspend the program. */
595 /* Print a message to that effect to the user. */
596 snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
597 buffer_append(berr, string, strlen(string));
599 /* Restore terminal modes and suspend. */
600 client_suspend_self(bin, bout, berr);
602 /* We have been continued. */
607 snprintf(string, sizeof string,
608 "%cB\r\n", escape_char);
609 buffer_append(berr, string,
611 channel_request_start(session_ident,
613 packet_put_int(1000);
620 if (datafellows & SSH_BUG_NOREKEY)
621 logit("Server does not support re-keying");
629 * Detach the program (continue to serve connections,
630 * but put in background and no more new connections).
632 /* Restore tty modes. */
635 /* Stop listening for new connections. */
636 channel_stop_listening();
638 snprintf(string, sizeof string,
639 "%c& [backgrounded]\n", escape_char);
640 buffer_append(berr, string, strlen(string));
642 /* Fork into background. */
645 error("fork: %.100s", strerror(errno));
648 if (pid != 0) { /* This is the parent. */
649 /* The parent just exits. */
652 /* The child continues serving connections. */
654 buffer_append(bin, "\004", 1);
655 /* fake EOF on stdin */
657 } else if (!stdin_eof) {
659 * Sending SSH_CMSG_EOF alone does not always appear
660 * to be enough. So we try to send an EOF character
663 packet_start(SSH_CMSG_STDIN_DATA);
664 packet_put_string("\004", 1);
668 if (buffer_len(bin) == 0) {
669 packet_start(SSH_CMSG_EOF);
676 snprintf(string, sizeof string,
678 Supported escape sequences:\r\n\
679 %c. - terminate connection\r\n\
680 %cB - send a BREAK to the remote system\r\n\
681 %cC - open a command line\r\n\
682 %cR - Request rekey (SSH protocol 2 only)\r\n\
683 %c^Z - suspend ssh\r\n\
684 %c# - list forwarded connections\r\n\
685 %c& - background ssh (when waiting for connections to terminate)\r\n\
686 %c? - this message\r\n\
687 %c%c - send the escape character by typing it twice\r\n\
688 (Note that escapes are only recognized immediately after newline.)\r\n",
689 escape_char, escape_char, escape_char, escape_char,
690 escape_char, escape_char, escape_char, escape_char,
691 escape_char, escape_char, escape_char);
692 buffer_append(berr, string, strlen(string));
696 snprintf(string, sizeof string, "%c#\r\n", escape_char);
697 buffer_append(berr, string, strlen(string));
698 s = channel_open_message();
699 buffer_append(berr, s, strlen(s));
708 if (ch != escape_char) {
709 buffer_put_char(bin, escape_char);
712 /* Escaped characters fall through here */
717 * The previous character was not an escape char. Check if this
720 if (last_was_cr && ch == escape_char) {
721 /* It is. Set the flag and continue to next character. */
728 * Normal character. Record whether it was a newline,
729 * and append it to the buffer.
731 last_was_cr = (ch == '\r' || ch == '\n');
732 buffer_put_char(bin, ch);
739 client_process_input(fd_set * readset)
744 /* Read input from stdin. */
745 if (FD_ISSET(fileno(stdin), readset)) {
746 /* Read as much as possible. */
747 len = read(fileno(stdin), buf, sizeof(buf));
748 if (len < 0 && (errno == EAGAIN || errno == EINTR))
749 return; /* we'll try again later */
752 * Received EOF or error. They are treated
753 * similarly, except that an error message is printed
754 * if it was an error condition.
757 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
758 buffer_append(&stderr_buffer, buf, strlen(buf));
760 /* Mark that we have seen EOF. */
763 * Send an EOF message to the server unless there is
764 * data in the buffer. If there is data in the
765 * buffer, no message will be sent now. Code
766 * elsewhere will send the EOF when the buffer
767 * becomes empty if stdin_eof is set.
769 if (buffer_len(&stdin_buffer) == 0) {
770 packet_start(SSH_CMSG_EOF);
773 } else if (escape_char == SSH_ESCAPECHAR_NONE) {
775 * Normal successful read, and no escape character.
776 * Just append the data to buffer.
778 buffer_append(&stdin_buffer, buf, len);
781 * Normal, successful read. But we have an escape character
782 * and have to process the characters one by one.
784 if (process_escapes(&stdin_buffer, &stdout_buffer,
785 &stderr_buffer, buf, len) == -1)
792 client_process_output(fd_set * writeset)
797 /* Write buffered output to stdout. */
798 if (FD_ISSET(fileno(stdout), writeset)) {
799 /* Write as much data as possible. */
800 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
801 buffer_len(&stdout_buffer));
803 if (errno == EINTR || errno == EAGAIN)
807 * An error or EOF was encountered. Put an
808 * error message to stderr buffer.
810 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
811 buffer_append(&stderr_buffer, buf, strlen(buf));
816 /* Consume printed data from the buffer. */
817 buffer_consume(&stdout_buffer, len);
820 /* Write buffered output to stderr. */
821 if (FD_ISSET(fileno(stderr), writeset)) {
822 /* Write as much data as possible. */
823 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
824 buffer_len(&stderr_buffer));
826 if (errno == EINTR || errno == EAGAIN)
829 /* EOF or error, but can't even print error message. */
834 /* Consume printed characters from the buffer. */
835 buffer_consume(&stderr_buffer, len);
841 * Get packets from the connection input buffer, and process them as long as
842 * there are packets available.
844 * Any unknown packets received during the actual
845 * session cause the session to terminate. This is
846 * intended to make debugging easier since no
847 * confirmations are sent. Any compatible protocol
848 * extensions must be negotiated during the
853 client_process_buffered_input_packets(void)
855 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
858 /* scan buf[] for '~' before sending data to the peer */
861 simple_escape_filter(Channel *c, char *buf, int len)
863 /* XXX we assume c->extended is writeable */
864 return process_escapes(&c->input, &c->output, &c->extended, buf, len);
868 client_channel_closed(int id, void *arg)
870 if (id != session_ident)
871 error("client_channel_closed: id %d != session_ident %d",
873 channel_cancel_cleanup(id);
879 * Implements the interactive session with the server. This is called after
880 * the user has been authenticated, and a command has been started on the
881 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
882 * used as an escape character for terminating or suspending the session.
886 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
888 fd_set *readset = NULL, *writeset = NULL;
889 double start_time, total_time;
890 int max_fd = 0, max_fd2 = 0, len, rekeying = 0, nalloc = 0;
893 debug("Entering interactive session.");
895 start_time = get_current_time();
897 /* Initialize variables. */
902 buffer_high = 64 * 1024;
903 connection_in = packet_get_connection_in();
904 connection_out = packet_get_connection_out();
905 max_fd = MAX(connection_in, connection_out);
908 /* enable nonblocking unless tty */
909 if (!isatty(fileno(stdin)))
910 set_nonblock(fileno(stdin));
911 if (!isatty(fileno(stdout)))
912 set_nonblock(fileno(stdout));
913 if (!isatty(fileno(stderr)))
914 set_nonblock(fileno(stderr));
915 max_fd = MAX(max_fd, fileno(stdin));
916 max_fd = MAX(max_fd, fileno(stdout));
917 max_fd = MAX(max_fd, fileno(stderr));
923 escape_char = escape_char_arg;
925 /* Initialize buffers. */
926 buffer_init(&stdin_buffer);
927 buffer_init(&stdout_buffer);
928 buffer_init(&stderr_buffer);
930 client_init_dispatch();
933 * Set signal handlers, (e.g. to restore non-blocking mode)
934 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
936 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
937 signal(SIGINT, signal_handler);
938 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
939 signal(SIGQUIT, signal_handler);
940 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
941 signal(SIGTERM, signal_handler);
943 signal(SIGWINCH, window_change_handler);
949 session_ident = ssh2_chan_id;
950 if (escape_char != SSH_ESCAPECHAR_NONE)
951 channel_register_filter(session_ident,
952 simple_escape_filter);
953 if (session_ident != -1)
954 channel_register_cleanup(session_ident,
955 client_channel_closed);
957 /* Check if we should immediately send eof on stdin. */
958 client_check_initial_eof_on_stdin();
961 /* Main loop of the client for the interactive session mode. */
962 while (!quit_pending) {
964 /* Process buffered packets sent by the server. */
965 client_process_buffered_input_packets();
967 if (compat20 && session_closed && !channel_still_open())
970 rekeying = (xxx_kex != NULL && !xxx_kex->done);
973 debug("rekeying in progress");
976 * Make packets of buffered stdin data, and buffer
977 * them for sending to the server.
980 client_make_packets_from_stdin_data();
983 * Make packets from buffered channel data, and
984 * enqueue them for sending to the server.
986 if (packet_not_very_much_data_to_write())
987 channel_output_poll();
990 * Check if the window size has changed, and buffer a
991 * message about it to the server if so.
993 client_check_window_change();
999 * Wait until we have something to do (something becomes
1000 * available on one of the descriptors).
1003 client_wait_until_can_do_something(&readset, &writeset,
1004 &max_fd2, &nalloc, rekeying);
1009 /* Do channel operations unless rekeying in progress. */
1011 channel_after_select(readset, writeset);
1012 if (need_rekeying || packet_need_rekeying()) {
1013 debug("need rekeying");
1015 kex_send_kexinit(xxx_kex);
1020 /* Buffer input from the connection. */
1021 client_process_net_input(readset);
1027 /* Buffer data from stdin */
1028 client_process_input(readset);
1030 * Process output to stdout and stderr. Output to
1031 * the connection is processed elsewhere (above).
1033 client_process_output(writeset);
1036 /* Send as much buffered packet data as possible to the sender. */
1037 if (FD_ISSET(connection_out, writeset))
1038 packet_write_poll();
1045 /* Terminate the session. */
1047 /* Stop watching for window change. */
1049 signal(SIGWINCH, SIG_DFL);
1056 /* restore blocking io */
1057 if (!isatty(fileno(stdin)))
1058 unset_nonblock(fileno(stdin));
1059 if (!isatty(fileno(stdout)))
1060 unset_nonblock(fileno(stdout));
1061 if (!isatty(fileno(stderr)))
1062 unset_nonblock(fileno(stderr));
1065 * If there was no shell or command requested, there will be no remote
1066 * exit status to be returned. In that case, clear error code if the
1067 * connection was deliberately terminated at this end.
1069 if (no_shell_flag && received_signal == SIGTERM) {
1070 received_signal = 0;
1074 if (received_signal)
1075 fatal("Killed by signal %d.", (int) received_signal);
1078 * In interactive mode (with pseudo tty) display a message indicating
1079 * that the connection has been closed.
1081 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1082 snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
1083 buffer_append(&stderr_buffer, buf, strlen(buf));
1086 /* Output any buffered data for stdout. */
1087 while (buffer_len(&stdout_buffer) > 0) {
1088 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1089 buffer_len(&stdout_buffer));
1091 error("Write failed flushing stdout buffer.");
1094 buffer_consume(&stdout_buffer, len);
1095 stdout_bytes += len;
1098 /* Output any buffered data for stderr. */
1099 while (buffer_len(&stderr_buffer) > 0) {
1100 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1101 buffer_len(&stderr_buffer));
1103 error("Write failed flushing stderr buffer.");
1106 buffer_consume(&stderr_buffer, len);
1107 stderr_bytes += len;
1110 /* Clear and free any buffers. */
1111 memset(buf, 0, sizeof(buf));
1112 buffer_free(&stdin_buffer);
1113 buffer_free(&stdout_buffer);
1114 buffer_free(&stderr_buffer);
1116 /* Report bytes transferred, and transfer rates. */
1117 total_time = get_current_time() - start_time;
1118 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
1119 stdin_bytes, stdout_bytes, stderr_bytes, total_time);
1121 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
1122 stdin_bytes / total_time, stdout_bytes / total_time,
1123 stderr_bytes / total_time);
1125 /* Return the exit status of the program. */
1126 debug("Exit status %d", exit_status);
1133 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1136 char *data = packet_get_string(&data_len);
1138 buffer_append(&stdout_buffer, data, data_len);
1139 memset(data, 0, data_len);
1143 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1146 char *data = packet_get_string(&data_len);
1148 buffer_append(&stderr_buffer, data, data_len);
1149 memset(data, 0, data_len);
1153 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1155 exit_status = packet_get_int();
1157 /* Acknowledge the exit. */
1158 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1161 * Must wait for packet to be sent since we are
1164 packet_write_wait();
1165 /* Flag that we want to exit. */
1169 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1172 int remote_id, sock;
1174 /* Read the remote channel number from the message. */
1175 remote_id = packet_get_int();
1179 * Get a connection to the local authentication agent (this may again
1182 sock = ssh_get_authentication_socket();
1185 * If we could not connect the agent, send an error message back to
1186 * the server. This should never happen unless the agent dies,
1187 * because authentication forwarding is only enabled if we have an
1191 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1192 -1, 0, 0, 0, "authentication agent connection", 1);
1193 c->remote_id = remote_id;
1197 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1198 packet_put_int(remote_id);
1200 /* Send a confirmation to the remote host. */
1201 debug("Forwarding authentication connection.");
1202 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1203 packet_put_int(remote_id);
1204 packet_put_int(c->self);
1210 client_request_forwarded_tcpip(const char *request_type, int rchan)
1213 char *listen_address, *originator_address;
1214 int listen_port, originator_port;
1217 /* Get rest of the packet */
1218 listen_address = packet_get_string(NULL);
1219 listen_port = packet_get_int();
1220 originator_address = packet_get_string(NULL);
1221 originator_port = packet_get_int();
1224 debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
1225 listen_address, listen_port, originator_address, originator_port);
1227 sock = channel_connect_by_listen_address(listen_port);
1229 xfree(originator_address);
1230 xfree(listen_address);
1233 c = channel_new("forwarded-tcpip",
1234 SSH_CHANNEL_CONNECTING, sock, sock, -1,
1235 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1236 originator_address, 1);
1237 xfree(originator_address);
1238 xfree(listen_address);
1243 client_request_x11(const char *request_type, int rchan)
1247 int originator_port;
1250 if (!options.forward_x11) {
1251 error("Warning: ssh server tried X11 forwarding.");
1252 error("Warning: this is probably a break in attempt by a malicious server.");
1255 originator = packet_get_string(NULL);
1256 if (datafellows & SSH_BUG_X11FWD) {
1257 debug2("buggy server: x11 request w/o originator_port");
1258 originator_port = 0;
1260 originator_port = packet_get_int();
1263 /* XXX check permission */
1264 debug("client_request_x11: request from %s %d", originator,
1267 sock = x11_connect_display();
1270 c = channel_new("x11",
1271 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1272 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1278 client_request_agent(const char *request_type, int rchan)
1283 if (!options.forward_agent) {
1284 error("Warning: ssh server tried agent forwarding.");
1285 error("Warning: this is probably a break in attempt by a malicious server.");
1288 sock = ssh_get_authentication_socket();
1291 c = channel_new("authentication agent connection",
1292 SSH_CHANNEL_OPEN, sock, sock, -1,
1293 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1294 "authentication agent connection", 1);
1299 /* XXXX move to generic input handler */
1301 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1306 u_int rmaxpack, rwindow, len;
1308 ctype = packet_get_string(&len);
1309 rchan = packet_get_int();
1310 rwindow = packet_get_int();
1311 rmaxpack = packet_get_int();
1313 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1314 ctype, rchan, rwindow, rmaxpack);
1316 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1317 c = client_request_forwarded_tcpip(ctype, rchan);
1318 } else if (strcmp(ctype, "x11") == 0) {
1319 c = client_request_x11(ctype, rchan);
1320 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1321 c = client_request_agent(ctype, rchan);
1323 /* XXX duplicate : */
1325 debug("confirm %s", ctype);
1326 c->remote_id = rchan;
1327 c->remote_window = rwindow;
1328 c->remote_maxpacket = rmaxpack;
1329 if (c->type != SSH_CHANNEL_CONNECTING) {
1330 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1331 packet_put_int(c->remote_id);
1332 packet_put_int(c->self);
1333 packet_put_int(c->local_window);
1334 packet_put_int(c->local_maxpacket);
1338 debug("failure %s", ctype);
1339 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1340 packet_put_int(rchan);
1341 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1342 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1343 packet_put_cstring("open failed");
1344 packet_put_cstring("");
1351 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1354 int id, reply, success = 0;
1357 id = packet_get_int();
1358 rtype = packet_get_string(NULL);
1359 reply = packet_get_char();
1361 debug("client_input_channel_req: channel %d rtype %s reply %d",
1364 if (session_ident == -1) {
1365 error("client_input_channel_req: no channel %d", session_ident);
1366 } else if (id != session_ident) {
1367 error("client_input_channel_req: channel %d: wrong channel: %d",
1370 c = channel_lookup(id);
1372 error("client_input_channel_req: channel %d: unknown channel", id);
1373 } else if (strcmp(rtype, "exit-status") == 0) {
1375 exit_status = packet_get_int();
1379 packet_start(success ?
1380 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1381 packet_put_int(c->remote_id);
1387 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1393 rtype = packet_get_string(NULL);
1394 want_reply = packet_get_char();
1395 debug("client_input_global_request: rtype %s want_reply %d",
1398 packet_start(success ?
1399 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1401 packet_write_wait();
1407 client_init_dispatch_20(void)
1409 dispatch_init(&dispatch_protocol_error);
1411 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1412 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1413 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1414 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1415 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1416 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1417 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1418 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1419 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1420 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1423 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1425 /* global request reply messages */
1426 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
1427 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1430 client_init_dispatch_13(void)
1432 dispatch_init(NULL);
1433 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1434 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1435 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1436 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1437 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1438 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1439 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
1440 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
1441 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1443 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1444 &client_input_agent_open : &deny_input_open);
1445 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
1446 &x11_input_open : &deny_input_open);
1449 client_init_dispatch_15(void)
1451 client_init_dispatch_13();
1452 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1453 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
1456 client_init_dispatch(void)
1459 client_init_dispatch_20();
1461 client_init_dispatch_13();
1463 client_init_dispatch_15();
1466 /* client specific fatal cleanup */
1471 leave_non_blocking();