1 /* $OpenBSD: clientloop.c,v 1.261 2014/07/15 15:54:14 millert Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The main loop for the interactive session (client side).
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #include <sys/param.h>
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
70 #ifdef HAVE_SYS_TIME_H
71 # include <sys/time.h>
73 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
115 extern Options options
;
117 /* Flag indicating that stdin should be redirected from /dev/null. */
118 extern int stdin_null_flag
;
120 /* Flag indicating that no shell has been requested */
121 extern int no_shell_flag
;
124 extern int muxserver_sock
; /* XXX use mux_client_cleanup() instead */
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the HostName specified for the user-supplied name in a
129 * configuration file.
134 * Flag to indicate that we have received a window change signal which has
135 * not yet been processed. This will cause a message indicating the new
136 * window size to be sent to the server a little later. This is volatile
137 * because this is updated in a signal handler.
139 static volatile sig_atomic_t received_window_change_signal
= 0;
140 static volatile sig_atomic_t received_signal
= 0;
142 /* Flag indicating whether the user's terminal is in non-blocking mode. */
143 static int in_non_blocking_mode
= 0;
145 /* Time when backgrounded control master using ControlPersist should exit */
146 static time_t control_persist_exit_time
= 0;
148 /* Common data for the client loop code. */
149 volatile sig_atomic_t quit_pending
; /* Set non-zero to quit the loop. */
150 static int escape_char1
; /* Escape character. (proto1 only) */
151 static int escape_pending1
; /* Last character was an escape (proto1 only) */
152 static int last_was_cr
; /* Last character was a newline. */
153 static int exit_status
; /* Used to store the command exit status. */
154 static int stdin_eof
; /* EOF has been encountered on stderr. */
155 static Buffer stdin_buffer
; /* Buffer for stdin data. */
156 static Buffer stdout_buffer
; /* Buffer for stdout data. */
157 static Buffer stderr_buffer
; /* Buffer for stderr data. */
158 static u_int buffer_high
; /* Soft max buffer size. */
159 static int connection_in
; /* Connection to server (input). */
160 static int connection_out
; /* Connection to server (output). */
161 static int need_rekeying
; /* Set to non-zero if rekeying is requested. */
162 static int session_closed
; /* In SSH2: login session closed. */
163 static int x11_refuse_time
; /* If >0, refuse x11 opens after this time. */
165 static void client_init_dispatch(void);
166 int session_ident
= -1;
168 int session_resumed
= 0;
170 /* Track escape per proto2 channel */
171 struct escape_filter_ctx
{
176 /* Context for channel confirmation replies */
177 struct channel_reply_ctx
{
178 const char *request_type
;
180 enum confirm_action action
;
183 /* Global request success/failure callbacks */
184 struct global_confirm
{
185 TAILQ_ENTRY(global_confirm
) entry
;
186 global_confirm_cb
*cb
;
190 TAILQ_HEAD(global_confirms
, global_confirm
);
191 static struct global_confirms global_confirms
=
192 TAILQ_HEAD_INITIALIZER(global_confirms
);
197 void ssh_process_session2_setup(int, int, int, Buffer
*);
199 /* Restores stdin to blocking mode. */
202 leave_non_blocking(void)
204 if (in_non_blocking_mode
) {
205 unset_nonblock(fileno(stdin
));
206 in_non_blocking_mode
= 0;
210 /* Puts stdin terminal in non-blocking mode. */
213 enter_non_blocking(void)
215 in_non_blocking_mode
= 1;
216 set_nonblock(fileno(stdin
));
220 * Signal handler for the window change signal (SIGWINCH). This just sets a
221 * flag indicating that the window has changed.
225 window_change_handler(int sig
)
227 received_window_change_signal
= 1;
228 signal(SIGWINCH
, window_change_handler
);
232 * Signal handler for signals that cause the program to terminate. These
233 * signals must be trapped to restore terminal modes.
237 signal_handler(int sig
)
239 received_signal
= sig
;
244 * Returns current time in seconds from Jan 1, 1970 with the maximum
245 * available resolution.
249 get_current_time(void)
252 gettimeofday(&tv
, NULL
);
253 return (double) tv
.tv_sec
+ (double) tv
.tv_usec
/ 1000000.0;
257 * Sets control_persist_exit_time to the absolute time when the
258 * backgrounded control master should exit due to expiry of the
259 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
260 * control master process, or if there is no ControlPersist timeout.
263 set_control_persist_exit_time(void)
265 if (muxserver_sock
== -1 || !options
.control_persist
266 || options
.control_persist_timeout
== 0) {
267 /* not using a ControlPersist timeout */
268 control_persist_exit_time
= 0;
269 } else if (channel_still_open()) {
270 /* some client connections are still open */
271 if (control_persist_exit_time
> 0)
272 debug2("%s: cancel scheduled exit", __func__
);
273 control_persist_exit_time
= 0;
274 } else if (control_persist_exit_time
<= 0) {
275 /* a client connection has recently closed */
276 control_persist_exit_time
= monotime() +
277 (time_t)options
.control_persist_timeout
;
278 debug2("%s: schedule exit in %d seconds", __func__
,
279 options
.control_persist_timeout
);
281 /* else we are already counting down to the timeout */
284 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
286 client_x11_display_valid(const char *display
)
290 dlen
= strlen(display
);
291 for (i
= 0; i
< dlen
; i
++) {
292 if (!isalnum((u_char
)display
[i
]) &&
293 strchr(SSH_X11_VALID_DISPLAY_CHARS
, display
[i
]) == NULL
) {
294 debug("Invalid character '%c' in DISPLAY", display
[i
]);
301 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
303 client_x11_get_proto(const char *display
, const char *xauth_path
,
304 u_int trusted
, u_int timeout
, char **_proto
, char **_data
)
309 static char proto
[512], data
[512];
311 int got_data
= 0, generated
= 0, do_unlink
= 0, i
;
312 char *xauthdir
, *xauthfile
;
316 xauthdir
= xauthfile
= NULL
;
319 proto
[0] = data
[0] = '\0';
321 if (xauth_path
== NULL
||(stat(xauth_path
, &st
) == -1)) {
322 debug("No xauth program.");
323 } else if (!client_x11_display_valid(display
)) {
324 logit("DISPLAY '%s' invalid, falling back to fake xauth data",
327 if (display
== NULL
) {
328 debug("x11_get_proto: DISPLAY not set");
332 * Handle FamilyLocal case where $DISPLAY does
333 * not match an authorization entry. For this we
334 * just try "xauth list unix:displaynum.screennum".
335 * XXX: "localhost" match to determine FamilyLocal
338 if (strncmp(display
, "localhost:", 10) == 0) {
339 snprintf(xdisplay
, sizeof(xdisplay
), "unix:%s",
344 xauthdir
= xmalloc(MAXPATHLEN
);
345 xauthfile
= xmalloc(MAXPATHLEN
);
346 mktemp_proto(xauthdir
, MAXPATHLEN
);
347 if (mkdtemp(xauthdir
) != NULL
) {
349 snprintf(xauthfile
, MAXPATHLEN
, "%s/xauthfile",
351 snprintf(cmd
, sizeof(cmd
),
352 "%s -f %s generate %s " SSH_X11_PROTO
353 " untrusted timeout %u 2>" _PATH_DEVNULL
,
354 xauth_path
, xauthfile
, display
, timeout
);
355 debug2("x11_get_proto: %s", cmd
);
356 if (system(cmd
) == 0)
358 if (x11_refuse_time
== 0) {
359 now
= monotime() + 1;
360 if (UINT_MAX
- timeout
< now
)
361 x11_refuse_time
= UINT_MAX
;
363 x11_refuse_time
= now
+ timeout
;
369 * When in untrusted mode, we read the cookie only if it was
370 * successfully generated as an untrusted one in the step
373 if (trusted
|| generated
) {
374 snprintf(cmd
, sizeof(cmd
),
375 "%s %s%s list %s 2>" _PATH_DEVNULL
,
377 generated
? "-f " : "" ,
378 generated
? xauthfile
: "",
380 debug2("x11_get_proto: %s", cmd
);
382 if (f
&& fgets(line
, sizeof(line
), f
) &&
383 sscanf(line
, "%*s %511s %511s", proto
, data
) == 2)
388 error("Warning: untrusted X11 forwarding setup failed: "
389 "xauth key data not generated");
400 * If we didn't get authentication data, just make up some
401 * data. The forwarding code will check the validity of the
402 * response anyway, and substitute this data. The X11
403 * server, however, will ignore this fake data and use
404 * whatever authentication mechanisms it was using otherwise
405 * for the local connection.
410 logit("Warning: No xauth data; "
411 "using fake authentication data for X11 forwarding.");
412 strlcpy(proto
, SSH_X11_PROTO
, sizeof proto
);
413 for (i
= 0; i
< 16; i
++) {
416 snprintf(data
+ 2 * i
, sizeof data
- 2 * i
, "%02x",
424 * This is called when the interactive is entered. This checks if there is
425 * an EOF coming on stdin. We must check this explicitly, as select() does
426 * not appear to wake up when redirecting from /dev/null.
430 client_check_initial_eof_on_stdin(void)
436 * If standard input is to be "redirected from /dev/null", we simply
437 * mark that we have seen an EOF and send an EOF message to the
438 * server. Otherwise, we try to read a single character; it appears
439 * that for some files, such /dev/null, select() never wakes up for
440 * read for this descriptor, which means that we never get EOF. This
441 * way we will get the EOF if stdin comes from /dev/null or similar.
443 if (stdin_null_flag
) {
444 /* Fake EOF on stdin. */
445 debug("Sending eof.");
447 packet_start(SSH_CMSG_EOF
);
450 enter_non_blocking();
452 /* Check for immediate EOF on stdin. */
453 len
= read(fileno(stdin
), buf
, 1);
456 * EOF. Record that we have seen it and send
459 debug("Sending eof.");
461 packet_start(SSH_CMSG_EOF
);
463 } else if (len
> 0) {
465 * Got data. We must store the data in the buffer,
466 * and also process it as an escape character if
469 if ((u_char
) buf
[0] == escape_char1
)
472 buffer_append(&stdin_buffer
, buf
, 1);
474 leave_non_blocking();
480 * Make packets from buffered stdin data, and buffer them for sending to the
485 client_make_packets_from_stdin_data(void)
489 /* Send buffered stdin data to the server. */
490 while (buffer_len(&stdin_buffer
) > 0 &&
491 packet_not_very_much_data_to_write()) {
492 len
= buffer_len(&stdin_buffer
);
493 /* Keep the packets at reasonable size. */
494 if (len
> packet_get_maxsize())
495 len
= packet_get_maxsize();
496 packet_start(SSH_CMSG_STDIN_DATA
);
497 packet_put_string(buffer_ptr(&stdin_buffer
), len
);
499 buffer_consume(&stdin_buffer
, len
);
500 /* If we have a pending EOF, send it now. */
501 if (stdin_eof
&& buffer_len(&stdin_buffer
) == 0) {
502 packet_start(SSH_CMSG_EOF
);
509 * Checks if the client window has changed, and sends a packet about it to
510 * the server if so. The actual change is detected elsewhere (by a software
511 * interrupt on Unix); this just checks the flag and sends a message if
516 client_check_window_change(void)
520 if (! received_window_change_signal
)
523 received_window_change_signal
= 0;
525 debug2("client_check_window_change: changed");
528 channel_send_window_changes();
530 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
532 packet_start(SSH_CMSG_WINDOW_SIZE
);
533 packet_put_int((u_int
)ws
.ws_row
);
534 packet_put_int((u_int
)ws
.ws_col
);
535 packet_put_int((u_int
)ws
.ws_xpixel
);
536 packet_put_int((u_int
)ws
.ws_ypixel
);
542 client_global_request_reply(int type
, u_int32_t seq
, void *ctxt
)
544 struct global_confirm
*gc
;
546 if ((gc
= TAILQ_FIRST(&global_confirms
)) == NULL
)
549 gc
->cb(type
, seq
, gc
->ctx
);
550 if (--gc
->ref_count
<= 0) {
551 TAILQ_REMOVE(&global_confirms
, gc
, entry
);
552 explicit_bzero(gc
, sizeof(*gc
));
556 packet_set_alive_timeouts(0);
560 server_alive_check(void)
562 if (packet_inc_alive_timeouts() > options
.server_alive_count_max
) {
563 logit("Timeout, server %s not responding.", host
);
566 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
567 packet_put_cstring("keepalive@openssh.com");
568 packet_put_char(1); /* boolean: want reply */
570 /* Insert an empty placeholder to maintain ordering */
571 client_register_global_confirm(NULL
, NULL
);
575 * Waits until the client can do something (some data becomes available on
576 * one of the file descriptors).
579 client_wait_until_can_do_something(fd_set
**readsetp
, fd_set
**writesetp
,
580 int *maxfdp
, u_int
*nallocp
, int rekeying
)
582 struct timeval tv
, *tvp
;
584 time_t minwait_secs
= 0, server_alive_time
= 0, now
= monotime();
587 /* Add any selections by the channel mechanism. */
588 channel_prepare_select(readsetp
, writesetp
, maxfdp
, nallocp
,
589 &minwait_secs
, rekeying
);
592 /* Read from the connection, unless our buffers are full. */
593 if (buffer_len(&stdout_buffer
) < buffer_high
&&
594 buffer_len(&stderr_buffer
) < buffer_high
&&
595 channel_not_very_much_buffered_data())
596 FD_SET(connection_in
, *readsetp
);
598 * Read from stdin, unless we have seen EOF or have very much
599 * buffered data to send to the server.
601 if (!stdin_eof
&& packet_not_very_much_data_to_write())
602 FD_SET(fileno(stdin
), *readsetp
);
604 /* Select stdout/stderr if have data in buffer. */
605 if (buffer_len(&stdout_buffer
) > 0)
606 FD_SET(fileno(stdout
), *writesetp
);
607 if (buffer_len(&stderr_buffer
) > 0)
608 FD_SET(fileno(stderr
), *writesetp
);
610 /* channel_prepare_select could have closed the last channel */
611 if (session_closed
&& !channel_still_open() &&
612 !packet_have_data_to_write()) {
613 /* clear mask since we did not call select() */
614 memset(*readsetp
, 0, *nallocp
);
615 memset(*writesetp
, 0, *nallocp
);
618 FD_SET(connection_in
, *readsetp
);
622 /* Select server connection if have data to write to the server. */
623 if (packet_have_data_to_write())
624 FD_SET(connection_out
, *writesetp
);
627 * Wait for something to happen. This will suspend the process until
628 * some selected descriptor can be read, written, or has some other
629 * event pending, or a timeout expires.
632 timeout_secs
= INT_MAX
; /* we use INT_MAX to mean no timeout */
633 if (options
.server_alive_interval
> 0 && compat20
) {
634 timeout_secs
= options
.server_alive_interval
;
635 server_alive_time
= now
+ options
.server_alive_interval
;
637 if (options
.rekey_interval
> 0 && compat20
&& !rekeying
)
638 timeout_secs
= MIN(timeout_secs
, packet_get_rekey_timeout());
639 set_control_persist_exit_time();
640 if (control_persist_exit_time
> 0) {
641 timeout_secs
= MIN(timeout_secs
,
642 control_persist_exit_time
- now
);
643 if (timeout_secs
< 0)
646 if (minwait_secs
!= 0)
647 timeout_secs
= MIN(timeout_secs
, (int)minwait_secs
);
648 if (timeout_secs
== INT_MAX
)
651 tv
.tv_sec
= timeout_secs
;
656 ret
= select((*maxfdp
)+1, *readsetp
, *writesetp
, NULL
, tvp
);
661 * We have to clear the select masks, because we return.
662 * We have to return, because the mainloop checks for the flags
663 * set by the signal handlers.
665 memset(*readsetp
, 0, *nallocp
);
666 memset(*writesetp
, 0, *nallocp
);
670 /* Note: we might still have data in the buffers. */
671 snprintf(buf
, sizeof buf
, "select: %s\r\n", strerror(errno
));
672 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
674 } else if (ret
== 0) {
676 * Timeout. Could have been either keepalive or rekeying.
677 * Keepalive we check here, rekeying is checked in clientloop.
679 if (server_alive_time
!= 0 && server_alive_time
<= monotime())
680 server_alive_check();
686 client_suspend_self(Buffer
*bin
, Buffer
*bout
, Buffer
*berr
)
688 /* Flush stdout and stderr buffers. */
689 if (buffer_len(bout
) > 0)
690 atomicio(vwrite
, fileno(stdout
), buffer_ptr(bout
),
692 if (buffer_len(berr
) > 0)
693 atomicio(vwrite
, fileno(stderr
), buffer_ptr(berr
),
696 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
699 * Free (and clear) the buffer to reduce the amount of data that gets
706 /* Send the suspend signal to the program itself. */
707 kill(getpid(), SIGTSTP
);
709 /* Reset window sizes in case they have changed */
710 received_window_change_signal
= 1;
712 /* OK, we have been continued by the user. Reinitialize buffers. */
717 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
721 client_process_net_input(fd_set
*readset
)
724 char buf
[SSH_IOBUFSZ
];
727 * Read input from the server, and add any such data to the buffer of
728 * the packet subsystem.
730 if (FD_ISSET(connection_in
, readset
)) {
731 /* Read as much as possible. */
732 len
= roaming_read(connection_in
, buf
, sizeof(buf
), &cont
);
733 if (len
== 0 && cont
== 0) {
735 * Received EOF. The remote host has closed the
738 snprintf(buf
, sizeof buf
,
739 "Connection to %.300s closed by remote host.\r\n",
741 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
746 * There is a kernel bug on Solaris that causes select to
747 * sometimes wake up even though there is no data available.
750 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
755 * An error has encountered. Perhaps there is a
758 snprintf(buf
, sizeof buf
,
759 "Read from remote host %.300s: %.100s\r\n",
760 host
, strerror(errno
));
761 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
765 packet_process_incoming(buf
, len
);
770 client_status_confirm(int type
, Channel
*c
, void *ctx
)
772 struct channel_reply_ctx
*cr
= (struct channel_reply_ctx
*)ctx
;
777 * If a TTY was explicitly requested, then a failure to allocate
780 if (cr
->action
== CONFIRM_TTY
&&
781 (options
.request_tty
== REQUEST_TTY_FORCE
||
782 options
.request_tty
== REQUEST_TTY_YES
))
783 cr
->action
= CONFIRM_CLOSE
;
785 /* XXX supress on mux _client_ quietmode */
786 tochan
= options
.log_level
>= SYSLOG_LEVEL_ERROR
&&
787 c
->ctl_chan
!= -1 && c
->extended_usage
== CHAN_EXTENDED_WRITE
;
789 if (type
== SSH2_MSG_CHANNEL_SUCCESS
) {
790 debug2("%s request accepted on channel %d",
791 cr
->request_type
, c
->self
);
792 } else if (type
== SSH2_MSG_CHANNEL_FAILURE
) {
794 snprintf(errmsg
, sizeof(errmsg
),
795 "%s request failed\r\n", cr
->request_type
);
797 snprintf(errmsg
, sizeof(errmsg
),
798 "%s request failed on channel %d",
799 cr
->request_type
, c
->self
);
801 /* If error occurred on primary session channel, then exit */
802 if (cr
->action
== CONFIRM_CLOSE
&& c
->self
== session_ident
)
805 * If error occurred on mux client, append to
809 buffer_append(&c
->extended
, errmsg
,
813 if (cr
->action
== CONFIRM_TTY
) {
815 * If a TTY allocation error occurred, then arrange
816 * for the correct TTY to leave raw mode.
818 if (c
->self
== session_ident
)
821 mux_tty_alloc_failed(c
);
822 } else if (cr
->action
== CONFIRM_CLOSE
) {
824 chan_write_failed(c
);
831 client_abandon_status_confirm(Channel
*c
, void *ctx
)
837 client_expect_confirm(int id
, const char *request
,
838 enum confirm_action action
)
840 struct channel_reply_ctx
*cr
= xcalloc(1, sizeof(*cr
));
842 cr
->request_type
= request
;
845 channel_register_status_confirm(id
, client_status_confirm
,
846 client_abandon_status_confirm
, cr
);
850 client_register_global_confirm(global_confirm_cb
*cb
, void *ctx
)
852 struct global_confirm
*gc
, *last_gc
;
854 /* Coalesce identical callbacks */
855 last_gc
= TAILQ_LAST(&global_confirms
, global_confirms
);
856 if (last_gc
&& last_gc
->cb
== cb
&& last_gc
->ctx
== ctx
) {
857 if (++last_gc
->ref_count
>= INT_MAX
)
858 fatal("%s: last_gc->ref_count = %d",
859 __func__
, last_gc
->ref_count
);
863 gc
= xcalloc(1, sizeof(*gc
));
867 TAILQ_INSERT_TAIL(&global_confirms
, gc
, entry
);
871 process_cmdline(void)
873 void (*handler
)(int);
875 int ok
, delete = 0, local
= 0, remote
= 0, dynamic
= 0;
878 memset(&fwd
, 0, sizeof(fwd
));
880 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
881 handler
= signal(SIGINT
, SIG_IGN
);
882 cmd
= s
= read_passphrase("\r\nssh> ", RP_ECHO
);
885 while (isspace((u_char
)*s
))
888 s
++; /* Skip cmdline '-', if any */
892 if (*s
== 'h' || *s
== 'H' || *s
== '?') {
894 logit(" -L[bind_address:]port:host:hostport "
895 "Request local forward");
896 logit(" -R[bind_address:]port:host:hostport "
897 "Request remote forward");
898 logit(" -D[bind_address:]port "
899 "Request dynamic forward");
900 logit(" -KL[bind_address:]port "
901 "Cancel local forward");
902 logit(" -KR[bind_address:]port "
903 "Cancel remote forward");
904 logit(" -KD[bind_address:]port "
905 "Cancel dynamic forward");
906 if (!options
.permit_local_command
)
909 "Execute local command");
913 if (*s
== '!' && options
.permit_local_command
) {
930 logit("Invalid command.");
934 if (delete && !compat20
) {
935 logit("Not supported for SSH protocol version 1.");
939 while (isspace((u_char
)*++s
))
942 /* XXX update list of forwards in options */
944 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
945 if (!parse_forward(&fwd
, s
, 1, 0)) {
946 logit("Bad forwarding close specification.");
950 ok
= channel_request_rforward_cancel(&fwd
) == 0;
952 ok
= channel_cancel_lport_listener(&fwd
,
953 0, &options
.fwd_opts
) > 0;
955 ok
= channel_cancel_lport_listener(&fwd
,
956 CHANNEL_CANCEL_PORT_STATIC
,
957 &options
.fwd_opts
) > 0;
959 logit("Unkown port forwarding.");
962 logit("Canceled forwarding.");
964 if (!parse_forward(&fwd
, s
, dynamic
, remote
)) {
965 logit("Bad forwarding specification.");
968 if (local
|| dynamic
) {
969 if (!channel_setup_local_fwd_listener(&fwd
,
970 &options
.fwd_opts
)) {
971 logit("Port forwarding failed.");
975 if (channel_request_remote_forwarding(&fwd
) < 0) {
976 logit("Port forwarding failed.");
980 logit("Forwarding port.");
984 signal(SIGINT
, handler
);
985 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
987 free(fwd
.listen_host
);
988 free(fwd
.listen_path
);
989 free(fwd
.connect_host
);
990 free(fwd
.connect_path
);
993 /* reasons to suppress output of an escape command in help output */
994 #define SUPPRESS_NEVER 0 /* never suppress, always show */
995 #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
996 #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
997 #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
998 #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
999 struct escape_help_text
{
1004 static struct escape_help_text esc_txt
[] = {
1005 {".", "terminate session", SUPPRESS_MUXMASTER
},
1006 {".", "terminate connection (and any multiplexed sessions)",
1007 SUPPRESS_MUXCLIENT
},
1008 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1
},
1009 {"C", "open a command line", SUPPRESS_MUXCLIENT
},
1010 {"R", "request rekey", SUPPRESS_PROTO1
},
1011 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT
},
1012 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT
},
1013 {"#", "list forwarded connections", SUPPRESS_NEVER
},
1014 {"&", "background ssh (when waiting for connections to terminate)",
1015 SUPPRESS_MUXCLIENT
},
1016 {"?", "this message", SUPPRESS_NEVER
},
1020 print_escape_help(Buffer
*b
, int escape_char
, int protocol2
, int mux_client
,
1023 unsigned int i
, suppress_flags
;
1026 snprintf(string
, sizeof string
, "%c?\r\n"
1027 "Supported escape sequences:\r\n", escape_char
);
1028 buffer_append(b
, string
, strlen(string
));
1030 suppress_flags
= (protocol2
? 0 : SUPPRESS_PROTO1
) |
1031 (mux_client
? SUPPRESS_MUXCLIENT
: 0) |
1032 (mux_client
? 0 : SUPPRESS_MUXMASTER
) |
1033 (using_stderr
? 0 : SUPPRESS_SYSLOG
);
1035 for (i
= 0; i
< sizeof(esc_txt
)/sizeof(esc_txt
[0]); i
++) {
1036 if (esc_txt
[i
].flags
& suppress_flags
)
1038 snprintf(string
, sizeof string
, " %c%-3s - %s\r\n",
1039 escape_char
, esc_txt
[i
].cmd
, esc_txt
[i
].text
);
1040 buffer_append(b
, string
, strlen(string
));
1043 snprintf(string
, sizeof string
,
1044 " %c%c - send the escape character by typing it twice\r\n"
1045 "(Note that escapes are only recognized immediately after "
1046 "newline.)\r\n", escape_char
, escape_char
);
1047 buffer_append(b
, string
, strlen(string
));
1051 * Process the characters one by one, call with c==NULL for proto1 case.
1054 process_escapes(Channel
*c
, Buffer
*bin
, Buffer
*bout
, Buffer
*berr
,
1063 int *escape_pendingp
, escape_char
;
1064 struct escape_filter_ctx
*efc
;
1067 escape_pendingp
= &escape_pending1
;
1068 escape_char
= escape_char1
;
1070 if (c
->filter_ctx
== NULL
)
1072 efc
= (struct escape_filter_ctx
*)c
->filter_ctx
;
1073 escape_pendingp
= &efc
->escape_pending
;
1074 escape_char
= efc
->escape_char
;
1080 for (i
= 0; i
< (u_int
)len
; i
++) {
1081 /* Get one character at a time. */
1084 if (*escape_pendingp
) {
1085 /* We have previously seen an escape character. */
1086 /* Clear the flag now. */
1087 *escape_pendingp
= 0;
1089 /* Process the escaped character. */
1092 /* Terminate the connection. */
1093 snprintf(string
, sizeof string
, "%c.\r\n",
1095 buffer_append(berr
, string
, strlen(string
));
1097 if (c
&& c
->ctl_chan
!= -1) {
1098 chan_read_failed(c
);
1099 chan_write_failed(c
);
1101 c
->detach_user(c
->self
, NULL
);
1102 c
->type
= SSH_CHANNEL_ABANDONED
;
1103 buffer_clear(&c
->input
);
1111 /* XXX support this for mux clients */
1112 if (c
&& c
->ctl_chan
!= -1) {
1116 snprintf(b
, sizeof b
, "^Z");
1118 snprintf(b
, sizeof b
, "%c", ch
);
1119 snprintf(string
, sizeof string
,
1120 "%c%s escape not available to "
1121 "multiplexed sessions\r\n",
1123 buffer_append(berr
, string
,
1127 /* Suspend the program. Inform the user */
1128 snprintf(string
, sizeof string
,
1129 "%c^Z [suspend ssh]\r\n", escape_char
);
1130 buffer_append(berr
, string
, strlen(string
));
1132 /* Restore terminal modes and suspend. */
1133 client_suspend_self(bin
, bout
, berr
);
1135 /* We have been continued. */
1140 snprintf(string
, sizeof string
,
1141 "%cB\r\n", escape_char
);
1142 buffer_append(berr
, string
,
1144 channel_request_start(c
->self
,
1146 packet_put_int(1000);
1153 if (datafellows
& SSH_BUG_NOREKEY
)
1154 logit("Server does not "
1155 "support re-keying");
1164 if (c
&& c
->ctl_chan
!= -1)
1166 if (!log_is_on_stderr()) {
1167 snprintf(string
, sizeof string
,
1168 "%c%c [Logging to syslog]\r\n",
1170 buffer_append(berr
, string
,
1174 if (ch
== 'V' && options
.log_level
>
1176 log_change_level(--options
.log_level
);
1177 if (ch
== 'v' && options
.log_level
<
1178 SYSLOG_LEVEL_DEBUG3
)
1179 log_change_level(++options
.log_level
);
1180 snprintf(string
, sizeof string
,
1181 "%c%c [LogLevel %s]\r\n", escape_char
, ch
,
1182 log_level_name(options
.log_level
));
1183 buffer_append(berr
, string
, strlen(string
));
1187 if (c
&& c
->ctl_chan
!= -1)
1190 * Detach the program (continue to serve
1191 * connections, but put in background and no
1192 * more new connections).
1194 /* Restore tty modes. */
1196 options
.request_tty
== REQUEST_TTY_FORCE
);
1198 /* Stop listening for new connections. */
1199 channel_stop_listening();
1201 snprintf(string
, sizeof string
,
1202 "%c& [backgrounded]\n", escape_char
);
1203 buffer_append(berr
, string
, strlen(string
));
1205 /* Fork into background. */
1208 error("fork: %.100s", strerror(errno
));
1211 if (pid
!= 0) { /* This is the parent. */
1212 /* The parent just exits. */
1215 /* The child continues serving connections. */
1217 buffer_append(bin
, "\004", 1);
1218 /* fake EOF on stdin */
1220 } else if (!stdin_eof
) {
1222 * Sending SSH_CMSG_EOF alone does not
1223 * always appear to be enough. So we
1224 * try to send an EOF character first.
1226 packet_start(SSH_CMSG_STDIN_DATA
);
1227 packet_put_string("\004", 1);
1231 if (buffer_len(bin
) == 0) {
1232 packet_start(SSH_CMSG_EOF
);
1239 print_escape_help(berr
, escape_char
, compat20
,
1240 (c
&& c
->ctl_chan
!= -1),
1241 log_is_on_stderr());
1245 snprintf(string
, sizeof string
, "%c#\r\n",
1247 buffer_append(berr
, string
, strlen(string
));
1248 s
= channel_open_message();
1249 buffer_append(berr
, s
, strlen(s
));
1254 if (c
&& c
->ctl_chan
!= -1)
1260 if (ch
!= escape_char
) {
1261 buffer_put_char(bin
, escape_char
);
1264 /* Escaped characters fall through here */
1269 * The previous character was not an escape char.
1270 * Check if this is an escape.
1272 if (last_was_cr
&& ch
== escape_char
) {
1274 * It is. Set the flag and continue to
1277 *escape_pendingp
= 1;
1283 * Normal character. Record whether it was a newline,
1284 * and append it to the buffer.
1286 last_was_cr
= (ch
== '\r' || ch
== '\n');
1287 buffer_put_char(bin
, ch
);
1294 client_process_input(fd_set
*readset
)
1297 char buf
[SSH_IOBUFSZ
];
1299 /* Read input from stdin. */
1300 if (FD_ISSET(fileno(stdin
), readset
)) {
1301 /* Read as much as possible. */
1302 len
= read(fileno(stdin
), buf
, sizeof(buf
));
1304 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
1305 return; /* we'll try again later */
1308 * Received EOF or error. They are treated
1309 * similarly, except that an error message is printed
1310 * if it was an error condition.
1313 snprintf(buf
, sizeof buf
, "read: %.100s\r\n",
1315 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1317 /* Mark that we have seen EOF. */
1320 * Send an EOF message to the server unless there is
1321 * data in the buffer. If there is data in the
1322 * buffer, no message will be sent now. Code
1323 * elsewhere will send the EOF when the buffer
1324 * becomes empty if stdin_eof is set.
1326 if (buffer_len(&stdin_buffer
) == 0) {
1327 packet_start(SSH_CMSG_EOF
);
1330 } else if (escape_char1
== SSH_ESCAPECHAR_NONE
) {
1332 * Normal successful read, and no escape character.
1333 * Just append the data to buffer.
1335 buffer_append(&stdin_buffer
, buf
, len
);
1338 * Normal, successful read. But we have an escape
1339 * character and have to process the characters one
1342 if (process_escapes(NULL
, &stdin_buffer
,
1343 &stdout_buffer
, &stderr_buffer
, buf
, len
) == -1)
1350 client_process_output(fd_set
*writeset
)
1355 /* Write buffered output to stdout. */
1356 if (FD_ISSET(fileno(stdout
), writeset
)) {
1357 /* Write as much data as possible. */
1358 len
= write(fileno(stdout
), buffer_ptr(&stdout_buffer
),
1359 buffer_len(&stdout_buffer
));
1361 if (errno
== EINTR
|| errno
== EAGAIN
||
1362 errno
== EWOULDBLOCK
)
1366 * An error or EOF was encountered. Put an
1367 * error message to stderr buffer.
1369 snprintf(buf
, sizeof buf
,
1370 "write stdout: %.50s\r\n", strerror(errno
));
1371 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1376 /* Consume printed data from the buffer. */
1377 buffer_consume(&stdout_buffer
, len
);
1379 /* Write buffered output to stderr. */
1380 if (FD_ISSET(fileno(stderr
), writeset
)) {
1381 /* Write as much data as possible. */
1382 len
= write(fileno(stderr
), buffer_ptr(&stderr_buffer
),
1383 buffer_len(&stderr_buffer
));
1385 if (errno
== EINTR
|| errno
== EAGAIN
||
1386 errno
== EWOULDBLOCK
)
1390 * EOF or error, but can't even print
1397 /* Consume printed characters from the buffer. */
1398 buffer_consume(&stderr_buffer
, len
);
1403 * Get packets from the connection input buffer, and process them as long as
1404 * there are packets available.
1406 * Any unknown packets received during the actual
1407 * session cause the session to terminate. This is
1408 * intended to make debugging easier since no
1409 * confirmations are sent. Any compatible protocol
1410 * extensions must be negotiated during the
1411 * preparatory phase.
1415 client_process_buffered_input_packets(void)
1417 dispatch_run(DISPATCH_NONBLOCK
, &quit_pending
,
1418 compat20
? xxx_kex
: NULL
);
1421 /* scan buf[] for '~' before sending data to the peer */
1423 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1425 client_new_escape_filter_ctx(int escape_char
)
1427 struct escape_filter_ctx
*ret
;
1429 ret
= xcalloc(1, sizeof(*ret
));
1430 ret
->escape_pending
= 0;
1431 ret
->escape_char
= escape_char
;
1435 /* Free the escape filter context on channel free */
1437 client_filter_cleanup(int cid
, void *ctx
)
1443 client_simple_escape_filter(Channel
*c
, char *buf
, int len
)
1445 if (c
->extended_usage
!= CHAN_EXTENDED_WRITE
)
1448 return process_escapes(c
, &c
->input
, &c
->output
, &c
->extended
,
1453 client_channel_closed(int id
, void *arg
)
1455 channel_cancel_cleanup(id
);
1457 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1461 * Implements the interactive session with the server. This is called after
1462 * the user has been authenticated, and a command has been started on the
1463 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1464 * used as an escape character for terminating or suspending the session.
1468 client_loop(int have_pty
, int escape_char_arg
, int ssh2_chan_id
)
1470 fd_set
*readset
= NULL
, *writeset
= NULL
;
1471 double start_time
, total_time
;
1472 int max_fd
= 0, max_fd2
= 0, len
, rekeying
= 0;
1473 u_int64_t ibytes
, obytes
;
1477 debug("Entering interactive session.");
1479 start_time
= get_current_time();
1481 /* Initialize variables. */
1482 escape_pending1
= 0;
1486 buffer_high
= 64 * 1024;
1487 connection_in
= packet_get_connection_in();
1488 connection_out
= packet_get_connection_out();
1489 max_fd
= MAX(connection_in
, connection_out
);
1492 /* enable nonblocking unless tty */
1493 if (!isatty(fileno(stdin
)))
1494 set_nonblock(fileno(stdin
));
1495 if (!isatty(fileno(stdout
)))
1496 set_nonblock(fileno(stdout
));
1497 if (!isatty(fileno(stderr
)))
1498 set_nonblock(fileno(stderr
));
1499 max_fd
= MAX(max_fd
, fileno(stdin
));
1500 max_fd
= MAX(max_fd
, fileno(stdout
));
1501 max_fd
= MAX(max_fd
, fileno(stderr
));
1504 escape_char1
= escape_char_arg
;
1506 /* Initialize buffers. */
1507 buffer_init(&stdin_buffer
);
1508 buffer_init(&stdout_buffer
);
1509 buffer_init(&stderr_buffer
);
1511 client_init_dispatch();
1514 * Set signal handlers, (e.g. to restore non-blocking mode)
1515 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1517 if (signal(SIGHUP
, SIG_IGN
) != SIG_IGN
)
1518 signal(SIGHUP
, signal_handler
);
1519 if (signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
1520 signal(SIGINT
, signal_handler
);
1521 if (signal(SIGQUIT
, SIG_IGN
) != SIG_IGN
)
1522 signal(SIGQUIT
, signal_handler
);
1523 if (signal(SIGTERM
, SIG_IGN
) != SIG_IGN
)
1524 signal(SIGTERM
, signal_handler
);
1525 signal(SIGWINCH
, window_change_handler
);
1528 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1531 session_ident
= ssh2_chan_id
;
1532 if (session_ident
!= -1) {
1533 if (escape_char_arg
!= SSH_ESCAPECHAR_NONE
) {
1534 channel_register_filter(session_ident
,
1535 client_simple_escape_filter
, NULL
,
1536 client_filter_cleanup
,
1537 client_new_escape_filter_ctx(
1540 channel_register_cleanup(session_ident
,
1541 client_channel_closed
, 0);
1544 /* Check if we should immediately send eof on stdin. */
1545 client_check_initial_eof_on_stdin();
1548 /* Main loop of the client for the interactive session mode. */
1549 while (!quit_pending
) {
1551 /* Process buffered packets sent by the server. */
1552 client_process_buffered_input_packets();
1554 if (compat20
&& session_closed
&& !channel_still_open())
1557 rekeying
= (xxx_kex
!= NULL
&& !xxx_kex
->done
);
1560 debug("rekeying in progress");
1563 * Make packets of buffered stdin data, and buffer
1564 * them for sending to the server.
1567 client_make_packets_from_stdin_data();
1570 * Make packets from buffered channel data, and
1571 * enqueue them for sending to the server.
1573 if (packet_not_very_much_data_to_write())
1574 channel_output_poll();
1577 * Check if the window size has changed, and buffer a
1578 * message about it to the server if so.
1580 client_check_window_change();
1586 * Wait until we have something to do (something becomes
1587 * available on one of the descriptors).
1590 client_wait_until_can_do_something(&readset
, &writeset
,
1591 &max_fd2
, &nalloc
, rekeying
);
1596 /* Do channel operations unless rekeying in progress. */
1598 channel_after_select(readset
, writeset
);
1599 if (need_rekeying
|| packet_need_rekeying()) {
1600 debug("need rekeying");
1602 kex_send_kexinit(xxx_kex
);
1607 /* Buffer input from the connection. */
1608 client_process_net_input(readset
);
1614 /* Buffer data from stdin */
1615 client_process_input(readset
);
1617 * Process output to stdout and stderr. Output to
1618 * the connection is processed elsewhere (above).
1620 client_process_output(writeset
);
1623 if (session_resumed
) {
1624 connection_in
= packet_get_connection_in();
1625 connection_out
= packet_get_connection_out();
1626 max_fd
= MAX(max_fd
, connection_out
);
1627 max_fd
= MAX(max_fd
, connection_in
);
1628 session_resumed
= 0;
1632 * Send as much buffered packet data as possible to the
1635 if (FD_ISSET(connection_out
, writeset
))
1636 packet_write_poll();
1639 * If we are a backgrounded control master, and the
1640 * timeout has expired without any active client
1641 * connections, then quit.
1643 if (control_persist_exit_time
> 0) {
1644 if (monotime() >= control_persist_exit_time
) {
1645 debug("ControlPersist timeout expired");
1653 /* Terminate the session. */
1655 /* Stop watching for window change. */
1656 signal(SIGWINCH
, SIG_DFL
);
1659 packet_start(SSH2_MSG_DISCONNECT
);
1660 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION
);
1661 packet_put_cstring("disconnected by user");
1662 packet_put_cstring(""); /* language tag */
1664 packet_write_wait();
1670 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1672 /* restore blocking io */
1673 if (!isatty(fileno(stdin
)))
1674 unset_nonblock(fileno(stdin
));
1675 if (!isatty(fileno(stdout
)))
1676 unset_nonblock(fileno(stdout
));
1677 if (!isatty(fileno(stderr
)))
1678 unset_nonblock(fileno(stderr
));
1681 * If there was no shell or command requested, there will be no remote
1682 * exit status to be returned. In that case, clear error code if the
1683 * connection was deliberately terminated at this end.
1685 if (no_shell_flag
&& received_signal
== SIGTERM
) {
1686 received_signal
= 0;
1690 if (received_signal
)
1691 fatal("Killed by signal %d.", (int) received_signal
);
1694 * In interactive mode (with pseudo tty) display a message indicating
1695 * that the connection has been closed.
1697 if (have_pty
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
) {
1698 snprintf(buf
, sizeof buf
,
1699 "Connection to %.64s closed.\r\n", host
);
1700 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1703 /* Output any buffered data for stdout. */
1704 if (buffer_len(&stdout_buffer
) > 0) {
1705 len
= atomicio(vwrite
, fileno(stdout
),
1706 buffer_ptr(&stdout_buffer
), buffer_len(&stdout_buffer
));
1707 if (len
< 0 || (u_int
)len
!= buffer_len(&stdout_buffer
))
1708 error("Write failed flushing stdout buffer.");
1710 buffer_consume(&stdout_buffer
, len
);
1713 /* Output any buffered data for stderr. */
1714 if (buffer_len(&stderr_buffer
) > 0) {
1715 len
= atomicio(vwrite
, fileno(stderr
),
1716 buffer_ptr(&stderr_buffer
), buffer_len(&stderr_buffer
));
1717 if (len
< 0 || (u_int
)len
!= buffer_len(&stderr_buffer
))
1718 error("Write failed flushing stderr buffer.");
1720 buffer_consume(&stderr_buffer
, len
);
1723 /* Clear and free any buffers. */
1724 memset(buf
, 0, sizeof(buf
));
1725 buffer_free(&stdin_buffer
);
1726 buffer_free(&stdout_buffer
);
1727 buffer_free(&stderr_buffer
);
1729 /* Report bytes transferred, and transfer rates. */
1730 total_time
= get_current_time() - start_time
;
1731 packet_get_state(MODE_IN
, NULL
, NULL
, NULL
, &ibytes
);
1732 packet_get_state(MODE_OUT
, NULL
, NULL
, NULL
, &obytes
);
1733 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1734 (unsigned long long)obytes
, (unsigned long long)ibytes
, total_time
);
1736 verbose("Bytes per second: sent %.1f, received %.1f",
1737 obytes
/ total_time
, ibytes
/ total_time
);
1738 /* Return the exit status of the program. */
1739 debug("Exit status %d", exit_status
);
1746 client_input_stdout_data(int type
, u_int32_t seq
, void *ctxt
)
1749 char *data
= packet_get_string(&data_len
);
1751 buffer_append(&stdout_buffer
, data
, data_len
);
1752 explicit_bzero(data
, data_len
);
1756 client_input_stderr_data(int type
, u_int32_t seq
, void *ctxt
)
1759 char *data
= packet_get_string(&data_len
);
1761 buffer_append(&stderr_buffer
, data
, data_len
);
1762 explicit_bzero(data
, data_len
);
1766 client_input_exit_status(int type
, u_int32_t seq
, void *ctxt
)
1768 exit_status
= packet_get_int();
1770 /* Acknowledge the exit. */
1771 packet_start(SSH_CMSG_EXIT_CONFIRMATION
);
1774 * Must wait for packet to be sent since we are
1777 packet_write_wait();
1778 /* Flag that we want to exit. */
1782 client_input_agent_open(int type
, u_int32_t seq
, void *ctxt
)
1785 int remote_id
, sock
;
1787 /* Read the remote channel number from the message. */
1788 remote_id
= packet_get_int();
1792 * Get a connection to the local authentication agent (this may again
1795 sock
= ssh_get_authentication_socket();
1798 * If we could not connect the agent, send an error message back to
1799 * the server. This should never happen unless the agent dies,
1800 * because authentication forwarding is only enabled if we have an
1804 c
= channel_new("", SSH_CHANNEL_OPEN
, sock
, sock
,
1805 -1, 0, 0, 0, "authentication agent connection", 1);
1806 c
->remote_id
= remote_id
;
1810 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1811 packet_put_int(remote_id
);
1813 /* Send a confirmation to the remote host. */
1814 debug("Forwarding authentication connection.");
1815 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1816 packet_put_int(remote_id
);
1817 packet_put_int(c
->self
);
1823 client_request_forwarded_tcpip(const char *request_type
, int rchan
)
1826 char *listen_address
, *originator_address
;
1827 u_short listen_port
, originator_port
;
1829 /* Get rest of the packet */
1830 listen_address
= packet_get_string(NULL
);
1831 listen_port
= packet_get_int();
1832 originator_address
= packet_get_string(NULL
);
1833 originator_port
= packet_get_int();
1836 debug("%s: listen %s port %d, originator %s port %d", __func__
,
1837 listen_address
, listen_port
, originator_address
, originator_port
);
1839 c
= channel_connect_by_listen_address(listen_address
, listen_port
,
1840 "forwarded-tcpip", originator_address
);
1842 free(originator_address
);
1843 free(listen_address
);
1848 client_request_forwarded_streamlocal(const char *request_type
, int rchan
)
1853 /* Get the remote path. */
1854 listen_path
= packet_get_string(NULL
);
1855 /* XXX: Skip reserved field for now. */
1856 if (packet_get_string_ptr(NULL
) == NULL
)
1857 fatal("%s: packet_get_string_ptr failed", __func__
);
1860 debug("%s: %s", __func__
, listen_path
);
1862 c
= channel_connect_by_listen_path(listen_path
,
1863 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1869 client_request_x11(const char *request_type
, int rchan
)
1873 u_short originator_port
;
1876 if (!options
.forward_x11
) {
1877 error("Warning: ssh server tried X11 forwarding.");
1878 error("Warning: this is probably a break-in attempt by a "
1879 "malicious server.");
1882 if (x11_refuse_time
!= 0 && monotime() >= x11_refuse_time
) {
1883 verbose("Rejected X11 connection after ForwardX11Timeout "
1887 originator
= packet_get_string(NULL
);
1888 if (datafellows
& SSH_BUG_X11FWD
) {
1889 debug2("buggy server: x11 request w/o originator_port");
1890 originator_port
= 0;
1892 originator_port
= packet_get_int();
1895 /* XXX check permission */
1896 debug("client_request_x11: request from %s %d", originator
,
1899 sock
= x11_connect_display();
1902 /* again is this really necessary for X11? */
1903 if (options
.hpn_disabled
)
1904 c
= channel_new("x11",
1905 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1,
1906 CHAN_TCP_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
, 0, "x11", 1);
1908 c
= channel_new("x11",
1909 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1,
1910 options
.hpn_buffer_size
, CHAN_X11_PACKET_DEFAULT
, 0, "x11", 1);
1916 client_request_agent(const char *request_type
, int rchan
)
1921 if (!options
.forward_agent
) {
1922 error("Warning: ssh server tried agent forwarding.");
1923 error("Warning: this is probably a break-in attempt by a "
1924 "malicious server.");
1927 sock
= ssh_get_authentication_socket();
1930 if (options
.hpn_disabled
)
1931 c
= channel_new("authentication agent connection",
1932 SSH_CHANNEL_OPEN
, sock
, sock
, -1,
1933 CHAN_X11_WINDOW_DEFAULT
, CHAN_TCP_WINDOW_DEFAULT
, 0,
1934 "authentication agent connection", 1);
1936 c
= channel_new("authentication agent connection",
1937 SSH_CHANNEL_OPEN
, sock
, sock
, -1,
1938 options
.hpn_buffer_size
, options
.hpn_buffer_size
, 0,
1939 "authentication agent connection", 1);
1945 client_request_tun_fwd(int tun_mode
, int local_tun
, int remote_tun
)
1950 if (tun_mode
== SSH_TUNMODE_NO
)
1954 error("Tunnel forwarding is not supported for protocol 1");
1958 debug("Requesting tun unit %d in mode %d", local_tun
, tun_mode
);
1960 /* Open local tunnel device */
1961 if ((fd
= tun_open(local_tun
, tun_mode
)) == -1) {
1962 error("Tunnel device open failed.");
1966 if(options
.hpn_disabled
)
1967 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1968 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1971 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1972 options
.hpn_buffer_size
, CHAN_TCP_PACKET_DEFAULT
,
1978 #if defined(SSH_TUN_FILTER)
1979 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1980 channel_register_filter(c
->self
, sys_tun_infilter
,
1981 sys_tun_outfilter
, NULL
, NULL
);
1984 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1985 packet_put_cstring("tun@openssh.com");
1986 packet_put_int(c
->self
);
1987 packet_put_int(c
->local_window_max
);
1988 packet_put_int(c
->local_maxpacket
);
1989 packet_put_int(tun_mode
);
1990 packet_put_int(remote_tun
);
1996 /* XXXX move to generic input handler */
1998 client_input_channel_open(int type
, u_int32_t seq
, void *ctxt
)
2003 u_int rmaxpack
, rwindow
, len
;
2005 ctype
= packet_get_string(&len
);
2006 rchan
= packet_get_int();
2007 rwindow
= packet_get_int();
2008 rmaxpack
= packet_get_int();
2010 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2011 ctype
, rchan
, rwindow
, rmaxpack
);
2013 if (strcmp(ctype
, "forwarded-tcpip") == 0) {
2014 c
= client_request_forwarded_tcpip(ctype
, rchan
);
2015 } else if (strcmp(ctype
, "forwarded-streamlocal@openssh.com") == 0) {
2016 c
= client_request_forwarded_streamlocal(ctype
, rchan
);
2017 } else if (strcmp(ctype
, "x11") == 0) {
2018 c
= client_request_x11(ctype
, rchan
);
2019 } else if (strcmp(ctype
, "auth-agent@openssh.com") == 0) {
2020 c
= client_request_agent(ctype
, rchan
);
2022 /* XXX duplicate : */
2024 debug("confirm %s", ctype
);
2025 c
->remote_id
= rchan
;
2026 c
->remote_window
= rwindow
;
2027 c
->remote_maxpacket
= rmaxpack
;
2028 if (c
->type
!= SSH_CHANNEL_CONNECTING
) {
2029 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
2030 packet_put_int(c
->remote_id
);
2031 packet_put_int(c
->self
);
2032 packet_put_int(c
->local_window
);
2033 packet_put_int(c
->local_maxpacket
);
2037 debug("failure %s", ctype
);
2038 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
2039 packet_put_int(rchan
);
2040 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
);
2041 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
2042 packet_put_cstring("open failed");
2043 packet_put_cstring("");
2050 client_input_channel_req(int type
, u_int32_t seq
, void *ctxt
)
2053 int exitval
, id
, reply
, success
= 0;
2056 id
= packet_get_int();
2057 rtype
= packet_get_string(NULL
);
2058 reply
= packet_get_char();
2060 debug("client_input_channel_req: channel %d rtype %s reply %d",
2064 error("client_input_channel_req: request for channel -1");
2065 } else if ((c
= channel_lookup(id
)) == NULL
) {
2066 error("client_input_channel_req: channel %d: "
2067 "unknown channel", id
);
2068 } else if (strcmp(rtype
, "eow@openssh.com") == 0) {
2071 } else if (strcmp(rtype
, "exit-status") == 0) {
2072 exitval
= packet_get_int();
2073 if (c
->ctl_chan
!= -1) {
2074 mux_exit_message(c
, exitval
);
2076 } else if (id
== session_ident
) {
2077 /* Record exit value of local session */
2079 exit_status
= exitval
;
2081 /* Probably for a mux channel that has already closed */
2082 debug("%s: no sink for exit-status on channel %d",
2087 if (reply
&& c
!= NULL
&& !(c
->flags
& CHAN_CLOSE_SENT
)) {
2088 packet_start(success
?
2089 SSH2_MSG_CHANNEL_SUCCESS
: SSH2_MSG_CHANNEL_FAILURE
);
2090 packet_put_int(c
->remote_id
);
2096 client_input_global_request(int type
, u_int32_t seq
, void *ctxt
)
2102 rtype
= packet_get_string(NULL
);
2103 want_reply
= packet_get_char();
2104 debug("client_input_global_request: rtype %s want_reply %d",
2107 packet_start(success
?
2108 SSH2_MSG_REQUEST_SUCCESS
: SSH2_MSG_REQUEST_FAILURE
);
2110 packet_write_wait();
2116 client_session2_setup(int id
, int want_tty
, int want_subsystem
,
2117 const char *term
, struct termios
*tiop
, int in_fd
, Buffer
*cmd
, char **env
)
2122 debug2("%s: id %d", __func__
, id
);
2124 if ((c
= channel_lookup(id
)) == NULL
)
2125 fatal("client_session2_setup: channel %d: unknown channel", id
);
2127 packet_set_interactive(want_tty
,
2128 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
2133 /* Store window size in the packet. */
2134 if (ioctl(in_fd
, TIOCGWINSZ
, &ws
) < 0)
2135 memset(&ws
, 0, sizeof(ws
));
2137 channel_request_start(id
, "pty-req", 1);
2138 client_expect_confirm(id
, "PTY allocation", CONFIRM_TTY
);
2139 packet_put_cstring(term
!= NULL
? term
: "");
2140 packet_put_int((u_int
)ws
.ws_col
);
2141 packet_put_int((u_int
)ws
.ws_row
);
2142 packet_put_int((u_int
)ws
.ws_xpixel
);
2143 packet_put_int((u_int
)ws
.ws_ypixel
);
2145 tiop
= get_saved_tio();
2146 tty_make_modes(-1, tiop
);
2148 /* XXX wait for reply */
2152 /* Transfer any environment variables from client to server */
2153 if (options
.num_send_env
!= 0 && env
!= NULL
) {
2157 debug("Sending environment.");
2158 for (i
= 0; env
[i
] != NULL
; i
++) {
2160 name
= xstrdup(env
[i
]);
2161 if ((val
= strchr(name
, '=')) == NULL
) {
2168 for (j
= 0; j
< options
.num_send_env
; j
++) {
2169 if (match_pattern(name
, options
.send_env
[j
])) {
2175 debug3("Ignored env %s", name
);
2180 debug("Sending env %s = %s", name
, val
);
2181 channel_request_start(id
, "env", 0);
2182 packet_put_cstring(name
);
2183 packet_put_cstring(val
);
2189 len
= buffer_len(cmd
);
2193 if (want_subsystem
) {
2194 debug("Sending subsystem: %.*s",
2195 len
, (u_char
*)buffer_ptr(cmd
));
2196 channel_request_start(id
, "subsystem", 1);
2197 client_expect_confirm(id
, "subsystem", CONFIRM_CLOSE
);
2199 debug("Sending command: %.*s",
2200 len
, (u_char
*)buffer_ptr(cmd
));
2201 channel_request_start(id
, "exec", 1);
2202 client_expect_confirm(id
, "exec", CONFIRM_CLOSE
);
2204 packet_put_string(buffer_ptr(cmd
), buffer_len(cmd
));
2207 channel_request_start(id
, "shell", 1);
2208 client_expect_confirm(id
, "shell", CONFIRM_CLOSE
);
2214 client_init_dispatch_20(void)
2216 dispatch_init(&dispatch_protocol_error
);
2218 dispatch_set(SSH2_MSG_CHANNEL_CLOSE
, &channel_input_oclose
);
2219 dispatch_set(SSH2_MSG_CHANNEL_DATA
, &channel_input_data
);
2220 dispatch_set(SSH2_MSG_CHANNEL_EOF
, &channel_input_ieof
);
2221 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA
, &channel_input_extended_data
);
2222 dispatch_set(SSH2_MSG_CHANNEL_OPEN
, &client_input_channel_open
);
2223 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2224 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2225 dispatch_set(SSH2_MSG_CHANNEL_REQUEST
, &client_input_channel_req
);
2226 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST
, &channel_input_window_adjust
);
2227 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS
, &channel_input_status_confirm
);
2228 dispatch_set(SSH2_MSG_CHANNEL_FAILURE
, &channel_input_status_confirm
);
2229 dispatch_set(SSH2_MSG_GLOBAL_REQUEST
, &client_input_global_request
);
2232 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
2234 /* global request reply messages */
2235 dispatch_set(SSH2_MSG_REQUEST_FAILURE
, &client_global_request_reply
);
2236 dispatch_set(SSH2_MSG_REQUEST_SUCCESS
, &client_global_request_reply
);
2240 client_init_dispatch_13(void)
2242 dispatch_init(NULL
);
2243 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_close
);
2244 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, &channel_input_close_confirmation
);
2245 dispatch_set(SSH_MSG_CHANNEL_DATA
, &channel_input_data
);
2246 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2247 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2248 dispatch_set(SSH_MSG_PORT_OPEN
, &channel_input_port_open
);
2249 dispatch_set(SSH_SMSG_EXITSTATUS
, &client_input_exit_status
);
2250 dispatch_set(SSH_SMSG_STDERR_DATA
, &client_input_stderr_data
);
2251 dispatch_set(SSH_SMSG_STDOUT_DATA
, &client_input_stdout_data
);
2253 dispatch_set(SSH_SMSG_AGENT_OPEN
, options
.forward_agent
?
2254 &client_input_agent_open
: &deny_input_open
);
2255 dispatch_set(SSH_SMSG_X11_OPEN
, options
.forward_x11
?
2256 &x11_input_open
: &deny_input_open
);
2260 client_init_dispatch_15(void)
2262 client_init_dispatch_13();
2263 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_ieof
);
2264 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, & channel_input_oclose
);
2268 client_init_dispatch(void)
2271 client_init_dispatch_20();
2273 client_init_dispatch_13();
2275 client_init_dispatch_15();
2279 client_stop_mux(void)
2281 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
2282 unlink(options
.control_path
);
2284 * If we are in persist mode, or don't have a shell, signal that we
2285 * should close when all active channels are closed.
2287 if (options
.control_persist
|| no_shell_flag
) {
2289 setproctitle("[stopped mux]");
2293 /* client specific fatal cleanup */
2297 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
2298 leave_non_blocking();
2299 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
2300 unlink(options
.control_path
);
2301 ssh_kill_proxy_command();