1 /* $OpenBSD: clientloop.c,v 1.231 2011/01/16 12:05:59 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * The main loop for the interactive session (client side).
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * SSH2 support added by Markus Friedl.
40 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
51 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
52 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
53 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
54 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
55 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
60 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65 #include <sys/types.h>
66 #include <sys/ioctl.h>
67 #include <sys/param.h>
68 #ifdef HAVE_SYS_STAT_H
69 # include <sys/stat.h>
71 #ifdef HAVE_SYS_TIME_H
72 # include <sys/time.h>
74 #include <sys/socket.h>
90 #include "openbsd-compat/sys-queue.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
116 extern Options options;
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
125 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
128 * Name of the host we are connecting to. This is the name given on the
129 * command line, or the HostName specified for the user-supplied name in a
130 * configuration file.
134 /* Force TTY allocation */
135 extern int force_tty_flag;
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
152 /* Common data for the client loop code. */
153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
154 static int escape_char1; /* Escape character. (proto1 only) */
155 static int escape_pending1; /* Last character was an escape (proto1 only) */
156 static int last_was_cr; /* Last character was a newline. */
157 static int exit_status; /* Used to store the command exit status. */
158 static int stdin_eof; /* EOF has been encountered on stderr. */
159 static Buffer stdin_buffer; /* Buffer for stdin data. */
160 static Buffer stdout_buffer; /* Buffer for stdout data. */
161 static Buffer stderr_buffer; /* Buffer for stderr data. */
162 static u_int buffer_high; /* Soft max buffer size. */
163 static int connection_in; /* Connection to server (input). */
164 static int connection_out; /* Connection to server (output). */
165 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
166 static int session_closed; /* In SSH2: login session closed. */
167 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
169 static void client_init_dispatch(void);
170 int session_ident = -1;
172 int session_resumed = 0;
174 /* Track escape per proto2 channel */
175 struct escape_filter_ctx {
180 /* Context for channel confirmation replies */
181 struct channel_reply_ctx {
182 const char *request_type;
186 /* Global request success/failure callbacks */
187 struct global_confirm {
188 TAILQ_ENTRY(global_confirm) entry;
189 global_confirm_cb *cb;
193 TAILQ_HEAD(global_confirms, global_confirm);
194 static struct global_confirms global_confirms =
195 TAILQ_HEAD_INITIALIZER(global_confirms);
200 void ssh_process_session2_setup(int, int, int, Buffer *);
202 /* Restores stdin to blocking mode. */
205 leave_non_blocking(void)
207 if (in_non_blocking_mode) {
208 unset_nonblock(fileno(stdin));
209 in_non_blocking_mode = 0;
213 /* Puts stdin terminal in non-blocking mode. */
216 enter_non_blocking(void)
218 in_non_blocking_mode = 1;
219 set_nonblock(fileno(stdin));
223 * Signal handler for the window change signal (SIGWINCH). This just sets a
224 * flag indicating that the window has changed.
228 window_change_handler(int sig)
230 received_window_change_signal = 1;
231 signal(SIGWINCH, window_change_handler);
235 * Signal handler for signals that cause the program to terminate. These
236 * signals must be trapped to restore terminal modes.
240 signal_handler(int sig)
242 received_signal = sig;
247 * Returns current time in seconds from Jan 1, 1970 with the maximum
248 * available resolution.
252 get_current_time(void)
255 gettimeofday(&tv, NULL);
256 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
260 * Sets control_persist_exit_time to the absolute time when the
261 * backgrounded control master should exit due to expiry of the
262 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
263 * control master process, or if there is no ControlPersist timeout.
266 set_control_persist_exit_time(void)
268 if (muxserver_sock == -1 || !options.control_persist
269 || options.control_persist_timeout == 0)
270 /* not using a ControlPersist timeout */
271 control_persist_exit_time = 0;
272 else if (channel_still_open()) {
273 /* some client connections are still open */
274 if (control_persist_exit_time > 0)
275 debug2("%s: cancel scheduled exit", __func__);
276 control_persist_exit_time = 0;
277 } else if (control_persist_exit_time <= 0) {
278 /* a client connection has recently closed */
279 control_persist_exit_time = time(NULL) +
280 (time_t)options.control_persist_timeout;
281 debug2("%s: schedule exit in %d seconds", __func__,
282 options.control_persist_timeout);
284 /* else we are already counting down to the timeout */
287 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
289 client_x11_get_proto(const char *display, const char *xauth_path,
290 u_int trusted, u_int timeout, char **_proto, char **_data)
295 static char proto[512], data[512];
297 int got_data = 0, generated = 0, do_unlink = 0, i;
298 char *xauthdir, *xauthfile;
302 xauthdir = xauthfile = NULL;
305 proto[0] = data[0] = '\0';
307 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
308 debug("No xauth program.");
310 if (display == NULL) {
311 debug("x11_get_proto: DISPLAY not set");
315 * Handle FamilyLocal case where $DISPLAY does
316 * not match an authorization entry. For this we
317 * just try "xauth list unix:displaynum.screennum".
318 * XXX: "localhost" match to determine FamilyLocal
321 if (strncmp(display, "localhost:", 10) == 0) {
322 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
327 xauthdir = xmalloc(MAXPATHLEN);
328 xauthfile = xmalloc(MAXPATHLEN);
329 mktemp_proto(xauthdir, MAXPATHLEN);
330 if (mkdtemp(xauthdir) != NULL) {
332 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
334 snprintf(cmd, sizeof(cmd),
335 "%s -f %s generate %s " SSH_X11_PROTO
336 " untrusted timeout %u 2>" _PATH_DEVNULL,
337 xauth_path, xauthfile, display, timeout);
338 debug2("x11_get_proto: %s", cmd);
339 if (system(cmd) == 0)
341 if (x11_refuse_time == 0) {
342 now = time(NULL) + 1;
343 if (UINT_MAX - timeout < now)
344 x11_refuse_time = UINT_MAX;
346 x11_refuse_time = now + timeout;
352 * When in untrusted mode, we read the cookie only if it was
353 * successfully generated as an untrusted one in the step
356 if (trusted || generated) {
357 snprintf(cmd, sizeof(cmd),
358 "%s %s%s list %s 2>" _PATH_DEVNULL,
360 generated ? "-f " : "" ,
361 generated ? xauthfile : "",
363 debug2("x11_get_proto: %s", cmd);
365 if (f && fgets(line, sizeof(line), f) &&
366 sscanf(line, "%*s %511s %511s", proto, data) == 2)
371 error("Warning: untrusted X11 forwarding setup failed: "
372 "xauth key data not generated");
385 * If we didn't get authentication data, just make up some
386 * data. The forwarding code will check the validity of the
387 * response anyway, and substitute this data. The X11
388 * server, however, will ignore this fake data and use
389 * whatever authentication mechanisms it was using otherwise
390 * for the local connection.
395 logit("Warning: No xauth data; "
396 "using fake authentication data for X11 forwarding.");
397 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
398 for (i = 0; i < 16; i++) {
401 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
409 * This is called when the interactive is entered. This checks if there is
410 * an EOF coming on stdin. We must check this explicitly, as select() does
411 * not appear to wake up when redirecting from /dev/null.
415 client_check_initial_eof_on_stdin(void)
421 * If standard input is to be "redirected from /dev/null", we simply
422 * mark that we have seen an EOF and send an EOF message to the
423 * server. Otherwise, we try to read a single character; it appears
424 * that for some files, such /dev/null, select() never wakes up for
425 * read for this descriptor, which means that we never get EOF. This
426 * way we will get the EOF if stdin comes from /dev/null or similar.
428 if (stdin_null_flag) {
429 /* Fake EOF on stdin. */
430 debug("Sending eof.");
432 packet_start(SSH_CMSG_EOF);
435 enter_non_blocking();
437 /* Check for immediate EOF on stdin. */
438 len = read(fileno(stdin), buf, 1);
441 * EOF. Record that we have seen it and send
444 debug("Sending eof.");
446 packet_start(SSH_CMSG_EOF);
448 } else if (len > 0) {
450 * Got data. We must store the data in the buffer,
451 * and also process it as an escape character if
454 if ((u_char) buf[0] == escape_char1)
457 buffer_append(&stdin_buffer, buf, 1);
459 leave_non_blocking();
465 * Make packets from buffered stdin data, and buffer them for sending to the
470 client_make_packets_from_stdin_data(void)
474 /* Send buffered stdin data to the server. */
475 while (buffer_len(&stdin_buffer) > 0 &&
476 packet_not_very_much_data_to_write()) {
477 len = buffer_len(&stdin_buffer);
478 /* Keep the packets at reasonable size. */
479 if (len > packet_get_maxsize())
480 len = packet_get_maxsize();
481 packet_start(SSH_CMSG_STDIN_DATA);
482 packet_put_string(buffer_ptr(&stdin_buffer), len);
484 buffer_consume(&stdin_buffer, len);
485 /* If we have a pending EOF, send it now. */
486 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
487 packet_start(SSH_CMSG_EOF);
494 * Checks if the client window has changed, and sends a packet about it to
495 * the server if so. The actual change is detected elsewhere (by a software
496 * interrupt on Unix); this just checks the flag and sends a message if
501 client_check_window_change(void)
505 if (! received_window_change_signal)
508 received_window_change_signal = 0;
510 debug2("client_check_window_change: changed");
513 channel_send_window_changes();
515 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
517 packet_start(SSH_CMSG_WINDOW_SIZE);
518 packet_put_int((u_int)ws.ws_row);
519 packet_put_int((u_int)ws.ws_col);
520 packet_put_int((u_int)ws.ws_xpixel);
521 packet_put_int((u_int)ws.ws_ypixel);
527 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
529 struct global_confirm *gc;
531 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
534 gc->cb(type, seq, gc->ctx);
535 if (--gc->ref_count <= 0) {
536 TAILQ_REMOVE(&global_confirms, gc, entry);
537 bzero(gc, sizeof(*gc));
541 packet_set_alive_timeouts(0);
545 server_alive_check(void)
547 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
548 logit("Timeout, server %s not responding.", host);
551 packet_start(SSH2_MSG_GLOBAL_REQUEST);
552 packet_put_cstring("keepalive@openssh.com");
553 packet_put_char(1); /* boolean: want reply */
555 /* Insert an empty placeholder to maintain ordering */
556 client_register_global_confirm(NULL, NULL);
560 * Waits until the client can do something (some data becomes available on
561 * one of the file descriptors).
564 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
565 int *maxfdp, u_int *nallocp, int rekeying)
567 struct timeval tv, *tvp;
571 /* Add any selections by the channel mechanism. */
572 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
575 /* Read from the connection, unless our buffers are full. */
576 if (buffer_len(&stdout_buffer) < buffer_high &&
577 buffer_len(&stderr_buffer) < buffer_high &&
578 channel_not_very_much_buffered_data())
579 FD_SET(connection_in, *readsetp);
581 * Read from stdin, unless we have seen EOF or have very much
582 * buffered data to send to the server.
584 if (!stdin_eof && packet_not_very_much_data_to_write())
585 FD_SET(fileno(stdin), *readsetp);
587 /* Select stdout/stderr if have data in buffer. */
588 if (buffer_len(&stdout_buffer) > 0)
589 FD_SET(fileno(stdout), *writesetp);
590 if (buffer_len(&stderr_buffer) > 0)
591 FD_SET(fileno(stderr), *writesetp);
593 /* channel_prepare_select could have closed the last channel */
594 if (session_closed && !channel_still_open() &&
595 !packet_have_data_to_write()) {
596 /* clear mask since we did not call select() */
597 memset(*readsetp, 0, *nallocp);
598 memset(*writesetp, 0, *nallocp);
601 FD_SET(connection_in, *readsetp);
605 /* Select server connection if have data to write to the server. */
606 if (packet_have_data_to_write())
607 FD_SET(connection_out, *writesetp);
610 * Wait for something to happen. This will suspend the process until
611 * some selected descriptor can be read, written, or has some other
612 * event pending, or a timeout expires.
615 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
616 if (options.server_alive_interval > 0 && compat20)
617 timeout_secs = options.server_alive_interval;
618 set_control_persist_exit_time();
619 if (control_persist_exit_time > 0) {
620 timeout_secs = MIN(timeout_secs,
621 control_persist_exit_time - time(NULL));
622 if (timeout_secs < 0)
625 if (timeout_secs == INT_MAX)
628 tv.tv_sec = timeout_secs;
633 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
638 * We have to clear the select masks, because we return.
639 * We have to return, because the mainloop checks for the flags
640 * set by the signal handlers.
642 memset(*readsetp, 0, *nallocp);
643 memset(*writesetp, 0, *nallocp);
647 /* Note: we might still have data in the buffers. */
648 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
649 buffer_append(&stderr_buffer, buf, strlen(buf));
652 server_alive_check();
656 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
658 /* Flush stdout and stderr buffers. */
659 if (buffer_len(bout) > 0)
660 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
662 if (buffer_len(berr) > 0)
663 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
666 leave_raw_mode(force_tty_flag);
669 * Free (and clear) the buffer to reduce the amount of data that gets
676 /* Send the suspend signal to the program itself. */
677 kill(getpid(), SIGTSTP);
679 /* Reset window sizes in case they have changed */
680 received_window_change_signal = 1;
682 /* OK, we have been continued by the user. Reinitialize buffers. */
687 enter_raw_mode(force_tty_flag);
691 client_process_net_input(fd_set *readset)
694 char buf[SSH_IOBUFSZ];
697 * Read input from the server, and add any such data to the buffer of
698 * the packet subsystem.
700 if (FD_ISSET(connection_in, readset)) {
701 /* Read as much as possible. */
702 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
703 if (len == 0 && cont == 0) {
705 * Received EOF. The remote host has closed the
708 snprintf(buf, sizeof buf,
709 "Connection to %.300s closed by remote host.\r\n",
711 buffer_append(&stderr_buffer, buf, strlen(buf));
716 * There is a kernel bug on Solaris that causes select to
717 * sometimes wake up even though there is no data available.
720 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
725 * An error has encountered. Perhaps there is a
728 snprintf(buf, sizeof buf,
729 "Read from remote host %.300s: %.100s\r\n",
730 host, strerror(errno));
731 buffer_append(&stderr_buffer, buf, strlen(buf));
735 packet_process_incoming(buf, len);
740 client_status_confirm(int type, Channel *c, void *ctx)
742 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
746 /* XXX supress on mux _client_ quietmode */
747 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
748 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
750 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
751 debug2("%s request accepted on channel %d",
752 cr->request_type, c->self);
753 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
755 snprintf(errmsg, sizeof(errmsg),
756 "%s request failed\r\n", cr->request_type);
758 snprintf(errmsg, sizeof(errmsg),
759 "%s request failed on channel %d",
760 cr->request_type, c->self);
762 /* If error occurred on primary session channel, then exit */
763 if (cr->do_close && c->self == session_ident)
765 /* If error occurred on mux client, append to their stderr */
767 buffer_append(&c->extended, errmsg, strlen(errmsg));
772 chan_write_failed(c);
779 client_abandon_status_confirm(Channel *c, void *ctx)
785 client_expect_confirm(int id, const char *request, int do_close)
787 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
789 cr->request_type = request;
790 cr->do_close = do_close;
792 channel_register_status_confirm(id, client_status_confirm,
793 client_abandon_status_confirm, cr);
797 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
799 struct global_confirm *gc, *last_gc;
801 /* Coalesce identical callbacks */
802 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
803 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
804 if (++last_gc->ref_count >= INT_MAX)
805 fatal("%s: last_gc->ref_count = %d",
806 __func__, last_gc->ref_count);
810 gc = xmalloc(sizeof(*gc));
814 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
818 process_cmdline(void)
820 void (*handler)(int);
821 char *s, *cmd, *cancel_host;
823 int local = 0, remote = 0, dynamic = 0;
827 bzero(&fwd, sizeof(fwd));
828 fwd.listen_host = fwd.connect_host = NULL;
830 leave_raw_mode(force_tty_flag);
831 handler = signal(SIGINT, SIG_IGN);
832 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
838 s++; /* Skip cmdline '-', if any */
842 if (*s == 'h' || *s == 'H' || *s == '?') {
844 logit(" -L[bind_address:]port:host:hostport "
845 "Request local forward");
846 logit(" -R[bind_address:]port:host:hostport "
847 "Request remote forward");
848 logit(" -D[bind_address:]port "
849 "Request dynamic forward");
850 logit(" -KR[bind_address:]port "
851 "Cancel remote forward");
852 if (!options.permit_local_command)
855 "Execute local command");
859 if (*s == '!' && options.permit_local_command) {
876 logit("Invalid command.");
880 if ((local || dynamic) && delete) {
881 logit("Not supported.");
884 if (remote && delete && !compat20) {
885 logit("Not supported for SSH protocol version 1.");
889 while (isspace(*++s))
892 /* XXX update list of forwards in options */
895 cancel_host = hpdelim(&s); /* may be NULL */
897 cancel_port = a2port(s);
898 cancel_host = cleanhostname(cancel_host);
900 cancel_port = a2port(cancel_host);
903 if (cancel_port <= 0) {
904 logit("Bad forwarding close port");
907 channel_request_rforward_cancel(cancel_host, cancel_port);
909 if (!parse_forward(&fwd, s, dynamic, remote)) {
910 logit("Bad forwarding specification.");
913 if (local || dynamic) {
914 if (channel_setup_local_fwd_listener(fwd.listen_host,
915 fwd.listen_port, fwd.connect_host,
916 fwd.connect_port, options.gateway_ports) < 0) {
917 logit("Port forwarding failed.");
921 if (channel_request_remote_forwarding(fwd.listen_host,
922 fwd.listen_port, fwd.connect_host,
923 fwd.connect_port) < 0) {
924 logit("Port forwarding failed.");
929 logit("Forwarding port.");
933 signal(SIGINT, handler);
934 enter_raw_mode(force_tty_flag);
937 if (fwd.listen_host != NULL)
938 xfree(fwd.listen_host);
939 if (fwd.connect_host != NULL)
940 xfree(fwd.connect_host);
944 * Process the characters one by one, call with c==NULL for proto1 case.
947 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
956 int *escape_pendingp, escape_char;
957 struct escape_filter_ctx *efc;
960 escape_pendingp = &escape_pending1;
961 escape_char = escape_char1;
963 if (c->filter_ctx == NULL)
965 efc = (struct escape_filter_ctx *)c->filter_ctx;
966 escape_pendingp = &efc->escape_pending;
967 escape_char = efc->escape_char;
973 for (i = 0; i < (u_int)len; i++) {
974 /* Get one character at a time. */
977 if (*escape_pendingp) {
978 /* We have previously seen an escape character. */
979 /* Clear the flag now. */
980 *escape_pendingp = 0;
982 /* Process the escaped character. */
985 /* Terminate the connection. */
986 snprintf(string, sizeof string, "%c.\r\n",
988 buffer_append(berr, string, strlen(string));
990 if (c && c->ctl_chan != -1) {
992 chan_write_failed(c);
999 /* XXX support this for mux clients */
1000 if (c && c->ctl_chan != -1) {
1002 snprintf(string, sizeof string,
1003 "%c%c escape not available to "
1004 "multiplexed sessions\r\n",
1006 buffer_append(berr, string,
1010 /* Suspend the program. Inform the user */
1011 snprintf(string, sizeof string,
1012 "%c^Z [suspend ssh]\r\n", escape_char);
1013 buffer_append(berr, string, strlen(string));
1015 /* Restore terminal modes and suspend. */
1016 client_suspend_self(bin, bout, berr);
1018 /* We have been continued. */
1023 snprintf(string, sizeof string,
1024 "%cB\r\n", escape_char);
1025 buffer_append(berr, string,
1027 channel_request_start(session_ident,
1029 packet_put_int(1000);
1036 if (datafellows & SSH_BUG_NOREKEY)
1037 logit("Server does not "
1038 "support re-keying");
1045 if (c && c->ctl_chan != -1)
1048 * Detach the program (continue to serve
1049 * connections, but put in background and no
1050 * more new connections).
1052 /* Restore tty modes. */
1053 leave_raw_mode(force_tty_flag);
1055 /* Stop listening for new connections. */
1056 channel_stop_listening();
1058 snprintf(string, sizeof string,
1059 "%c& [backgrounded]\n", escape_char);
1060 buffer_append(berr, string, strlen(string));
1062 /* Fork into background. */
1065 error("fork: %.100s", strerror(errno));
1068 if (pid != 0) { /* This is the parent. */
1069 /* The parent just exits. */
1072 /* The child continues serving connections. */
1074 buffer_append(bin, "\004", 1);
1075 /* fake EOF on stdin */
1077 } else if (!stdin_eof) {
1079 * Sending SSH_CMSG_EOF alone does not
1080 * always appear to be enough. So we
1081 * try to send an EOF character first.
1083 packet_start(SSH_CMSG_STDIN_DATA);
1084 packet_put_string("\004", 1);
1088 if (buffer_len(bin) == 0) {
1089 packet_start(SSH_CMSG_EOF);
1096 if (c && c->ctl_chan != -1) {
1097 snprintf(string, sizeof string,
1099 Supported escape sequences:\r\n\
1100 %c. - terminate session\r\n\
1101 %cB - send a BREAK to the remote system\r\n\
1102 %cR - Request rekey (SSH protocol 2 only)\r\n\
1103 %c# - list forwarded connections\r\n\
1104 %c? - this message\r\n\
1105 %c%c - send the escape character by typing it twice\r\n\
1106 (Note that escapes are only recognized immediately after newline.)\r\n",
1107 escape_char, escape_char,
1108 escape_char, escape_char,
1109 escape_char, escape_char,
1110 escape_char, escape_char);
1112 snprintf(string, sizeof string,
1114 Supported escape sequences:\r\n\
1115 %c. - terminate connection (and any multiplexed sessions)\r\n\
1116 %cB - send a BREAK to the remote system\r\n\
1117 %cC - open a command line\r\n\
1118 %cR - Request rekey (SSH protocol 2 only)\r\n\
1119 %c^Z - suspend ssh\r\n\
1120 %c# - list forwarded connections\r\n\
1121 %c& - background ssh (when waiting for connections to terminate)\r\n\
1122 %c? - this message\r\n\
1123 %c%c - send the escape character by typing it twice\r\n\
1124 (Note that escapes are only recognized immediately after newline.)\r\n",
1125 escape_char, escape_char,
1126 escape_char, escape_char,
1127 escape_char, escape_char,
1128 escape_char, escape_char,
1129 escape_char, escape_char,
1132 buffer_append(berr, string, strlen(string));
1136 snprintf(string, sizeof string, "%c#\r\n",
1138 buffer_append(berr, string, strlen(string));
1139 s = channel_open_message();
1140 buffer_append(berr, s, strlen(s));
1145 if (c && c->ctl_chan != -1)
1151 if (ch != escape_char) {
1152 buffer_put_char(bin, escape_char);
1155 /* Escaped characters fall through here */
1160 * The previous character was not an escape char.
1161 * Check if this is an escape.
1163 if (last_was_cr && ch == escape_char) {
1165 * It is. Set the flag and continue to
1168 *escape_pendingp = 1;
1174 * Normal character. Record whether it was a newline,
1175 * and append it to the buffer.
1177 last_was_cr = (ch == '\r' || ch == '\n');
1178 buffer_put_char(bin, ch);
1185 client_process_input(fd_set *readset)
1188 char buf[SSH_IOBUFSZ];
1190 /* Read input from stdin. */
1191 if (FD_ISSET(fileno(stdin), readset)) {
1192 /* Read as much as possible. */
1193 len = read(fileno(stdin), buf, sizeof(buf));
1195 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1196 return; /* we'll try again later */
1199 * Received EOF or error. They are treated
1200 * similarly, except that an error message is printed
1201 * if it was an error condition.
1204 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1206 buffer_append(&stderr_buffer, buf, strlen(buf));
1208 /* Mark that we have seen EOF. */
1211 * Send an EOF message to the server unless there is
1212 * data in the buffer. If there is data in the
1213 * buffer, no message will be sent now. Code
1214 * elsewhere will send the EOF when the buffer
1215 * becomes empty if stdin_eof is set.
1217 if (buffer_len(&stdin_buffer) == 0) {
1218 packet_start(SSH_CMSG_EOF);
1221 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1223 * Normal successful read, and no escape character.
1224 * Just append the data to buffer.
1226 buffer_append(&stdin_buffer, buf, len);
1229 * Normal, successful read. But we have an escape
1230 * character and have to process the characters one
1233 if (process_escapes(NULL, &stdin_buffer,
1234 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1241 client_process_output(fd_set *writeset)
1246 /* Write buffered output to stdout. */
1247 if (FD_ISSET(fileno(stdout), writeset)) {
1248 /* Write as much data as possible. */
1249 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1250 buffer_len(&stdout_buffer));
1252 if (errno == EINTR || errno == EAGAIN ||
1253 errno == EWOULDBLOCK)
1257 * An error or EOF was encountered. Put an
1258 * error message to stderr buffer.
1260 snprintf(buf, sizeof buf,
1261 "write stdout: %.50s\r\n", strerror(errno));
1262 buffer_append(&stderr_buffer, buf, strlen(buf));
1267 /* Consume printed data from the buffer. */
1268 buffer_consume(&stdout_buffer, len);
1270 /* Write buffered output to stderr. */
1271 if (FD_ISSET(fileno(stderr), writeset)) {
1272 /* Write as much data as possible. */
1273 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1274 buffer_len(&stderr_buffer));
1276 if (errno == EINTR || errno == EAGAIN ||
1277 errno == EWOULDBLOCK)
1281 * EOF or error, but can't even print
1288 /* Consume printed characters from the buffer. */
1289 buffer_consume(&stderr_buffer, len);
1294 * Get packets from the connection input buffer, and process them as long as
1295 * there are packets available.
1297 * Any unknown packets received during the actual
1298 * session cause the session to terminate. This is
1299 * intended to make debugging easier since no
1300 * confirmations are sent. Any compatible protocol
1301 * extensions must be negotiated during the
1302 * preparatory phase.
1306 client_process_buffered_input_packets(void)
1308 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1309 compat20 ? xxx_kex : NULL);
1312 /* scan buf[] for '~' before sending data to the peer */
1314 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1316 client_new_escape_filter_ctx(int escape_char)
1318 struct escape_filter_ctx *ret;
1320 ret = xmalloc(sizeof(*ret));
1321 ret->escape_pending = 0;
1322 ret->escape_char = escape_char;
1326 /* Free the escape filter context on channel free */
1328 client_filter_cleanup(int cid, void *ctx)
1334 client_simple_escape_filter(Channel *c, char *buf, int len)
1336 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1339 return process_escapes(c, &c->input, &c->output, &c->extended,
1344 client_channel_closed(int id, void *arg)
1346 channel_cancel_cleanup(id);
1348 leave_raw_mode(force_tty_flag);
1352 * Implements the interactive session with the server. This is called after
1353 * the user has been authenticated, and a command has been started on the
1354 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1355 * used as an escape character for terminating or suspending the session.
1359 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1361 fd_set *readset = NULL, *writeset = NULL;
1362 double start_time, total_time;
1363 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1364 u_int64_t ibytes, obytes;
1368 debug("Entering interactive session.");
1370 start_time = get_current_time();
1372 /* Initialize variables. */
1373 escape_pending1 = 0;
1377 buffer_high = 64 * 1024;
1378 connection_in = packet_get_connection_in();
1379 connection_out = packet_get_connection_out();
1380 max_fd = MAX(connection_in, connection_out);
1383 /* enable nonblocking unless tty */
1384 if (!isatty(fileno(stdin)))
1385 set_nonblock(fileno(stdin));
1386 if (!isatty(fileno(stdout)))
1387 set_nonblock(fileno(stdout));
1388 if (!isatty(fileno(stderr)))
1389 set_nonblock(fileno(stderr));
1390 max_fd = MAX(max_fd, fileno(stdin));
1391 max_fd = MAX(max_fd, fileno(stdout));
1392 max_fd = MAX(max_fd, fileno(stderr));
1395 escape_char1 = escape_char_arg;
1397 /* Initialize buffers. */
1398 buffer_init(&stdin_buffer);
1399 buffer_init(&stdout_buffer);
1400 buffer_init(&stderr_buffer);
1402 client_init_dispatch();
1405 * Set signal handlers, (e.g. to restore non-blocking mode)
1406 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1408 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1409 signal(SIGHUP, signal_handler);
1410 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1411 signal(SIGINT, signal_handler);
1412 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1413 signal(SIGQUIT, signal_handler);
1414 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1415 signal(SIGTERM, signal_handler);
1416 signal(SIGWINCH, window_change_handler);
1419 enter_raw_mode(force_tty_flag);
1422 session_ident = ssh2_chan_id;
1423 if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1424 channel_register_filter(session_ident,
1425 client_simple_escape_filter, NULL,
1426 client_filter_cleanup,
1427 client_new_escape_filter_ctx(escape_char_arg));
1428 if (session_ident != -1)
1429 channel_register_cleanup(session_ident,
1430 client_channel_closed, 0);
1432 /* Check if we should immediately send eof on stdin. */
1433 client_check_initial_eof_on_stdin();
1436 /* Main loop of the client for the interactive session mode. */
1437 while (!quit_pending) {
1439 /* Process buffered packets sent by the server. */
1440 client_process_buffered_input_packets();
1442 if (compat20 && session_closed && !channel_still_open())
1445 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1448 debug("rekeying in progress");
1451 * Make packets of buffered stdin data, and buffer
1452 * them for sending to the server.
1455 client_make_packets_from_stdin_data();
1458 * Make packets from buffered channel data, and
1459 * enqueue them for sending to the server.
1461 if (packet_not_very_much_data_to_write())
1462 channel_output_poll();
1465 * Check if the window size has changed, and buffer a
1466 * message about it to the server if so.
1468 client_check_window_change();
1474 * Wait until we have something to do (something becomes
1475 * available on one of the descriptors).
1478 client_wait_until_can_do_something(&readset, &writeset,
1479 &max_fd2, &nalloc, rekeying);
1484 /* Do channel operations unless rekeying in progress. */
1486 channel_after_select(readset, writeset);
1487 if (need_rekeying || packet_need_rekeying()) {
1488 debug("need rekeying");
1490 kex_send_kexinit(xxx_kex);
1495 /* Buffer input from the connection. */
1496 client_process_net_input(readset);
1502 /* Buffer data from stdin */
1503 client_process_input(readset);
1505 * Process output to stdout and stderr. Output to
1506 * the connection is processed elsewhere (above).
1508 client_process_output(writeset);
1511 if (session_resumed) {
1512 connection_in = packet_get_connection_in();
1513 connection_out = packet_get_connection_out();
1514 max_fd = MAX(max_fd, connection_out);
1515 max_fd = MAX(max_fd, connection_in);
1516 session_resumed = 0;
1520 * Send as much buffered packet data as possible to the
1523 if (FD_ISSET(connection_out, writeset))
1524 packet_write_poll();
1527 * If we are a backgrounded control master, and the
1528 * timeout has expired without any active client
1529 * connections, then quit.
1531 if (control_persist_exit_time > 0) {
1532 if (time(NULL) >= control_persist_exit_time) {
1533 debug("ControlPersist timeout expired");
1543 /* Terminate the session. */
1545 /* Stop watching for window change. */
1546 signal(SIGWINCH, SIG_DFL);
1549 packet_start(SSH2_MSG_DISCONNECT);
1550 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1551 packet_put_cstring("disconnected by user");
1552 packet_put_cstring(""); /* language tag */
1554 packet_write_wait();
1560 leave_raw_mode(force_tty_flag);
1562 /* restore blocking io */
1563 if (!isatty(fileno(stdin)))
1564 unset_nonblock(fileno(stdin));
1565 if (!isatty(fileno(stdout)))
1566 unset_nonblock(fileno(stdout));
1567 if (!isatty(fileno(stderr)))
1568 unset_nonblock(fileno(stderr));
1571 * If there was no shell or command requested, there will be no remote
1572 * exit status to be returned. In that case, clear error code if the
1573 * connection was deliberately terminated at this end.
1575 if (no_shell_flag && received_signal == SIGTERM) {
1576 received_signal = 0;
1580 if (received_signal)
1581 fatal("Killed by signal %d.", (int) received_signal);
1584 * In interactive mode (with pseudo tty) display a message indicating
1585 * that the connection has been closed.
1587 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1588 snprintf(buf, sizeof buf,
1589 "Connection to %.64s closed.\r\n", host);
1590 buffer_append(&stderr_buffer, buf, strlen(buf));
1593 /* Output any buffered data for stdout. */
1594 if (buffer_len(&stdout_buffer) > 0) {
1595 len = atomicio(vwrite, fileno(stdout),
1596 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1597 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1598 error("Write failed flushing stdout buffer.");
1600 buffer_consume(&stdout_buffer, len);
1603 /* Output any buffered data for stderr. */
1604 if (buffer_len(&stderr_buffer) > 0) {
1605 len = atomicio(vwrite, fileno(stderr),
1606 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1607 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1608 error("Write failed flushing stderr buffer.");
1610 buffer_consume(&stderr_buffer, len);
1613 /* Clear and free any buffers. */
1614 memset(buf, 0, sizeof(buf));
1615 buffer_free(&stdin_buffer);
1616 buffer_free(&stdout_buffer);
1617 buffer_free(&stderr_buffer);
1619 /* Report bytes transferred, and transfer rates. */
1620 total_time = get_current_time() - start_time;
1621 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1622 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1623 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1624 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1626 verbose("Bytes per second: sent %.1f, received %.1f",
1627 obytes / total_time, ibytes / total_time);
1628 /* Return the exit status of the program. */
1629 debug("Exit status %d", exit_status);
1636 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1639 char *data = packet_get_string(&data_len);
1641 buffer_append(&stdout_buffer, data, data_len);
1642 memset(data, 0, data_len);
1646 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1649 char *data = packet_get_string(&data_len);
1651 buffer_append(&stderr_buffer, data, data_len);
1652 memset(data, 0, data_len);
1656 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1658 exit_status = packet_get_int();
1660 /* Acknowledge the exit. */
1661 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1664 * Must wait for packet to be sent since we are
1667 packet_write_wait();
1668 /* Flag that we want to exit. */
1672 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1675 int remote_id, sock;
1677 /* Read the remote channel number from the message. */
1678 remote_id = packet_get_int();
1682 * Get a connection to the local authentication agent (this may again
1685 sock = ssh_get_authentication_socket();
1688 * If we could not connect the agent, send an error message back to
1689 * the server. This should never happen unless the agent dies,
1690 * because authentication forwarding is only enabled if we have an
1694 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1695 -1, 0, 0, 0, "authentication agent connection", 1);
1696 c->remote_id = remote_id;
1700 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1701 packet_put_int(remote_id);
1703 /* Send a confirmation to the remote host. */
1704 debug("Forwarding authentication connection.");
1705 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1706 packet_put_int(remote_id);
1707 packet_put_int(c->self);
1713 client_request_forwarded_tcpip(const char *request_type, int rchan)
1716 char *listen_address, *originator_address;
1717 u_short listen_port, originator_port;
1719 /* Get rest of the packet */
1720 listen_address = packet_get_string(NULL);
1721 listen_port = packet_get_int();
1722 originator_address = packet_get_string(NULL);
1723 originator_port = packet_get_int();
1726 debug("client_request_forwarded_tcpip: listen %s port %d, "
1727 "originator %s port %d", listen_address, listen_port,
1728 originator_address, originator_port);
1730 c = channel_connect_by_listen_address(listen_port,
1731 "forwarded-tcpip", originator_address);
1733 xfree(originator_address);
1734 xfree(listen_address);
1739 client_request_x11(const char *request_type, int rchan)
1743 u_short originator_port;
1746 if (!options.forward_x11) {
1747 error("Warning: ssh server tried X11 forwarding.");
1748 error("Warning: this is probably a break-in attempt by a "
1749 "malicious server.");
1752 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1753 verbose("Rejected X11 connection after ForwardX11Timeout "
1757 originator = packet_get_string(NULL);
1758 if (datafellows & SSH_BUG_X11FWD) {
1759 debug2("buggy server: x11 request w/o originator_port");
1760 originator_port = 0;
1762 originator_port = packet_get_int();
1765 /* XXX check permission */
1766 debug("client_request_x11: request from %s %d", originator,
1769 sock = x11_connect_display();
1772 if (options.hpn_disabled)
1773 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1774 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1777 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1778 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
1785 client_request_agent(const char *request_type, int rchan)
1790 if (!options.forward_agent) {
1791 error("Warning: ssh server tried agent forwarding.");
1792 error("Warning: this is probably a break-in attempt by a "
1793 "malicious server.");
1796 sock = ssh_get_authentication_socket();
1799 if (options.hpn_disabled)
1800 c = channel_new("authentication agent connection",
1801 SSH_CHANNEL_OPEN, sock, sock, -1,
1802 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1803 "authentication agent connection", 1);
1805 c = channel_new("authentication agent connection",
1806 SSH_CHANNEL_OPEN, sock, sock, -1,
1807 options.hpn_buffer_size, options.hpn_buffer_size, 0,
1808 "authentication agent connection", 1);
1814 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1819 if (tun_mode == SSH_TUNMODE_NO)
1823 error("Tunnel forwarding is not supported for protocol 1");
1827 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1829 /* Open local tunnel device */
1830 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1831 error("Tunnel device open failed.");
1835 if (options.hpn_disabled)
1836 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1837 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1840 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1841 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1845 #if defined(SSH_TUN_FILTER)
1846 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1847 channel_register_filter(c->self, sys_tun_infilter,
1848 sys_tun_outfilter, NULL, NULL);
1851 packet_start(SSH2_MSG_CHANNEL_OPEN);
1852 packet_put_cstring("tun@openssh.com");
1853 packet_put_int(c->self);
1854 packet_put_int(c->local_window_max);
1855 packet_put_int(c->local_maxpacket);
1856 packet_put_int(tun_mode);
1857 packet_put_int(remote_tun);
1863 /* XXXX move to generic input handler */
1865 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1870 u_int rmaxpack, rwindow, len;
1872 ctype = packet_get_string(&len);
1873 rchan = packet_get_int();
1874 rwindow = packet_get_int();
1875 rmaxpack = packet_get_int();
1877 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1878 ctype, rchan, rwindow, rmaxpack);
1880 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1881 c = client_request_forwarded_tcpip(ctype, rchan);
1882 } else if (strcmp(ctype, "x11") == 0) {
1883 c = client_request_x11(ctype, rchan);
1884 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1885 c = client_request_agent(ctype, rchan);
1887 /* XXX duplicate : */
1889 debug("confirm %s", ctype);
1890 c->remote_id = rchan;
1891 c->remote_window = rwindow;
1892 c->remote_maxpacket = rmaxpack;
1893 if (c->type != SSH_CHANNEL_CONNECTING) {
1894 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1895 packet_put_int(c->remote_id);
1896 packet_put_int(c->self);
1897 packet_put_int(c->local_window);
1898 packet_put_int(c->local_maxpacket);
1902 debug("failure %s", ctype);
1903 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1904 packet_put_int(rchan);
1905 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1906 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1907 packet_put_cstring("open failed");
1908 packet_put_cstring("");
1915 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1918 int exitval, id, reply, success = 0;
1921 id = packet_get_int();
1922 rtype = packet_get_string(NULL);
1923 reply = packet_get_char();
1925 debug("client_input_channel_req: channel %d rtype %s reply %d",
1929 error("client_input_channel_req: request for channel -1");
1930 } else if ((c = channel_lookup(id)) == NULL) {
1931 error("client_input_channel_req: channel %d: "
1932 "unknown channel", id);
1933 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1936 } else if (strcmp(rtype, "exit-status") == 0) {
1937 exitval = packet_get_int();
1938 if (c->ctl_chan != -1) {
1939 mux_exit_message(c, exitval);
1941 } else if (id == session_ident) {
1942 /* Record exit value of local session */
1944 exit_status = exitval;
1946 /* Probably for a mux channel that has already closed */
1947 debug("%s: no sink for exit-status on channel %d",
1952 if (reply && c != NULL) {
1953 packet_start(success ?
1954 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1955 packet_put_int(c->remote_id);
1961 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1967 rtype = packet_get_string(NULL);
1968 want_reply = packet_get_char();
1969 debug("client_input_global_request: rtype %s want_reply %d",
1972 packet_start(success ?
1973 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1975 packet_write_wait();
1981 client_session2_setup(int id, int want_tty, int want_subsystem,
1982 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1987 debug2("%s: id %d", __func__, id);
1989 if ((c = channel_lookup(id)) == NULL)
1990 fatal("client_session2_setup: channel %d: unknown channel", id);
1992 packet_set_interactive(want_tty,
1993 options.ip_qos_interactive, options.ip_qos_bulk);
1998 /* Store window size in the packet. */
1999 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2000 memset(&ws, 0, sizeof(ws));
2002 channel_request_start(id, "pty-req", 1);
2003 client_expect_confirm(id, "PTY allocation", 1);
2004 packet_put_cstring(term != NULL ? term : "");
2005 packet_put_int((u_int)ws.ws_col);
2006 packet_put_int((u_int)ws.ws_row);
2007 packet_put_int((u_int)ws.ws_xpixel);
2008 packet_put_int((u_int)ws.ws_ypixel);
2010 tiop = get_saved_tio();
2011 tty_make_modes(-1, tiop);
2013 /* XXX wait for reply */
2017 /* Transfer any environment variables from client to server */
2018 if (options.num_send_env != 0 && env != NULL) {
2022 debug("Sending environment.");
2023 for (i = 0; env[i] != NULL; i++) {
2025 name = xstrdup(env[i]);
2026 if ((val = strchr(name, '=')) == NULL) {
2033 for (j = 0; j < options.num_send_env; j++) {
2034 if (match_pattern(name, options.send_env[j])) {
2040 debug3("Ignored env %s", name);
2045 debug("Sending env %s = %s", name, val);
2046 channel_request_start(id, "env", 0);
2047 packet_put_cstring(name);
2048 packet_put_cstring(val);
2054 len = buffer_len(cmd);
2058 if (want_subsystem) {
2059 debug("Sending subsystem: %.*s",
2060 len, (u_char*)buffer_ptr(cmd));
2061 channel_request_start(id, "subsystem", 1);
2062 client_expect_confirm(id, "subsystem", 1);
2064 debug("Sending command: %.*s",
2065 len, (u_char*)buffer_ptr(cmd));
2066 channel_request_start(id, "exec", 1);
2067 client_expect_confirm(id, "exec", 1);
2069 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2072 channel_request_start(id, "shell", 1);
2073 client_expect_confirm(id, "shell", 1);
2079 client_init_dispatch_20(void)
2081 dispatch_init(&dispatch_protocol_error);
2083 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2084 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2085 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2086 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2087 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2088 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2089 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2090 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2091 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2092 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2093 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2094 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2097 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2099 /* global request reply messages */
2100 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2101 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2105 client_init_dispatch_13(void)
2107 dispatch_init(NULL);
2108 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2109 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2110 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2111 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2112 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2113 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2114 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2115 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2116 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2118 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2119 &client_input_agent_open : &deny_input_open);
2120 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2121 &x11_input_open : &deny_input_open);
2125 client_init_dispatch_15(void)
2127 client_init_dispatch_13();
2128 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2129 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2133 client_init_dispatch(void)
2136 client_init_dispatch_20();
2138 client_init_dispatch_13();
2140 client_init_dispatch_15();
2143 /* client specific fatal cleanup */
2147 leave_raw_mode(force_tty_flag);
2148 leave_non_blocking();
2149 if (options.control_path != NULL && muxserver_sock != -1)
2150 unlink(options.control_path);
2151 ssh_kill_proxy_command();