1 /* $OpenBSD: clientloop.c,v 1.216 2010/01/09 05:04:24 djm 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"
103 #include "readconf.h"
104 #include "clientloop.h"
105 #include "sshconnect.h"
107 #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
;
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.
133 /* Force TTY allocation */
134 extern int force_tty_flag
;
137 * Flag to indicate that we have received a window change signal which has
138 * not yet been processed. This will cause a message indicating the new
139 * window size to be sent to the server a little later. This is volatile
140 * because this is updated in a signal handler.
142 static volatile sig_atomic_t received_window_change_signal
= 0;
143 static volatile sig_atomic_t received_signal
= 0;
145 /* Flag indicating whether the user's terminal is in non-blocking mode. */
146 static int in_non_blocking_mode
= 0;
148 /* Common data for the client loop code. */
149 static 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
= 0; /* In SSH2: login session closed. */
164 static void client_init_dispatch(void);
165 int session_ident
= -1;
167 int session_resumed
= 0;
169 /* Track escape per proto2 channel */
170 struct escape_filter_ctx
{
175 /* Context for channel confirmation replies */
176 struct channel_reply_ctx
{
177 const char *request_type
;
181 /* Global request success/failure callbacks */
182 struct global_confirm
{
183 TAILQ_ENTRY(global_confirm
) entry
;
184 global_confirm_cb
*cb
;
188 TAILQ_HEAD(global_confirms
, global_confirm
);
189 static struct global_confirms global_confirms
=
190 TAILQ_HEAD_INITIALIZER(global_confirms
);
195 void ssh_process_session2_setup(int, int, int, Buffer
*);
197 /* Restores stdin to blocking mode. */
200 leave_non_blocking(void)
202 if (in_non_blocking_mode
) {
203 unset_nonblock(fileno(stdin
));
204 in_non_blocking_mode
= 0;
208 /* Puts stdin terminal in non-blocking mode. */
211 enter_non_blocking(void)
213 in_non_blocking_mode
= 1;
214 set_nonblock(fileno(stdin
));
218 * Signal handler for the window change signal (SIGWINCH). This just sets a
219 * flag indicating that the window has changed.
223 window_change_handler(int sig
)
225 received_window_change_signal
= 1;
226 signal(SIGWINCH
, window_change_handler
);
230 * Signal handler for signals that cause the program to terminate. These
231 * signals must be trapped to restore terminal modes.
235 signal_handler(int sig
)
237 received_signal
= sig
;
242 * Returns current time in seconds from Jan 1, 1970 with the maximum
243 * available resolution.
247 get_current_time(void)
250 gettimeofday(&tv
, NULL
);
251 return (double) tv
.tv_sec
+ (double) tv
.tv_usec
/ 1000000.0;
254 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
256 client_x11_get_proto(const char *display
, const char *xauth_path
,
257 u_int trusted
, char **_proto
, char **_data
)
262 static char proto
[512], data
[512];
264 int got_data
= 0, generated
= 0, do_unlink
= 0, i
;
265 char *xauthdir
, *xauthfile
;
268 xauthdir
= xauthfile
= NULL
;
271 proto
[0] = data
[0] = '\0';
273 if (xauth_path
== NULL
||(stat(xauth_path
, &st
) == -1)) {
274 debug("No xauth program.");
276 if (display
== NULL
) {
277 debug("x11_get_proto: DISPLAY not set");
281 * Handle FamilyLocal case where $DISPLAY does
282 * not match an authorization entry. For this we
283 * just try "xauth list unix:displaynum.screennum".
284 * XXX: "localhost" match to determine FamilyLocal
287 if (strncmp(display
, "localhost:", 10) == 0) {
288 snprintf(xdisplay
, sizeof(xdisplay
), "unix:%s",
293 xauthdir
= xmalloc(MAXPATHLEN
);
294 xauthfile
= xmalloc(MAXPATHLEN
);
295 strlcpy(xauthdir
, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN
);
296 if (mkdtemp(xauthdir
) != NULL
) {
298 snprintf(xauthfile
, MAXPATHLEN
, "%s/xauthfile",
300 snprintf(cmd
, sizeof(cmd
),
301 "%s -f %s generate %s " SSH_X11_PROTO
302 " untrusted timeout 1200 2>" _PATH_DEVNULL
,
303 xauth_path
, xauthfile
, display
);
304 debug2("x11_get_proto: %s", cmd
);
305 if (system(cmd
) == 0)
311 * When in untrusted mode, we read the cookie only if it was
312 * successfully generated as an untrusted one in the step
315 if (trusted
|| generated
) {
316 snprintf(cmd
, sizeof(cmd
),
317 "%s %s%s list %s 2>" _PATH_DEVNULL
,
319 generated
? "-f " : "" ,
320 generated
? xauthfile
: "",
322 debug2("x11_get_proto: %s", cmd
);
324 if (f
&& fgets(line
, sizeof(line
), f
) &&
325 sscanf(line
, "%*s %511s %511s", proto
, data
) == 2)
330 error("Warning: untrusted X11 forwarding setup failed: "
331 "xauth key data not generated");
344 * If we didn't get authentication data, just make up some
345 * data. The forwarding code will check the validity of the
346 * response anyway, and substitute this data. The X11
347 * server, however, will ignore this fake data and use
348 * whatever authentication mechanisms it was using otherwise
349 * for the local connection.
354 logit("Warning: No xauth data; "
355 "using fake authentication data for X11 forwarding.");
356 strlcpy(proto
, SSH_X11_PROTO
, sizeof proto
);
357 for (i
= 0; i
< 16; i
++) {
360 snprintf(data
+ 2 * i
, sizeof data
- 2 * i
, "%02x",
368 * This is called when the interactive is entered. This checks if there is
369 * an EOF coming on stdin. We must check this explicitly, as select() does
370 * not appear to wake up when redirecting from /dev/null.
374 client_check_initial_eof_on_stdin(void)
380 * If standard input is to be "redirected from /dev/null", we simply
381 * mark that we have seen an EOF and send an EOF message to the
382 * server. Otherwise, we try to read a single character; it appears
383 * that for some files, such /dev/null, select() never wakes up for
384 * read for this descriptor, which means that we never get EOF. This
385 * way we will get the EOF if stdin comes from /dev/null or similar.
387 if (stdin_null_flag
) {
388 /* Fake EOF on stdin. */
389 debug("Sending eof.");
391 packet_start(SSH_CMSG_EOF
);
394 enter_non_blocking();
396 /* Check for immediate EOF on stdin. */
397 len
= read(fileno(stdin
), buf
, 1);
400 * EOF. Record that we have seen it and send
403 debug("Sending eof.");
405 packet_start(SSH_CMSG_EOF
);
407 } else if (len
> 0) {
409 * Got data. We must store the data in the buffer,
410 * and also process it as an escape character if
413 if ((u_char
) buf
[0] == escape_char1
)
416 buffer_append(&stdin_buffer
, buf
, 1);
418 leave_non_blocking();
424 * Make packets from buffered stdin data, and buffer them for sending to the
429 client_make_packets_from_stdin_data(void)
433 /* Send buffered stdin data to the server. */
434 while (buffer_len(&stdin_buffer
) > 0 &&
435 packet_not_very_much_data_to_write()) {
436 len
= buffer_len(&stdin_buffer
);
437 /* Keep the packets at reasonable size. */
438 if (len
> packet_get_maxsize())
439 len
= packet_get_maxsize();
440 packet_start(SSH_CMSG_STDIN_DATA
);
441 packet_put_string(buffer_ptr(&stdin_buffer
), len
);
443 buffer_consume(&stdin_buffer
, len
);
444 /* If we have a pending EOF, send it now. */
445 if (stdin_eof
&& buffer_len(&stdin_buffer
) == 0) {
446 packet_start(SSH_CMSG_EOF
);
453 * Checks if the client window has changed, and sends a packet about it to
454 * the server if so. The actual change is detected elsewhere (by a software
455 * interrupt on Unix); this just checks the flag and sends a message if
460 client_check_window_change(void)
464 if (! received_window_change_signal
)
467 received_window_change_signal
= 0;
469 debug2("client_check_window_change: changed");
472 channel_send_window_changes();
474 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
476 packet_start(SSH_CMSG_WINDOW_SIZE
);
477 packet_put_int((u_int
)ws
.ws_row
);
478 packet_put_int((u_int
)ws
.ws_col
);
479 packet_put_int((u_int
)ws
.ws_xpixel
);
480 packet_put_int((u_int
)ws
.ws_ypixel
);
486 client_global_request_reply(int type
, u_int32_t seq
, void *ctxt
)
488 struct global_confirm
*gc
;
490 if ((gc
= TAILQ_FIRST(&global_confirms
)) == NULL
)
493 gc
->cb(type
, seq
, gc
->ctx
);
494 if (--gc
->ref_count
<= 0) {
495 TAILQ_REMOVE(&global_confirms
, gc
, entry
);
496 bzero(gc
, sizeof(*gc
));
500 packet_set_alive_timeouts(0);
504 server_alive_check(void)
506 if (packet_inc_alive_timeouts() > options
.server_alive_count_max
) {
507 logit("Timeout, server not responding.");
510 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
511 packet_put_cstring("keepalive@openssh.com");
512 packet_put_char(1); /* boolean: want reply */
514 /* Insert an empty placeholder to maintain ordering */
515 client_register_global_confirm(NULL
, NULL
);
519 * Waits until the client can do something (some data becomes available on
520 * one of the file descriptors).
523 client_wait_until_can_do_something(fd_set
**readsetp
, fd_set
**writesetp
,
524 int *maxfdp
, u_int
*nallocp
, int rekeying
)
526 struct timeval tv
, *tvp
;
529 /* Add any selections by the channel mechanism. */
530 channel_prepare_select(readsetp
, writesetp
, maxfdp
, nallocp
, rekeying
);
533 /* Read from the connection, unless our buffers are full. */
534 if (buffer_len(&stdout_buffer
) < buffer_high
&&
535 buffer_len(&stderr_buffer
) < buffer_high
&&
536 channel_not_very_much_buffered_data())
537 FD_SET(connection_in
, *readsetp
);
539 * Read from stdin, unless we have seen EOF or have very much
540 * buffered data to send to the server.
542 if (!stdin_eof
&& packet_not_very_much_data_to_write())
543 FD_SET(fileno(stdin
), *readsetp
);
545 /* Select stdout/stderr if have data in buffer. */
546 if (buffer_len(&stdout_buffer
) > 0)
547 FD_SET(fileno(stdout
), *writesetp
);
548 if (buffer_len(&stderr_buffer
) > 0)
549 FD_SET(fileno(stderr
), *writesetp
);
551 /* channel_prepare_select could have closed the last channel */
552 if (session_closed
&& !channel_still_open() &&
553 !packet_have_data_to_write()) {
554 /* clear mask since we did not call select() */
555 memset(*readsetp
, 0, *nallocp
);
556 memset(*writesetp
, 0, *nallocp
);
559 FD_SET(connection_in
, *readsetp
);
563 /* Select server connection if have data to write to the server. */
564 if (packet_have_data_to_write())
565 FD_SET(connection_out
, *writesetp
);
567 if (muxserver_sock
!= -1)
568 FD_SET(muxserver_sock
, *readsetp
);
571 * Wait for something to happen. This will suspend the process until
572 * some selected descriptor can be read, written, or has some other
576 if (options
.server_alive_interval
== 0 || !compat20
)
579 tv
.tv_sec
= options
.server_alive_interval
;
583 ret
= select((*maxfdp
)+1, *readsetp
, *writesetp
, NULL
, tvp
);
588 * We have to clear the select masks, because we return.
589 * We have to return, because the mainloop checks for the flags
590 * set by the signal handlers.
592 memset(*readsetp
, 0, *nallocp
);
593 memset(*writesetp
, 0, *nallocp
);
597 /* Note: we might still have data in the buffers. */
598 snprintf(buf
, sizeof buf
, "select: %s\r\n", strerror(errno
));
599 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
602 server_alive_check();
606 client_suspend_self(Buffer
*bin
, Buffer
*bout
, Buffer
*berr
)
608 /* Flush stdout and stderr buffers. */
609 if (buffer_len(bout
) > 0)
610 atomicio(vwrite
, fileno(stdout
), buffer_ptr(bout
),
612 if (buffer_len(berr
) > 0)
613 atomicio(vwrite
, fileno(stderr
), buffer_ptr(berr
),
616 leave_raw_mode(force_tty_flag
);
619 * Free (and clear) the buffer to reduce the amount of data that gets
626 /* Send the suspend signal to the program itself. */
627 kill(getpid(), SIGTSTP
);
629 /* Reset window sizes in case they have changed */
630 received_window_change_signal
= 1;
632 /* OK, we have been continued by the user. Reinitialize buffers. */
637 enter_raw_mode(force_tty_flag
);
641 client_process_net_input(fd_set
*readset
)
644 char buf
[SSH_IOBUFSZ
];
647 * Read input from the server, and add any such data to the buffer of
648 * the packet subsystem.
650 if (FD_ISSET(connection_in
, readset
)) {
651 /* Read as much as possible. */
652 len
= roaming_read(connection_in
, buf
, sizeof(buf
), &cont
);
653 if (len
== 0 && cont
== 0) {
655 * Received EOF. The remote host has closed the
658 snprintf(buf
, sizeof buf
,
659 "Connection to %.300s closed by remote host.\r\n",
661 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
666 * There is a kernel bug on Solaris that causes select to
667 * sometimes wake up even though there is no data available.
670 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
675 * An error has encountered. Perhaps there is a
678 snprintf(buf
, sizeof buf
,
679 "Read from remote host %.300s: %.100s\r\n",
680 host
, strerror(errno
));
681 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
685 packet_process_incoming(buf
, len
);
690 client_status_confirm(int type
, Channel
*c
, void *ctx
)
692 struct channel_reply_ctx
*cr
= (struct channel_reply_ctx
*)ctx
;
696 /* XXX supress on mux _client_ quietmode */
697 tochan
= options
.log_level
>= SYSLOG_LEVEL_ERROR
&&
698 c
->ctl_fd
!= -1 && c
->extended_usage
== CHAN_EXTENDED_WRITE
;
700 if (type
== SSH2_MSG_CHANNEL_SUCCESS
) {
701 debug2("%s request accepted on channel %d",
702 cr
->request_type
, c
->self
);
703 } else if (type
== SSH2_MSG_CHANNEL_FAILURE
) {
705 snprintf(errmsg
, sizeof(errmsg
),
706 "%s request failed\r\n", cr
->request_type
);
708 snprintf(errmsg
, sizeof(errmsg
),
709 "%s request failed on channel %d",
710 cr
->request_type
, c
->self
);
712 /* If error occurred on primary session channel, then exit */
713 if (cr
->do_close
&& c
->self
== session_ident
)
715 /* If error occurred on mux client, append to their stderr */
717 buffer_append(&c
->extended
, errmsg
, strlen(errmsg
));
722 chan_write_failed(c
);
729 client_abandon_status_confirm(Channel
*c
, void *ctx
)
735 client_expect_confirm(int id
, const char *request
, int do_close
)
737 struct channel_reply_ctx
*cr
= xmalloc(sizeof(*cr
));
739 cr
->request_type
= request
;
740 cr
->do_close
= do_close
;
742 channel_register_status_confirm(id
, client_status_confirm
,
743 client_abandon_status_confirm
, cr
);
747 client_register_global_confirm(global_confirm_cb
*cb
, void *ctx
)
749 struct global_confirm
*gc
, *last_gc
;
751 /* Coalesce identical callbacks */
752 last_gc
= TAILQ_LAST(&global_confirms
, global_confirms
);
753 if (last_gc
&& last_gc
->cb
== cb
&& last_gc
->ctx
== ctx
) {
754 if (++last_gc
->ref_count
>= INT_MAX
)
755 fatal("%s: last_gc->ref_count = %d",
756 __func__
, last_gc
->ref_count
);
760 gc
= xmalloc(sizeof(*gc
));
764 TAILQ_INSERT_TAIL(&global_confirms
, gc
, entry
);
768 process_cmdline(void)
770 void (*handler
)(int);
771 char *s
, *cmd
, *cancel_host
;
773 int local
= 0, remote
= 0, dynamic
= 0;
777 bzero(&fwd
, sizeof(fwd
));
778 fwd
.listen_host
= fwd
.connect_host
= NULL
;
780 leave_raw_mode(force_tty_flag
);
781 handler
= signal(SIGINT
, SIG_IGN
);
782 cmd
= s
= read_passphrase("\r\nssh> ", RP_ECHO
);
788 s
++; /* Skip cmdline '-', if any */
792 if (*s
== 'h' || *s
== 'H' || *s
== '?') {
794 logit(" -L[bind_address:]port:host:hostport "
795 "Request local forward");
796 logit(" -R[bind_address:]port:host:hostport "
797 "Request remote forward");
798 logit(" -D[bind_address:]port "
799 "Request dynamic forward");
800 logit(" -KR[bind_address:]port "
801 "Cancel remote forward");
802 if (!options
.permit_local_command
)
805 "Execute local command");
809 if (*s
== '!' && options
.permit_local_command
) {
826 logit("Invalid command.");
830 if ((local
|| dynamic
) && delete) {
831 logit("Not supported.");
834 if (remote
&& delete && !compat20
) {
835 logit("Not supported for SSH protocol version 1.");
839 while (isspace(*++s
))
844 cancel_host
= hpdelim(&s
); /* may be NULL */
846 cancel_port
= a2port(s
);
847 cancel_host
= cleanhostname(cancel_host
);
849 cancel_port
= a2port(cancel_host
);
852 if (cancel_port
<= 0) {
853 logit("Bad forwarding close port");
856 channel_request_rforward_cancel(cancel_host
, cancel_port
);
858 if (!parse_forward(&fwd
, s
, dynamic
, remote
)) {
859 logit("Bad forwarding specification.");
862 if (local
|| dynamic
) {
863 if (channel_setup_local_fwd_listener(fwd
.listen_host
,
864 fwd
.listen_port
, fwd
.connect_host
,
865 fwd
.connect_port
, options
.gateway_ports
) < 0) {
866 logit("Port forwarding failed.");
870 if (channel_request_remote_forwarding(fwd
.listen_host
,
871 fwd
.listen_port
, fwd
.connect_host
,
872 fwd
.connect_port
) < 0) {
873 logit("Port forwarding failed.");
878 logit("Forwarding port.");
882 signal(SIGINT
, handler
);
883 enter_raw_mode(force_tty_flag
);
886 if (fwd
.listen_host
!= NULL
)
887 xfree(fwd
.listen_host
);
888 if (fwd
.connect_host
!= NULL
)
889 xfree(fwd
.connect_host
);
893 * Process the characters one by one, call with c==NULL for proto1 case.
896 process_escapes(Channel
*c
, Buffer
*bin
, Buffer
*bout
, Buffer
*berr
,
905 int *escape_pendingp
, escape_char
;
906 struct escape_filter_ctx
*efc
;
909 escape_pendingp
= &escape_pending1
;
910 escape_char
= escape_char1
;
912 if (c
->filter_ctx
== NULL
)
914 efc
= (struct escape_filter_ctx
*)c
->filter_ctx
;
915 escape_pendingp
= &efc
->escape_pending
;
916 escape_char
= efc
->escape_char
;
922 for (i
= 0; i
< (u_int
)len
; i
++) {
923 /* Get one character at a time. */
926 if (*escape_pendingp
) {
927 /* We have previously seen an escape character. */
928 /* Clear the flag now. */
929 *escape_pendingp
= 0;
931 /* Process the escaped character. */
934 /* Terminate the connection. */
935 snprintf(string
, sizeof string
, "%c.\r\n",
937 buffer_append(berr
, string
, strlen(string
));
939 if (c
&& c
->ctl_fd
!= -1) {
941 chan_write_failed(c
);
948 /* XXX support this for mux clients */
949 if (c
&& c
->ctl_fd
!= -1) {
951 snprintf(string
, sizeof string
,
952 "%c%c escape not available to "
953 "multiplexed sessions\r\n",
955 buffer_append(berr
, string
,
959 /* Suspend the program. Inform the user */
960 snprintf(string
, sizeof string
,
961 "%c^Z [suspend ssh]\r\n", escape_char
);
962 buffer_append(berr
, string
, strlen(string
));
964 /* Restore terminal modes and suspend. */
965 client_suspend_self(bin
, bout
, berr
);
967 /* We have been continued. */
972 snprintf(string
, sizeof string
,
973 "%cB\r\n", escape_char
);
974 buffer_append(berr
, string
,
976 channel_request_start(session_ident
,
978 packet_put_int(1000);
985 if (datafellows
& SSH_BUG_NOREKEY
)
986 logit("Server does not "
987 "support re-keying");
994 if (c
&& c
->ctl_fd
!= -1)
997 * Detach the program (continue to serve
998 * connections, but put in background and no
999 * more new connections).
1001 /* Restore tty modes. */
1002 leave_raw_mode(force_tty_flag
);
1004 /* Stop listening for new connections. */
1005 channel_stop_listening();
1007 snprintf(string
, sizeof string
,
1008 "%c& [backgrounded]\n", escape_char
);
1009 buffer_append(berr
, string
, strlen(string
));
1011 /* Fork into background. */
1014 error("fork: %.100s", strerror(errno
));
1017 if (pid
!= 0) { /* This is the parent. */
1018 /* The parent just exits. */
1021 /* The child continues serving connections. */
1023 buffer_append(bin
, "\004", 1);
1024 /* fake EOF on stdin */
1026 } else if (!stdin_eof
) {
1028 * Sending SSH_CMSG_EOF alone does not
1029 * always appear to be enough. So we
1030 * try to send an EOF character first.
1032 packet_start(SSH_CMSG_STDIN_DATA
);
1033 packet_put_string("\004", 1);
1037 if (buffer_len(bin
) == 0) {
1038 packet_start(SSH_CMSG_EOF
);
1045 if (c
&& c
->ctl_fd
!= -1) {
1046 snprintf(string
, sizeof string
,
1048 Supported escape sequences:\r\n\
1049 %c. - terminate session\r\n\
1050 %cB - send a BREAK to the remote system\r\n\
1051 %cR - Request rekey (SSH protocol 2 only)\r\n\
1052 %c# - list forwarded connections\r\n\
1053 %c? - this message\r\n\
1054 %c%c - send the escape character by typing it twice\r\n\
1055 (Note that escapes are only recognized immediately after newline.)\r\n",
1056 escape_char
, escape_char
,
1057 escape_char
, escape_char
,
1058 escape_char
, escape_char
,
1059 escape_char
, escape_char
);
1061 snprintf(string
, sizeof string
,
1063 Supported escape sequences:\r\n\
1064 %c. - terminate connection (and any multiplexed sessions)\r\n\
1065 %cB - send a BREAK to the remote system\r\n\
1066 %cC - open a command line\r\n\
1067 %cR - Request rekey (SSH protocol 2 only)\r\n\
1068 %c^Z - suspend ssh\r\n\
1069 %c# - list forwarded connections\r\n\
1070 %c& - background ssh (when waiting for connections to terminate)\r\n\
1071 %c? - this message\r\n\
1072 %c%c - send the escape character by typing it twice\r\n\
1073 (Note that escapes are only recognized immediately after newline.)\r\n",
1074 escape_char
, escape_char
,
1075 escape_char
, escape_char
,
1076 escape_char
, escape_char
,
1077 escape_char
, escape_char
,
1078 escape_char
, escape_char
,
1081 buffer_append(berr
, string
, strlen(string
));
1085 snprintf(string
, sizeof string
, "%c#\r\n",
1087 buffer_append(berr
, string
, strlen(string
));
1088 s
= channel_open_message();
1089 buffer_append(berr
, s
, strlen(s
));
1094 if (c
&& c
->ctl_fd
!= -1)
1100 if (ch
!= escape_char
) {
1101 buffer_put_char(bin
, escape_char
);
1104 /* Escaped characters fall through here */
1109 * The previous character was not an escape char.
1110 * Check if this is an escape.
1112 if (last_was_cr
&& ch
== escape_char
) {
1114 * It is. Set the flag and continue to
1117 *escape_pendingp
= 1;
1123 * Normal character. Record whether it was a newline,
1124 * and append it to the buffer.
1126 last_was_cr
= (ch
== '\r' || ch
== '\n');
1127 buffer_put_char(bin
, ch
);
1134 client_process_input(fd_set
*readset
)
1137 char buf
[SSH_IOBUFSZ
];
1139 /* Read input from stdin. */
1140 if (FD_ISSET(fileno(stdin
), readset
)) {
1141 /* Read as much as possible. */
1142 len
= read(fileno(stdin
), buf
, sizeof(buf
));
1144 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
1145 return; /* we'll try again later */
1148 * Received EOF or error. They are treated
1149 * similarly, except that an error message is printed
1150 * if it was an error condition.
1153 snprintf(buf
, sizeof buf
, "read: %.100s\r\n",
1155 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1157 /* Mark that we have seen EOF. */
1160 * Send an EOF message to the server unless there is
1161 * data in the buffer. If there is data in the
1162 * buffer, no message will be sent now. Code
1163 * elsewhere will send the EOF when the buffer
1164 * becomes empty if stdin_eof is set.
1166 if (buffer_len(&stdin_buffer
) == 0) {
1167 packet_start(SSH_CMSG_EOF
);
1170 } else if (escape_char1
== SSH_ESCAPECHAR_NONE
) {
1172 * Normal successful read, and no escape character.
1173 * Just append the data to buffer.
1175 buffer_append(&stdin_buffer
, buf
, len
);
1178 * Normal, successful read. But we have an escape
1179 * character and have to process the characters one
1182 if (process_escapes(NULL
, &stdin_buffer
,
1183 &stdout_buffer
, &stderr_buffer
, buf
, len
) == -1)
1190 client_process_output(fd_set
*writeset
)
1195 /* Write buffered output to stdout. */
1196 if (FD_ISSET(fileno(stdout
), writeset
)) {
1197 /* Write as much data as possible. */
1198 len
= write(fileno(stdout
), buffer_ptr(&stdout_buffer
),
1199 buffer_len(&stdout_buffer
));
1201 if (errno
== EINTR
|| errno
== EAGAIN
||
1202 errno
== EWOULDBLOCK
)
1206 * An error or EOF was encountered. Put an
1207 * error message to stderr buffer.
1209 snprintf(buf
, sizeof buf
,
1210 "write stdout: %.50s\r\n", strerror(errno
));
1211 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1216 /* Consume printed data from the buffer. */
1217 buffer_consume(&stdout_buffer
, len
);
1219 /* Write buffered output to stderr. */
1220 if (FD_ISSET(fileno(stderr
), writeset
)) {
1221 /* Write as much data as possible. */
1222 len
= write(fileno(stderr
), buffer_ptr(&stderr_buffer
),
1223 buffer_len(&stderr_buffer
));
1225 if (errno
== EINTR
|| errno
== EAGAIN
||
1226 errno
== EWOULDBLOCK
)
1230 * EOF or error, but can't even print
1237 /* Consume printed characters from the buffer. */
1238 buffer_consume(&stderr_buffer
, len
);
1243 * Get packets from the connection input buffer, and process them as long as
1244 * there are packets available.
1246 * Any unknown packets received during the actual
1247 * session cause the session to terminate. This is
1248 * intended to make debugging easier since no
1249 * confirmations are sent. Any compatible protocol
1250 * extensions must be negotiated during the
1251 * preparatory phase.
1255 client_process_buffered_input_packets(void)
1257 dispatch_run(DISPATCH_NONBLOCK
, &quit_pending
,
1258 compat20
? xxx_kex
: NULL
);
1261 /* scan buf[] for '~' before sending data to the peer */
1263 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1265 client_new_escape_filter_ctx(int escape_char
)
1267 struct escape_filter_ctx
*ret
;
1269 ret
= xmalloc(sizeof(*ret
));
1270 ret
->escape_pending
= 0;
1271 ret
->escape_char
= escape_char
;
1275 /* Free the escape filter context on channel free */
1277 client_filter_cleanup(int cid
, void *ctx
)
1283 client_simple_escape_filter(Channel
*c
, char *buf
, int len
)
1285 if (c
->extended_usage
!= CHAN_EXTENDED_WRITE
)
1288 return process_escapes(c
, &c
->input
, &c
->output
, &c
->extended
,
1293 client_channel_closed(int id
, void *arg
)
1295 channel_cancel_cleanup(id
);
1297 leave_raw_mode(force_tty_flag
);
1301 * Implements the interactive session with the server. This is called after
1302 * the user has been authenticated, and a command has been started on the
1303 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1304 * used as an escape character for terminating or suspending the session.
1308 client_loop(int have_pty
, int escape_char_arg
, int ssh2_chan_id
)
1310 fd_set
*readset
= NULL
, *writeset
= NULL
;
1311 double start_time
, total_time
;
1312 int max_fd
= 0, max_fd2
= 0, len
, rekeying
= 0;
1313 u_int64_t ibytes
, obytes
;
1317 debug("Entering interactive session.");
1319 start_time
= get_current_time();
1321 /* Initialize variables. */
1322 escape_pending1
= 0;
1326 buffer_high
= 64 * 1024;
1327 connection_in
= packet_get_connection_in();
1328 connection_out
= packet_get_connection_out();
1329 max_fd
= MAX(connection_in
, connection_out
);
1330 if (muxserver_sock
!= -1)
1331 max_fd
= MAX(max_fd
, muxserver_sock
);
1334 /* enable nonblocking unless tty */
1335 if (!isatty(fileno(stdin
)))
1336 set_nonblock(fileno(stdin
));
1337 if (!isatty(fileno(stdout
)))
1338 set_nonblock(fileno(stdout
));
1339 if (!isatty(fileno(stderr
)))
1340 set_nonblock(fileno(stderr
));
1341 max_fd
= MAX(max_fd
, fileno(stdin
));
1342 max_fd
= MAX(max_fd
, fileno(stdout
));
1343 max_fd
= MAX(max_fd
, fileno(stderr
));
1346 escape_char1
= escape_char_arg
;
1348 /* Initialize buffers. */
1349 buffer_init(&stdin_buffer
);
1350 buffer_init(&stdout_buffer
);
1351 buffer_init(&stderr_buffer
);
1353 client_init_dispatch();
1356 * Set signal handlers, (e.g. to restore non-blocking mode)
1357 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1359 if (signal(SIGHUP
, SIG_IGN
) != SIG_IGN
)
1360 signal(SIGHUP
, signal_handler
);
1361 if (signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
1362 signal(SIGINT
, signal_handler
);
1363 if (signal(SIGQUIT
, SIG_IGN
) != SIG_IGN
)
1364 signal(SIGQUIT
, signal_handler
);
1365 if (signal(SIGTERM
, SIG_IGN
) != SIG_IGN
)
1366 signal(SIGTERM
, signal_handler
);
1367 signal(SIGWINCH
, window_change_handler
);
1370 enter_raw_mode(force_tty_flag
);
1373 session_ident
= ssh2_chan_id
;
1374 if (escape_char_arg
!= SSH_ESCAPECHAR_NONE
)
1375 channel_register_filter(session_ident
,
1376 client_simple_escape_filter
, NULL
,
1377 client_filter_cleanup
,
1378 client_new_escape_filter_ctx(escape_char_arg
));
1379 if (session_ident
!= -1)
1380 channel_register_cleanup(session_ident
,
1381 client_channel_closed
, 0);
1383 /* Check if we should immediately send eof on stdin. */
1384 client_check_initial_eof_on_stdin();
1387 /* Main loop of the client for the interactive session mode. */
1388 while (!quit_pending
) {
1390 /* Process buffered packets sent by the server. */
1391 client_process_buffered_input_packets();
1393 if (compat20
&& session_closed
&& !channel_still_open())
1396 rekeying
= (xxx_kex
!= NULL
&& !xxx_kex
->done
);
1399 debug("rekeying in progress");
1402 * Make packets of buffered stdin data, and buffer
1403 * them for sending to the server.
1406 client_make_packets_from_stdin_data();
1409 * Make packets from buffered channel data, and
1410 * enqueue them for sending to the server.
1412 if (packet_not_very_much_data_to_write())
1413 channel_output_poll();
1416 * Check if the window size has changed, and buffer a
1417 * message about it to the server if so.
1419 client_check_window_change();
1425 * Wait until we have something to do (something becomes
1426 * available on one of the descriptors).
1429 client_wait_until_can_do_something(&readset
, &writeset
,
1430 &max_fd2
, &nalloc
, rekeying
);
1435 /* Do channel operations unless rekeying in progress. */
1437 channel_after_select(readset
, writeset
);
1438 if (need_rekeying
|| packet_need_rekeying()) {
1439 debug("need rekeying");
1441 kex_send_kexinit(xxx_kex
);
1446 /* Buffer input from the connection. */
1447 client_process_net_input(readset
);
1449 /* Accept control connections. */
1450 if (muxserver_sock
!= -1 &&FD_ISSET(muxserver_sock
, readset
)) {
1451 if (muxserver_accept_control())
1459 /* Buffer data from stdin */
1460 client_process_input(readset
);
1462 * Process output to stdout and stderr. Output to
1463 * the connection is processed elsewhere (above).
1465 client_process_output(writeset
);
1468 if (session_resumed
) {
1469 connection_in
= packet_get_connection_in();
1470 connection_out
= packet_get_connection_out();
1471 max_fd
= MAX(max_fd
, connection_out
);
1472 max_fd
= MAX(max_fd
, connection_in
);
1473 session_resumed
= 0;
1477 * Send as much buffered packet data as possible to the
1480 if (FD_ISSET(connection_out
, writeset
))
1481 packet_write_poll();
1488 /* Terminate the session. */
1490 /* Stop watching for window change. */
1491 signal(SIGWINCH
, SIG_DFL
);
1494 packet_start(SSH2_MSG_DISCONNECT
);
1495 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION
);
1496 packet_put_cstring("disconnected by user");
1498 packet_write_wait();
1504 leave_raw_mode(force_tty_flag
);
1506 /* restore blocking io */
1507 if (!isatty(fileno(stdin
)))
1508 unset_nonblock(fileno(stdin
));
1509 if (!isatty(fileno(stdout
)))
1510 unset_nonblock(fileno(stdout
));
1511 if (!isatty(fileno(stderr
)))
1512 unset_nonblock(fileno(stderr
));
1515 * If there was no shell or command requested, there will be no remote
1516 * exit status to be returned. In that case, clear error code if the
1517 * connection was deliberately terminated at this end.
1519 if (no_shell_flag
&& received_signal
== SIGTERM
) {
1520 received_signal
= 0;
1524 if (received_signal
)
1525 fatal("Killed by signal %d.", (int) received_signal
);
1528 * In interactive mode (with pseudo tty) display a message indicating
1529 * that the connection has been closed.
1531 if (have_pty
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
) {
1532 snprintf(buf
, sizeof buf
,
1533 "Connection to %.64s closed.\r\n", host
);
1534 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1537 /* Output any buffered data for stdout. */
1538 while (buffer_len(&stdout_buffer
) > 0) {
1539 len
= write(fileno(stdout
), buffer_ptr(&stdout_buffer
),
1540 buffer_len(&stdout_buffer
));
1542 error("Write failed flushing stdout buffer.");
1545 buffer_consume(&stdout_buffer
, len
);
1548 /* Output any buffered data for stderr. */
1549 while (buffer_len(&stderr_buffer
) > 0) {
1550 len
= write(fileno(stderr
), buffer_ptr(&stderr_buffer
),
1551 buffer_len(&stderr_buffer
));
1553 error("Write failed flushing stderr buffer.");
1556 buffer_consume(&stderr_buffer
, len
);
1559 /* Clear and free any buffers. */
1560 memset(buf
, 0, sizeof(buf
));
1561 buffer_free(&stdin_buffer
);
1562 buffer_free(&stdout_buffer
);
1563 buffer_free(&stderr_buffer
);
1565 /* Report bytes transferred, and transfer rates. */
1566 total_time
= get_current_time() - start_time
;
1567 packet_get_state(MODE_IN
, NULL
, NULL
, NULL
, &ibytes
);
1568 packet_get_state(MODE_OUT
, NULL
, NULL
, NULL
, &obytes
);
1569 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1570 obytes
, ibytes
, total_time
);
1572 verbose("Bytes per second: sent %.1f, received %.1f",
1573 obytes
/ total_time
, ibytes
/ total_time
);
1574 /* Return the exit status of the program. */
1575 debug("Exit status %d", exit_status
);
1582 client_input_stdout_data(int type
, u_int32_t seq
, void *ctxt
)
1585 char *data
= packet_get_string(&data_len
);
1587 buffer_append(&stdout_buffer
, data
, data_len
);
1588 memset(data
, 0, data_len
);
1592 client_input_stderr_data(int type
, u_int32_t seq
, void *ctxt
)
1595 char *data
= packet_get_string(&data_len
);
1597 buffer_append(&stderr_buffer
, data
, data_len
);
1598 memset(data
, 0, data_len
);
1602 client_input_exit_status(int type
, u_int32_t seq
, void *ctxt
)
1604 exit_status
= packet_get_int();
1606 /* Acknowledge the exit. */
1607 packet_start(SSH_CMSG_EXIT_CONFIRMATION
);
1610 * Must wait for packet to be sent since we are
1613 packet_write_wait();
1614 /* Flag that we want to exit. */
1618 client_input_agent_open(int type
, u_int32_t seq
, void *ctxt
)
1621 int remote_id
, sock
;
1623 /* Read the remote channel number from the message. */
1624 remote_id
= packet_get_int();
1628 * Get a connection to the local authentication agent (this may again
1631 sock
= ssh_get_authentication_socket();
1634 * If we could not connect the agent, send an error message back to
1635 * the server. This should never happen unless the agent dies,
1636 * because authentication forwarding is only enabled if we have an
1640 c
= channel_new("", SSH_CHANNEL_OPEN
, sock
, sock
,
1641 -1, 0, 0, 0, "authentication agent connection", 1);
1642 c
->remote_id
= remote_id
;
1646 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1647 packet_put_int(remote_id
);
1649 /* Send a confirmation to the remote host. */
1650 debug("Forwarding authentication connection.");
1651 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1652 packet_put_int(remote_id
);
1653 packet_put_int(c
->self
);
1659 client_request_forwarded_tcpip(const char *request_type
, int rchan
)
1662 char *listen_address
, *originator_address
;
1663 u_short listen_port
, originator_port
;
1665 /* Get rest of the packet */
1666 listen_address
= packet_get_string(NULL
);
1667 listen_port
= packet_get_int();
1668 originator_address
= packet_get_string(NULL
);
1669 originator_port
= packet_get_int();
1672 debug("client_request_forwarded_tcpip: listen %s port %d, "
1673 "originator %s port %d", listen_address
, listen_port
,
1674 originator_address
, originator_port
);
1676 c
= channel_connect_by_listen_address(listen_port
,
1677 "forwarded-tcpip", originator_address
);
1679 xfree(originator_address
);
1680 xfree(listen_address
);
1685 client_request_x11(const char *request_type
, int rchan
)
1689 u_short originator_port
;
1692 if (!options
.forward_x11
) {
1693 error("Warning: ssh server tried X11 forwarding.");
1694 error("Warning: this is probably a break-in attempt by a "
1695 "malicious server.");
1698 originator
= packet_get_string(NULL
);
1699 if (datafellows
& SSH_BUG_X11FWD
) {
1700 debug2("buggy server: x11 request w/o originator_port");
1701 originator_port
= 0;
1703 originator_port
= packet_get_int();
1706 /* XXX check permission */
1707 debug("client_request_x11: request from %s %d", originator
,
1710 sock
= x11_connect_display();
1713 c
= channel_new("x11",
1714 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1,
1715 CHAN_TCP_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
, 0, "x11", 1);
1721 client_request_agent(const char *request_type
, int rchan
)
1726 if (!options
.forward_agent
) {
1727 error("Warning: ssh server tried agent forwarding.");
1728 error("Warning: this is probably a break-in attempt by a "
1729 "malicious server.");
1732 sock
= ssh_get_authentication_socket();
1735 c
= channel_new("authentication agent connection",
1736 SSH_CHANNEL_OPEN
, sock
, sock
, -1,
1737 CHAN_X11_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0,
1738 "authentication agent connection", 1);
1744 client_request_tun_fwd(int tun_mode
, int local_tun
, int remote_tun
)
1749 if (tun_mode
== SSH_TUNMODE_NO
)
1753 error("Tunnel forwarding is not supported for protocol 1");
1757 debug("Requesting tun unit %d in mode %d", local_tun
, tun_mode
);
1759 /* Open local tunnel device */
1760 if ((fd
= tun_open(local_tun
, tun_mode
)) == -1) {
1761 error("Tunnel device open failed.");
1765 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1766 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0, "tun", 1);
1769 #if defined(SSH_TUN_FILTER)
1770 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1771 channel_register_filter(c
->self
, sys_tun_infilter
,
1772 sys_tun_outfilter
, NULL
, NULL
);
1775 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1776 packet_put_cstring("tun@openssh.com");
1777 packet_put_int(c
->self
);
1778 packet_put_int(c
->local_window_max
);
1779 packet_put_int(c
->local_maxpacket
);
1780 packet_put_int(tun_mode
);
1781 packet_put_int(remote_tun
);
1787 /* XXXX move to generic input handler */
1789 client_input_channel_open(int type
, u_int32_t seq
, void *ctxt
)
1794 u_int rmaxpack
, rwindow
, len
;
1796 ctype
= packet_get_string(&len
);
1797 rchan
= packet_get_int();
1798 rwindow
= packet_get_int();
1799 rmaxpack
= packet_get_int();
1801 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1802 ctype
, rchan
, rwindow
, rmaxpack
);
1804 if (strcmp(ctype
, "forwarded-tcpip") == 0) {
1805 c
= client_request_forwarded_tcpip(ctype
, rchan
);
1806 } else if (strcmp(ctype
, "x11") == 0) {
1807 c
= client_request_x11(ctype
, rchan
);
1808 } else if (strcmp(ctype
, "auth-agent@openssh.com") == 0) {
1809 c
= client_request_agent(ctype
, rchan
);
1811 /* XXX duplicate : */
1813 debug("confirm %s", ctype
);
1814 c
->remote_id
= rchan
;
1815 c
->remote_window
= rwindow
;
1816 c
->remote_maxpacket
= rmaxpack
;
1817 if (c
->type
!= SSH_CHANNEL_CONNECTING
) {
1818 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1819 packet_put_int(c
->remote_id
);
1820 packet_put_int(c
->self
);
1821 packet_put_int(c
->local_window
);
1822 packet_put_int(c
->local_maxpacket
);
1826 debug("failure %s", ctype
);
1827 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1828 packet_put_int(rchan
);
1829 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
);
1830 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1831 packet_put_cstring("open failed");
1832 packet_put_cstring("");
1839 client_input_channel_req(int type
, u_int32_t seq
, void *ctxt
)
1842 int exitval
, id
, reply
, success
= 0;
1845 id
= packet_get_int();
1846 rtype
= packet_get_string(NULL
);
1847 reply
= packet_get_char();
1849 debug("client_input_channel_req: channel %d rtype %s reply %d",
1853 error("client_input_channel_req: request for channel -1");
1854 } else if ((c
= channel_lookup(id
)) == NULL
) {
1855 error("client_input_channel_req: channel %d: "
1856 "unknown channel", id
);
1857 } else if (strcmp(rtype
, "eow@openssh.com") == 0) {
1860 } else if (strcmp(rtype
, "exit-status") == 0) {
1861 exitval
= packet_get_int();
1862 if (c
->ctl_fd
!= -1) {
1863 /* Dispatch to mux client */
1864 atomicio(vwrite
, c
->ctl_fd
, &exitval
, sizeof(exitval
));
1866 } else if (id
== session_ident
) {
1867 /* Record exit value of local session */
1869 exit_status
= exitval
;
1871 error("client_input_channel_req: unexpected channel %d",
1877 packet_start(success
?
1878 SSH2_MSG_CHANNEL_SUCCESS
: SSH2_MSG_CHANNEL_FAILURE
);
1879 packet_put_int(c
->remote_id
);
1885 client_input_global_request(int type
, u_int32_t seq
, void *ctxt
)
1891 rtype
= packet_get_string(NULL
);
1892 want_reply
= packet_get_char();
1893 debug("client_input_global_request: rtype %s want_reply %d",
1896 packet_start(success
?
1897 SSH2_MSG_REQUEST_SUCCESS
: SSH2_MSG_REQUEST_FAILURE
);
1899 packet_write_wait();
1905 client_session2_setup(int id
, int want_tty
, int want_subsystem
,
1906 const char *term
, struct termios
*tiop
, int in_fd
, Buffer
*cmd
, char **env
)
1911 debug2("%s: id %d", __func__
, id
);
1913 if ((c
= channel_lookup(id
)) == NULL
)
1914 fatal("client_session2_setup: channel %d: unknown channel", id
);
1919 /* Store window size in the packet. */
1920 if (ioctl(in_fd
, TIOCGWINSZ
, &ws
) < 0)
1921 memset(&ws
, 0, sizeof(ws
));
1923 channel_request_start(id
, "pty-req", 1);
1924 client_expect_confirm(id
, "PTY allocation", 0);
1925 packet_put_cstring(term
!= NULL
? term
: "");
1926 packet_put_int((u_int
)ws
.ws_col
);
1927 packet_put_int((u_int
)ws
.ws_row
);
1928 packet_put_int((u_int
)ws
.ws_xpixel
);
1929 packet_put_int((u_int
)ws
.ws_ypixel
);
1931 tiop
= get_saved_tio();
1932 tty_make_modes(-1, tiop
);
1934 /* XXX wait for reply */
1938 /* Transfer any environment variables from client to server */
1939 if (options
.num_send_env
!= 0 && env
!= NULL
) {
1943 debug("Sending environment.");
1944 for (i
= 0; env
[i
] != NULL
; i
++) {
1946 name
= xstrdup(env
[i
]);
1947 if ((val
= strchr(name
, '=')) == NULL
) {
1954 for (j
= 0; j
< options
.num_send_env
; j
++) {
1955 if (match_pattern(name
, options
.send_env
[j
])) {
1961 debug3("Ignored env %s", name
);
1966 debug("Sending env %s = %s", name
, val
);
1967 channel_request_start(id
, "env", 0);
1968 packet_put_cstring(name
);
1969 packet_put_cstring(val
);
1975 len
= buffer_len(cmd
);
1979 if (want_subsystem
) {
1980 debug("Sending subsystem: %.*s",
1981 len
, (u_char
*)buffer_ptr(cmd
));
1982 channel_request_start(id
, "subsystem", 1);
1983 client_expect_confirm(id
, "subsystem", 1);
1985 debug("Sending command: %.*s",
1986 len
, (u_char
*)buffer_ptr(cmd
));
1987 channel_request_start(id
, "exec", 1);
1988 client_expect_confirm(id
, "exec", 1);
1990 packet_put_string(buffer_ptr(cmd
), buffer_len(cmd
));
1993 channel_request_start(id
, "shell", 1);
1994 client_expect_confirm(id
, "shell", 1);
2000 client_init_dispatch_20(void)
2002 dispatch_init(&dispatch_protocol_error
);
2004 dispatch_set(SSH2_MSG_CHANNEL_CLOSE
, &channel_input_oclose
);
2005 dispatch_set(SSH2_MSG_CHANNEL_DATA
, &channel_input_data
);
2006 dispatch_set(SSH2_MSG_CHANNEL_EOF
, &channel_input_ieof
);
2007 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA
, &channel_input_extended_data
);
2008 dispatch_set(SSH2_MSG_CHANNEL_OPEN
, &client_input_channel_open
);
2009 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2010 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2011 dispatch_set(SSH2_MSG_CHANNEL_REQUEST
, &client_input_channel_req
);
2012 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST
, &channel_input_window_adjust
);
2013 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS
, &channel_input_status_confirm
);
2014 dispatch_set(SSH2_MSG_CHANNEL_FAILURE
, &channel_input_status_confirm
);
2015 dispatch_set(SSH2_MSG_GLOBAL_REQUEST
, &client_input_global_request
);
2018 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
2020 /* global request reply messages */
2021 dispatch_set(SSH2_MSG_REQUEST_FAILURE
, &client_global_request_reply
);
2022 dispatch_set(SSH2_MSG_REQUEST_SUCCESS
, &client_global_request_reply
);
2026 client_init_dispatch_13(void)
2028 dispatch_init(NULL
);
2029 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_close
);
2030 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, &channel_input_close_confirmation
);
2031 dispatch_set(SSH_MSG_CHANNEL_DATA
, &channel_input_data
);
2032 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2033 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2034 dispatch_set(SSH_MSG_PORT_OPEN
, &channel_input_port_open
);
2035 dispatch_set(SSH_SMSG_EXITSTATUS
, &client_input_exit_status
);
2036 dispatch_set(SSH_SMSG_STDERR_DATA
, &client_input_stderr_data
);
2037 dispatch_set(SSH_SMSG_STDOUT_DATA
, &client_input_stdout_data
);
2039 dispatch_set(SSH_SMSG_AGENT_OPEN
, options
.forward_agent
?
2040 &client_input_agent_open
: &deny_input_open
);
2041 dispatch_set(SSH_SMSG_X11_OPEN
, options
.forward_x11
?
2042 &x11_input_open
: &deny_input_open
);
2046 client_init_dispatch_15(void)
2048 client_init_dispatch_13();
2049 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_ieof
);
2050 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, & channel_input_oclose
);
2054 client_init_dispatch(void)
2057 client_init_dispatch_20();
2059 client_init_dispatch_13();
2061 client_init_dispatch_15();
2064 /* client specific fatal cleanup */
2068 leave_raw_mode(force_tty_flag
);
2069 leave_non_blocking();
2070 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
2071 unlink(options
.control_path
);