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 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.62 2001/04/14 16:33:20 stevesk Exp $");
79 #include "clientloop.h"
85 extern Options options;
87 /* Flag indicating that stdin should be redirected from /dev/null. */
88 extern int stdin_null_flag;
91 * Name of the host we are connecting to. This is the name given on the
92 * command line, or the HostName specified for the user-supplied name in a
98 * Flag to indicate that we have received a window change signal which has
99 * not yet been processed. This will cause a message indicating the new
100 * window size to be sent to the server a little later. This is volatile
101 * because this is updated in a signal handler.
103 static volatile int received_window_change_signal = 0;
105 /* Flag indicating whether the user\'s terminal is in non-blocking mode. */
106 static int in_non_blocking_mode = 0;
108 /* Common data for the client loop code. */
109 static int quit_pending; /* Set to non-zero to quit the client loop. */
110 static int escape_char; /* Escape character. */
111 static int escape_pending; /* Last character was the escape character */
112 static int last_was_cr; /* Last character was a newline. */
113 static int exit_status; /* Used to store the exit status of the command. */
114 static int stdin_eof; /* EOF has been encountered on standard error. */
115 static Buffer stdin_buffer; /* Buffer for stdin data. */
116 static Buffer stdout_buffer; /* Buffer for stdout data. */
117 static Buffer stderr_buffer; /* Buffer for stderr data. */
118 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
119 static u_int buffer_high;/* Soft max buffer size. */
120 static int connection_in; /* Connection to server (input). */
121 static int connection_out; /* Connection to server (output). */
122 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
123 static int session_closed = 0; /* In SSH2: login session closed. */
125 void client_init_dispatch(void);
126 int session_ident = -1;
131 /* Restores stdin to blocking mode. */
134 leave_non_blocking(void)
136 if (in_non_blocking_mode) {
137 (void) fcntl(fileno(stdin), F_SETFL, 0);
138 in_non_blocking_mode = 0;
139 fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
143 /* Puts stdin terminal in non-blocking mode. */
146 enter_non_blocking(void)
148 in_non_blocking_mode = 1;
149 (void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
150 fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
154 * Signal handler for the window change signal (SIGWINCH). This just sets a
155 * flag indicating that the window has changed.
159 window_change_handler(int sig)
161 received_window_change_signal = 1;
162 signal(SIGWINCH, window_change_handler);
166 * Signal handler for signals that cause the program to terminate. These
167 * signals must be trapped to restore terminal modes.
171 signal_handler(int sig)
175 if (in_non_blocking_mode)
176 leave_non_blocking();
177 channel_stop_listening();
179 fatal("Killed by signal %d.", sig);
183 * Returns current time in seconds from Jan 1, 1970 with the maximum
184 * available resolution.
188 get_current_time(void)
191 gettimeofday(&tv, NULL);
192 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
196 * This is called when the interactive is entered. This checks if there is
197 * an EOF coming on stdin. We must check this explicitly, as select() does
198 * not appear to wake up when redirecting from /dev/null.
202 client_check_initial_eof_on_stdin(void)
208 * If standard input is to be "redirected from /dev/null", we simply
209 * mark that we have seen an EOF and send an EOF message to the
210 * server. Otherwise, we try to read a single character; it appears
211 * that for some files, such /dev/null, select() never wakes up for
212 * read for this descriptor, which means that we never get EOF. This
213 * way we will get the EOF if stdin comes from /dev/null or similar.
215 if (stdin_null_flag) {
216 /* Fake EOF on stdin. */
217 debug("Sending eof.");
219 packet_start(SSH_CMSG_EOF);
222 enter_non_blocking();
224 /* Check for immediate EOF on stdin. */
225 len = read(fileno(stdin), buf, 1);
227 /* EOF. Record that we have seen it and send EOF to server. */
228 debug("Sending eof.");
230 packet_start(SSH_CMSG_EOF);
232 } else if (len > 0) {
234 * Got data. We must store the data in the buffer,
235 * and also process it as an escape character if
238 if ((u_char) buf[0] == escape_char)
241 buffer_append(&stdin_buffer, buf, 1);
243 leave_non_blocking();
249 * Make packets from buffered stdin data, and buffer them for sending to the
254 client_make_packets_from_stdin_data(void)
258 /* Send buffered stdin data to the server. */
259 while (buffer_len(&stdin_buffer) > 0 &&
260 packet_not_very_much_data_to_write()) {
261 len = buffer_len(&stdin_buffer);
262 /* Keep the packets at reasonable size. */
263 if (len > packet_get_maxsize())
264 len = packet_get_maxsize();
265 packet_start(SSH_CMSG_STDIN_DATA);
266 packet_put_string(buffer_ptr(&stdin_buffer), len);
268 buffer_consume(&stdin_buffer, len);
270 /* If we have a pending EOF, send it now. */
271 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
272 packet_start(SSH_CMSG_EOF);
279 * Checks if the client window has changed, and sends a packet about it to
280 * the server if so. The actual change is detected elsewhere (by a software
281 * interrupt on Unix); this just checks the flag and sends a message if
286 client_check_window_change(void)
290 if (! received_window_change_signal)
293 received_window_change_signal = 0;
295 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
298 debug2("client_check_window_change: changed");
301 channel_request_start(session_ident, "window-change", 0);
302 packet_put_int(ws.ws_col);
303 packet_put_int(ws.ws_row);
304 packet_put_int(ws.ws_xpixel);
305 packet_put_int(ws.ws_ypixel);
308 packet_start(SSH_CMSG_WINDOW_SIZE);
309 packet_put_int(ws.ws_row);
310 packet_put_int(ws.ws_col);
311 packet_put_int(ws.ws_xpixel);
312 packet_put_int(ws.ws_ypixel);
318 * Waits until the client can do something (some data becomes available on
319 * one of the file descriptors).
323 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
324 int *maxfdp, int rekeying)
326 /* Add any selections by the channel mechanism. */
327 channel_prepare_select(readsetp, writesetp, maxfdp, rekeying);
330 /* Read from the connection, unless our buffers are full. */
331 if (buffer_len(&stdout_buffer) < buffer_high &&
332 buffer_len(&stderr_buffer) < buffer_high &&
333 channel_not_very_much_buffered_data())
334 FD_SET(connection_in, *readsetp);
336 * Read from stdin, unless we have seen EOF or have very much
337 * buffered data to send to the server.
339 if (!stdin_eof && packet_not_very_much_data_to_write())
340 FD_SET(fileno(stdin), *readsetp);
342 /* Select stdout/stderr if have data in buffer. */
343 if (buffer_len(&stdout_buffer) > 0)
344 FD_SET(fileno(stdout), *writesetp);
345 if (buffer_len(&stderr_buffer) > 0)
346 FD_SET(fileno(stderr), *writesetp);
348 FD_SET(connection_in, *readsetp);
351 /* Select server connection if have data to write to the server. */
352 if (packet_have_data_to_write())
353 FD_SET(connection_out, *writesetp);
356 * Wait for something to happen. This will suspend the process until
357 * some selected descriptor can be read, written, or has some other
358 * event pending. Note: if you want to implement SSH_MSG_IGNORE
359 * messages to fool traffic analysis, this might be the place to do
360 * it: just have a random timeout for the select, and send a random
361 * SSH_MSG_IGNORE packet when the timeout expires.
364 if (select((*maxfdp)+1, *readsetp, *writesetp, NULL, NULL) < 0) {
368 * We have to clear the select masks, because we return.
369 * We have to return, because the mainloop checks for the flags
370 * set by the signal handlers.
372 memset(*readsetp, 0, *maxfdp);
373 memset(*writesetp, 0, *maxfdp);
377 /* Note: we might still have data in the buffers. */
378 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
379 buffer_append(&stderr_buffer, buf, strlen(buf));
385 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
387 struct winsize oldws, newws;
389 /* Flush stdout and stderr buffers. */
390 if (buffer_len(bout) > 0)
391 atomicio(write, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
392 if (buffer_len(berr) > 0)
393 atomicio(write, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
398 * Free (and clear) the buffer to reduce the amount of data that gets
405 /* Save old window size. */
406 ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
408 /* Send the suspend signal to the program itself. */
409 kill(getpid(), SIGTSTP);
411 /* Check if the window size has changed. */
412 if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
413 (oldws.ws_row != newws.ws_row ||
414 oldws.ws_col != newws.ws_col ||
415 oldws.ws_xpixel != newws.ws_xpixel ||
416 oldws.ws_ypixel != newws.ws_ypixel))
417 received_window_change_signal = 1;
419 /* OK, we have been continued by the user. Reinitialize buffers. */
428 client_process_net_input(fd_set * readset)
434 * Read input from the server, and add any such data to the buffer of
435 * the packet subsystem.
437 if (FD_ISSET(connection_in, readset)) {
438 /* Read as much as possible. */
439 len = read(connection_in, buf, sizeof(buf));
441 /* Received EOF. The remote host has closed the connection. */
442 snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
444 buffer_append(&stderr_buffer, buf, strlen(buf));
449 * There is a kernel bug on Solaris that causes select to
450 * sometimes wake up even though there is no data available.
452 if (len < 0 && (errno == EAGAIN || errno == EINTR))
456 /* An error has encountered. Perhaps there is a network problem. */
457 snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
458 host, strerror(errno));
459 buffer_append(&stderr_buffer, buf, strlen(buf));
463 packet_process_incoming(buf, len);
467 /* process the characters one by one */
469 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
478 for (i = 0; i < len; i++) {
479 /* Get one character at a time. */
482 if (escape_pending) {
483 /* We have previously seen an escape character. */
484 /* Clear the flag now. */
487 /* Process the escaped character. */
490 /* Terminate the connection. */
491 snprintf(string, sizeof string, "%c.\r\n", escape_char);
492 buffer_append(berr, string, strlen(string));
498 /* Suspend the program. */
499 /* Print a message to that effect to the user. */
500 snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
501 buffer_append(berr, string, strlen(string));
503 /* Restore terminal modes and suspend. */
504 client_suspend_self(bin, bout, berr);
506 /* We have been continued. */
511 if (datafellows & SSH_BUG_NOREKEY)
512 log("Server does not support re-keying");
519 /* XXX does not work yet with proto 2 */
523 * Detach the program (continue to serve connections,
524 * but put in background and no more new connections).
528 * Sending SSH_CMSG_EOF alone does not always appear
529 * to be enough. So we try to send an EOF character
532 packet_start(SSH_CMSG_STDIN_DATA);
533 packet_put_string("\004", 1);
537 if (buffer_len(bin) == 0) {
538 packet_start(SSH_CMSG_EOF);
542 /* Restore tty modes. */
545 /* Stop listening for new connections. */
546 channel_stop_listening();
548 printf("%c& [backgrounded]\n", escape_char);
550 /* Fork into background. */
553 error("fork: %.100s", strerror(errno));
556 if (pid != 0) { /* This is the parent. */
557 /* The parent just exits. */
560 /* The child continues serving connections. */
564 snprintf(string, sizeof string,
566 Supported escape sequences:\r\n\
567 ~. - terminate connection\r\n\
568 ~^Z - suspend ssh\r\n\
569 ~# - list forwarded connections\r\n\
570 ~& - background ssh (when waiting for connections to terminate)\r\n\
571 ~? - this message\r\n\
572 ~~ - send the escape character by typing it twice\r\n\
573 (Note that escapes are only recognized immediately after newline.)\r\n",
575 buffer_append(berr, string, strlen(string));
579 snprintf(string, sizeof string, "%c#\r\n", escape_char);
580 buffer_append(berr, string, strlen(string));
581 s = channel_open_message();
582 buffer_append(berr, s, strlen(s));
587 if (ch != escape_char) {
588 buffer_put_char(bin, escape_char);
591 /* Escaped characters fall through here */
596 * The previous character was not an escape char. Check if this
599 if (last_was_cr && ch == escape_char) {
600 /* It is. Set the flag and continue to next character. */
607 * Normal character. Record whether it was a newline,
608 * and append it to the buffer.
610 last_was_cr = (ch == '\r' || ch == '\n');
611 buffer_put_char(bin, ch);
618 client_process_input(fd_set * readset)
623 /* Read input from stdin. */
624 if (FD_ISSET(fileno(stdin), readset)) {
625 /* Read as much as possible. */
626 len = read(fileno(stdin), buf, sizeof(buf));
629 * Received EOF or error. They are treated
630 * similarly, except that an error message is printed
631 * if it was an error condition.
634 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
635 buffer_append(&stderr_buffer, buf, strlen(buf));
637 /* Mark that we have seen EOF. */
640 * Send an EOF message to the server unless there is
641 * data in the buffer. If there is data in the
642 * buffer, no message will be sent now. Code
643 * elsewhere will send the EOF when the buffer
644 * becomes empty if stdin_eof is set.
646 if (buffer_len(&stdin_buffer) == 0) {
647 packet_start(SSH_CMSG_EOF);
650 } else if (escape_char == -1) {
652 * Normal successful read, and no escape character.
653 * Just append the data to buffer.
655 buffer_append(&stdin_buffer, buf, len);
658 * Normal, successful read. But we have an escape character
659 * and have to process the characters one by one.
661 if (process_escapes(&stdin_buffer, &stdout_buffer,
662 &stderr_buffer, buf, len) == -1)
669 client_process_output(fd_set * writeset)
674 /* Write buffered output to stdout. */
675 if (FD_ISSET(fileno(stdout), writeset)) {
676 /* Write as much data as possible. */
677 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
678 buffer_len(&stdout_buffer));
684 * An error or EOF was encountered. Put an
685 * error message to stderr buffer.
687 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
688 buffer_append(&stderr_buffer, buf, strlen(buf));
693 /* Consume printed data from the buffer. */
694 buffer_consume(&stdout_buffer, len);
697 /* Write buffered output to stderr. */
698 if (FD_ISSET(fileno(stderr), writeset)) {
699 /* Write as much data as possible. */
700 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
701 buffer_len(&stderr_buffer));
706 /* EOF or error, but can't even print error message. */
711 /* Consume printed characters from the buffer. */
712 buffer_consume(&stderr_buffer, len);
718 * Get packets from the connection input buffer, and process them as long as
719 * there are packets available.
721 * Any unknown packets received during the actual
722 * session cause the session to terminate. This is
723 * intended to make debugging easier since no
724 * confirmations are sent. Any compatible protocol
725 * extensions must be negotiated during the
730 client_process_buffered_input_packets(void)
732 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
735 /* scan buf[] for '~' before sending data to the peer */
738 simple_escape_filter(Channel *c, char *buf, int len)
740 /* XXX we assume c->extended is writeable */
741 return process_escapes(&c->input, &c->output, &c->extended, buf, len);
745 client_channel_closed(int id, void *arg)
747 if (id != session_ident)
748 error("client_channel_closed: id %d != session_ident %d",
756 * Implements the interactive session with the server. This is called after
757 * the user has been authenticated, and a command has been started on the
758 * remote host. If escape_char != -1, it is the character used as an escape
759 * character for terminating or suspending the session.
763 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
765 fd_set *readset = NULL, *writeset = NULL;
766 double start_time, total_time;
767 int max_fd = 0, len, rekeying = 0;
770 debug("Entering interactive session.");
772 start_time = get_current_time();
774 /* Initialize variables. */
779 buffer_high = 64 * 1024;
780 connection_in = packet_get_connection_in();
781 connection_out = packet_get_connection_out();
782 max_fd = MAX(connection_in, connection_out);
785 max_fd = MAX(max_fd, fileno(stdin));
786 max_fd = MAX(max_fd, fileno(stdout));
787 max_fd = MAX(max_fd, fileno(stderr));
793 escape_char = escape_char_arg;
795 /* Initialize buffers. */
796 buffer_init(&stdin_buffer);
797 buffer_init(&stdout_buffer);
798 buffer_init(&stderr_buffer);
800 client_init_dispatch();
802 /* Set signal handlers to restore non-blocking mode. */
803 signal(SIGINT, signal_handler);
804 signal(SIGQUIT, signal_handler);
805 signal(SIGTERM, signal_handler);
806 signal(SIGPIPE, SIG_IGN);
808 signal(SIGWINCH, window_change_handler);
814 session_ident = ssh2_chan_id;
815 if (escape_char != -1)
816 channel_register_filter(session_ident,
817 simple_escape_filter);
818 if (session_ident != -1)
819 channel_register_cleanup(session_ident,
820 client_channel_closed);
822 /* Check if we should immediately send eof on stdin. */
823 client_check_initial_eof_on_stdin();
826 /* Main loop of the client for the interactive session mode. */
827 while (!quit_pending) {
829 /* Process buffered packets sent by the server. */
830 client_process_buffered_input_packets();
832 if (compat20 && session_closed && !channel_still_open())
835 rekeying = (xxx_kex != NULL && !xxx_kex->done);
838 debug("rekeying in progress");
841 * Make packets of buffered stdin data, and buffer
842 * them for sending to the server.
845 client_make_packets_from_stdin_data();
848 * Make packets from buffered channel data, and
849 * enqueue them for sending to the server.
851 if (packet_not_very_much_data_to_write())
852 channel_output_poll();
855 * Check if the window size has changed, and buffer a
856 * message about it to the server if so.
858 client_check_window_change();
864 * Wait until we have something to do (something becomes
865 * available on one of the descriptors).
867 client_wait_until_can_do_something(&readset, &writeset,
873 /* Do channel operations unless rekeying in progress. */
875 channel_after_select(readset, writeset);
878 debug("user requests rekeying");
880 kex_send_kexinit(xxx_kex);
885 /* Buffer input from the connection. */
886 client_process_net_input(readset);
892 /* Buffer data from stdin */
893 client_process_input(readset);
895 * Process output to stdout and stderr. Output to
896 * the connection is processed elsewhere (above).
898 client_process_output(writeset);
901 /* Send as much buffered packet data as possible to the sender. */
902 if (FD_ISSET(connection_out, writeset))
910 /* Terminate the session. */
912 /* Stop watching for window change. */
914 signal(SIGWINCH, SIG_DFL);
916 /* Stop listening for connections. */
917 channel_stop_listening();
920 * In interactive mode (with pseudo tty) display a message indicating
921 * that the connection has been closed.
923 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
924 snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
925 buffer_append(&stderr_buffer, buf, strlen(buf));
927 /* Output any buffered data for stdout. */
928 while (buffer_len(&stdout_buffer) > 0) {
929 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
930 buffer_len(&stdout_buffer));
932 error("Write failed flushing stdout buffer.");
935 buffer_consume(&stdout_buffer, len);
939 /* Output any buffered data for stderr. */
940 while (buffer_len(&stderr_buffer) > 0) {
941 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
942 buffer_len(&stderr_buffer));
944 error("Write failed flushing stderr buffer.");
947 buffer_consume(&stderr_buffer, len);
954 /* Clear and free any buffers. */
955 memset(buf, 0, sizeof(buf));
956 buffer_free(&stdin_buffer);
957 buffer_free(&stdout_buffer);
958 buffer_free(&stderr_buffer);
960 /* Report bytes transferred, and transfer rates. */
961 total_time = get_current_time() - start_time;
962 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
963 stdin_bytes, stdout_bytes, stderr_bytes, total_time);
965 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
966 stdin_bytes / total_time, stdout_bytes / total_time,
967 stderr_bytes / total_time);
969 /* Return the exit status of the program. */
970 debug("Exit status %d", exit_status);
977 client_input_stdout_data(int type, int plen, void *ctxt)
980 char *data = packet_get_string(&data_len);
981 packet_integrity_check(plen, 4 + data_len, type);
982 buffer_append(&stdout_buffer, data, data_len);
983 memset(data, 0, data_len);
987 client_input_stderr_data(int type, int plen, void *ctxt)
990 char *data = packet_get_string(&data_len);
991 packet_integrity_check(plen, 4 + data_len, type);
992 buffer_append(&stderr_buffer, data, data_len);
993 memset(data, 0, data_len);
997 client_input_exit_status(int type, int plen, void *ctxt)
999 packet_integrity_check(plen, 4, type);
1000 exit_status = packet_get_int();
1001 /* Acknowledge the exit. */
1002 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1005 * Must wait for packet to be sent since we are
1008 packet_write_wait();
1009 /* Flag that we want to exit. */
1014 client_request_forwarded_tcpip(const char *request_type, int rchan)
1017 char *listen_address, *originator_address;
1018 int listen_port, originator_port;
1021 /* Get rest of the packet */
1022 listen_address = packet_get_string(NULL);
1023 listen_port = packet_get_int();
1024 originator_address = packet_get_string(NULL);
1025 originator_port = packet_get_int();
1028 debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
1029 listen_address, listen_port, originator_address, originator_port);
1031 sock = channel_connect_by_listen_adress(listen_port);
1033 newch = channel_new("forwarded-tcpip",
1034 SSH_CHANNEL_CONNECTING, sock, sock, -1,
1035 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1036 xstrdup(originator_address), 1);
1037 c = channel_lookup(newch);
1039 xfree(originator_address);
1040 xfree(listen_address);
1045 client_request_x11(const char *request_type, int rchan)
1049 int originator_port;
1052 if (!options.forward_x11) {
1053 error("Warning: ssh server tried X11 forwarding.");
1054 error("Warning: this is probably a break in attempt by a malicious server.");
1057 originator = packet_get_string(NULL);
1058 if (datafellows & SSH_BUG_X11FWD) {
1059 debug2("buggy server: x11 request w/o originator_port");
1060 originator_port = 0;
1062 originator_port = packet_get_int();
1065 /* XXX check permission */
1066 debug("client_request_x11: request from %s %d", originator,
1068 sock = x11_connect_display();
1070 newch = channel_new("x11",
1071 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1072 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0,
1074 c = channel_lookup(newch);
1081 client_request_agent(const char *request_type, int rchan)
1086 if (!options.forward_agent) {
1087 error("Warning: ssh server tried agent forwarding.");
1088 error("Warning: this is probably a break in attempt by a malicious server.");
1091 sock = ssh_get_authentication_socket();
1093 newch = channel_new("authentication agent connection",
1094 SSH_CHANNEL_OPEN, sock, sock, -1,
1095 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1096 xstrdup("authentication agent connection"), 1);
1097 c = channel_lookup(newch);
1102 /* XXXX move to generic input handler */
1104 client_input_channel_open(int type, int plen, void *ctxt)
1113 ctype = packet_get_string(&len);
1114 rchan = packet_get_int();
1115 rwindow = packet_get_int();
1116 rmaxpack = packet_get_int();
1118 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1119 ctype, rchan, rwindow, rmaxpack);
1121 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1122 c = client_request_forwarded_tcpip(ctype, rchan);
1123 } else if (strcmp(ctype, "x11") == 0) {
1124 c = client_request_x11(ctype, rchan);
1125 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1126 c = client_request_agent(ctype, rchan);
1128 /* XXX duplicate : */
1130 debug("confirm %s", ctype);
1131 c->remote_id = rchan;
1132 c->remote_window = rwindow;
1133 c->remote_maxpacket = rmaxpack;
1135 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1136 packet_put_int(c->remote_id);
1137 packet_put_int(c->self);
1138 packet_put_int(c->local_window);
1139 packet_put_int(c->local_maxpacket);
1142 debug("failure %s", ctype);
1143 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1144 packet_put_int(rchan);
1145 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1146 packet_put_cstring("bla bla");
1147 packet_put_cstring("");
1153 client_input_channel_req(int type, int plen, void *ctxt)
1156 int id, reply, success = 0;
1159 id = packet_get_int();
1160 rtype = packet_get_string(NULL);
1161 reply = packet_get_char();
1163 debug("client_input_channel_req: channel %d rtype %s reply %d",
1166 if (session_ident == -1) {
1167 error("client_input_channel_req: no channel %d", session_ident);
1168 } else if (id != session_ident) {
1169 error("client_input_channel_req: channel %d: wrong channel: %d",
1172 c = channel_lookup(id);
1174 error("client_input_channel_req: channel %d: unknown channel", id);
1175 } else if (strcmp(rtype, "exit-status") == 0) {
1177 exit_status = packet_get_int();
1181 packet_start(success ?
1182 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1183 packet_put_int(c->remote_id);
1190 client_init_dispatch_20(void)
1192 dispatch_init(&dispatch_protocol_error);
1193 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1194 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1195 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1196 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1197 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1198 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1199 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1200 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1201 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1204 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1207 client_init_dispatch_13(void)
1209 dispatch_init(NULL);
1210 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1211 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1212 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1213 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1214 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1215 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1216 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
1217 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
1218 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
1220 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
1221 &auth_input_open_request : &deny_input_open);
1222 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
1223 &x11_input_open : &deny_input_open);
1226 client_init_dispatch_15(void)
1228 client_init_dispatch_13();
1229 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1230 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
1233 client_init_dispatch(void)
1236 client_init_dispatch_20();
1238 client_init_dispatch_13();
1240 client_init_dispatch_15();