1 /* $OpenBSD: clientloop.c,v 1.231 2011/01/16 12:05:59 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; /* XXX use mux_client_cleanup() instead */
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the HostName specified for the user-supplied name in a
129 * configuration file.
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 /* Time when backgrounded control master using ControlPersist should exit */
149 static time_t control_persist_exit_time = 0;
151 /* Common data for the client loop code. */
152 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
153 static int escape_char1; /* Escape character. (proto1 only) */
154 static int escape_pending1; /* Last character was an escape (proto1 only) */
155 static int last_was_cr; /* Last character was a newline. */
156 static int exit_status; /* Used to store the command exit status. */
157 static int stdin_eof; /* EOF has been encountered on stderr. */
158 static Buffer stdin_buffer; /* Buffer for stdin data. */
159 static Buffer stdout_buffer; /* Buffer for stdout data. */
160 static Buffer stderr_buffer; /* Buffer for stderr data. */
161 static u_int buffer_high; /* Soft max buffer size. */
162 static int connection_in; /* Connection to server (input). */
163 static int connection_out; /* Connection to server (output). */
164 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
165 static int session_closed; /* In SSH2: login session closed. */
166 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
168 static void client_init_dispatch(void);
169 int session_ident = -1;
171 int session_resumed = 0;
173 /* Track escape per proto2 channel */
174 struct escape_filter_ctx {
179 /* Context for channel confirmation replies */
180 struct channel_reply_ctx {
181 const char *request_type;
185 /* Global request success/failure callbacks */
186 struct global_confirm {
187 TAILQ_ENTRY(global_confirm) entry;
188 global_confirm_cb *cb;
192 TAILQ_HEAD(global_confirms, global_confirm);
193 static struct global_confirms global_confirms =
194 TAILQ_HEAD_INITIALIZER(global_confirms);
199 void ssh_process_session2_setup(int, int, int, Buffer *);
201 /* Restores stdin to blocking mode. */
204 leave_non_blocking(void)
206 if (in_non_blocking_mode) {
207 unset_nonblock(fileno(stdin));
208 in_non_blocking_mode = 0;
212 /* Puts stdin terminal in non-blocking mode. */
215 enter_non_blocking(void)
217 in_non_blocking_mode = 1;
218 set_nonblock(fileno(stdin));
222 * Signal handler for the window change signal (SIGWINCH). This just sets a
223 * flag indicating that the window has changed.
227 window_change_handler(int sig)
229 received_window_change_signal = 1;
230 signal(SIGWINCH, window_change_handler);
234 * Signal handler for signals that cause the program to terminate. These
235 * signals must be trapped to restore terminal modes.
239 signal_handler(int sig)
241 received_signal = sig;
246 * Returns current time in seconds from Jan 1, 1970 with the maximum
247 * available resolution.
251 get_current_time(void)
254 gettimeofday(&tv, NULL);
255 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
259 * Sets control_persist_exit_time to the absolute time when the
260 * backgrounded control master should exit due to expiry of the
261 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
262 * control master process, or if there is no ControlPersist timeout.
265 set_control_persist_exit_time(void)
267 if (muxserver_sock == -1 || !options.control_persist
268 || options.control_persist_timeout == 0)
269 /* not using a ControlPersist timeout */
270 control_persist_exit_time = 0;
271 else if (channel_still_open()) {
272 /* some client connections are still open */
273 if (control_persist_exit_time > 0)
274 debug2("%s: cancel scheduled exit", __func__);
275 control_persist_exit_time = 0;
276 } else if (control_persist_exit_time <= 0) {
277 /* a client connection has recently closed */
278 control_persist_exit_time = time(NULL) +
279 (time_t)options.control_persist_timeout;
280 debug2("%s: schedule exit in %d seconds", __func__,
281 options.control_persist_timeout);
283 /* else we are already counting down to the timeout */
286 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
288 client_x11_get_proto(const char *display, const char *xauth_path,
289 u_int trusted, u_int timeout, char **_proto, char **_data)
294 static char proto[512], data[512];
296 int got_data = 0, generated = 0, do_unlink = 0, i;
297 char *xauthdir, *xauthfile;
301 xauthdir = xauthfile = NULL;
304 proto[0] = data[0] = '\0';
306 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
307 debug("No xauth program.");
309 if (display == NULL) {
310 debug("x11_get_proto: DISPLAY not set");
314 * Handle FamilyLocal case where $DISPLAY does
315 * not match an authorization entry. For this we
316 * just try "xauth list unix:displaynum.screennum".
317 * XXX: "localhost" match to determine FamilyLocal
320 if (strncmp(display, "localhost:", 10) == 0) {
321 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
326 xauthdir = xmalloc(MAXPATHLEN);
327 xauthfile = xmalloc(MAXPATHLEN);
328 mktemp_proto(xauthdir, MAXPATHLEN);
329 if (mkdtemp(xauthdir) != NULL) {
331 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
333 snprintf(cmd, sizeof(cmd),
334 "%s -f %s generate %s " SSH_X11_PROTO
335 " untrusted timeout %u 2>" _PATH_DEVNULL,
336 xauth_path, xauthfile, display, timeout);
337 debug2("x11_get_proto: %s", cmd);
338 if (system(cmd) == 0)
340 if (x11_refuse_time == 0) {
341 now = time(NULL) + 1;
342 if (UINT_MAX - timeout < now)
343 x11_refuse_time = UINT_MAX;
345 x11_refuse_time = now + timeout;
351 * When in untrusted mode, we read the cookie only if it was
352 * successfully generated as an untrusted one in the step
355 if (trusted || generated) {
356 snprintf(cmd, sizeof(cmd),
357 "%s %s%s list %s 2>" _PATH_DEVNULL,
359 generated ? "-f " : "" ,
360 generated ? xauthfile : "",
362 debug2("x11_get_proto: %s", cmd);
364 if (f && fgets(line, sizeof(line), f) &&
365 sscanf(line, "%*s %511s %511s", proto, data) == 2)
370 error("Warning: untrusted X11 forwarding setup failed: "
371 "xauth key data not generated");
384 * If we didn't get authentication data, just make up some
385 * data. The forwarding code will check the validity of the
386 * response anyway, and substitute this data. The X11
387 * server, however, will ignore this fake data and use
388 * whatever authentication mechanisms it was using otherwise
389 * for the local connection.
394 logit("Warning: No xauth data; "
395 "using fake authentication data for X11 forwarding.");
396 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
397 for (i = 0; i < 16; i++) {
400 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
408 * This is called when the interactive is entered. This checks if there is
409 * an EOF coming on stdin. We must check this explicitly, as select() does
410 * not appear to wake up when redirecting from /dev/null.
414 client_check_initial_eof_on_stdin(void)
420 * If standard input is to be "redirected from /dev/null", we simply
421 * mark that we have seen an EOF and send an EOF message to the
422 * server. Otherwise, we try to read a single character; it appears
423 * that for some files, such /dev/null, select() never wakes up for
424 * read for this descriptor, which means that we never get EOF. This
425 * way we will get the EOF if stdin comes from /dev/null or similar.
427 if (stdin_null_flag) {
428 /* Fake EOF on stdin. */
429 debug("Sending eof.");
431 packet_start(SSH_CMSG_EOF);
434 enter_non_blocking();
436 /* Check for immediate EOF on stdin. */
437 len = read(fileno(stdin), buf, 1);
440 * EOF. Record that we have seen it and send
443 debug("Sending eof.");
445 packet_start(SSH_CMSG_EOF);
447 } else if (len > 0) {
449 * Got data. We must store the data in the buffer,
450 * and also process it as an escape character if
453 if ((u_char) buf[0] == escape_char1)
456 buffer_append(&stdin_buffer, buf, 1);
458 leave_non_blocking();
464 * Make packets from buffered stdin data, and buffer them for sending to the
469 client_make_packets_from_stdin_data(void)
473 /* Send buffered stdin data to the server. */
474 while (buffer_len(&stdin_buffer) > 0 &&
475 packet_not_very_much_data_to_write()) {
476 len = buffer_len(&stdin_buffer);
477 /* Keep the packets at reasonable size. */
478 if (len > packet_get_maxsize())
479 len = packet_get_maxsize();
480 packet_start(SSH_CMSG_STDIN_DATA);
481 packet_put_string(buffer_ptr(&stdin_buffer), len);
483 buffer_consume(&stdin_buffer, len);
484 /* If we have a pending EOF, send it now. */
485 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
486 packet_start(SSH_CMSG_EOF);
493 * Checks if the client window has changed, and sends a packet about it to
494 * the server if so. The actual change is detected elsewhere (by a software
495 * interrupt on Unix); this just checks the flag and sends a message if
500 client_check_window_change(void)
504 if (! received_window_change_signal)
507 received_window_change_signal = 0;
509 debug2("client_check_window_change: changed");
512 channel_send_window_changes();
514 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
516 packet_start(SSH_CMSG_WINDOW_SIZE);
517 packet_put_int((u_int)ws.ws_row);
518 packet_put_int((u_int)ws.ws_col);
519 packet_put_int((u_int)ws.ws_xpixel);
520 packet_put_int((u_int)ws.ws_ypixel);
526 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
528 struct global_confirm *gc;
530 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
533 gc->cb(type, seq, gc->ctx);
534 if (--gc->ref_count <= 0) {
535 TAILQ_REMOVE(&global_confirms, gc, entry);
536 bzero(gc, sizeof(*gc));
540 packet_set_alive_timeouts(0);
544 server_alive_check(void)
546 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
547 logit("Timeout, server %s not responding.", host);
550 packet_start(SSH2_MSG_GLOBAL_REQUEST);
551 packet_put_cstring("keepalive@openssh.com");
552 packet_put_char(1); /* boolean: want reply */
554 /* Insert an empty placeholder to maintain ordering */
555 client_register_global_confirm(NULL, NULL);
559 * Waits until the client can do something (some data becomes available on
560 * one of the file descriptors).
563 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
564 int *maxfdp, u_int *nallocp, int rekeying)
566 struct timeval tv, *tvp;
570 /* Add any selections by the channel mechanism. */
571 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
574 /* Read from the connection, unless our buffers are full. */
575 if (buffer_len(&stdout_buffer) < buffer_high &&
576 buffer_len(&stderr_buffer) < buffer_high &&
577 channel_not_very_much_buffered_data())
578 FD_SET(connection_in, *readsetp);
580 * Read from stdin, unless we have seen EOF or have very much
581 * buffered data to send to the server.
583 if (!stdin_eof && packet_not_very_much_data_to_write())
584 FD_SET(fileno(stdin), *readsetp);
586 /* Select stdout/stderr if have data in buffer. */
587 if (buffer_len(&stdout_buffer) > 0)
588 FD_SET(fileno(stdout), *writesetp);
589 if (buffer_len(&stderr_buffer) > 0)
590 FD_SET(fileno(stderr), *writesetp);
592 /* channel_prepare_select could have closed the last channel */
593 if (session_closed && !channel_still_open() &&
594 !packet_have_data_to_write()) {
595 /* clear mask since we did not call select() */
596 memset(*readsetp, 0, *nallocp);
597 memset(*writesetp, 0, *nallocp);
600 FD_SET(connection_in, *readsetp);
604 /* Select server connection if have data to write to the server. */
605 if (packet_have_data_to_write())
606 FD_SET(connection_out, *writesetp);
609 * Wait for something to happen. This will suspend the process until
610 * some selected descriptor can be read, written, or has some other
611 * event pending, or a timeout expires.
614 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
615 if (options.server_alive_interval > 0 && compat20)
616 timeout_secs = options.server_alive_interval;
617 set_control_persist_exit_time();
618 if (control_persist_exit_time > 0) {
619 timeout_secs = MIN(timeout_secs,
620 control_persist_exit_time - time(NULL));
621 if (timeout_secs < 0)
624 if (timeout_secs == INT_MAX)
627 tv.tv_sec = timeout_secs;
632 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
637 * We have to clear the select masks, because we return.
638 * We have to return, because the mainloop checks for the flags
639 * set by the signal handlers.
641 memset(*readsetp, 0, *nallocp);
642 memset(*writesetp, 0, *nallocp);
646 /* Note: we might still have data in the buffers. */
647 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
648 buffer_append(&stderr_buffer, buf, strlen(buf));
651 server_alive_check();
655 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
657 /* Flush stdout and stderr buffers. */
658 if (buffer_len(bout) > 0)
659 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
661 if (buffer_len(berr) > 0)
662 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
665 leave_raw_mode(force_tty_flag);
668 * Free (and clear) the buffer to reduce the amount of data that gets
675 /* Send the suspend signal to the program itself. */
676 kill(getpid(), SIGTSTP);
678 /* Reset window sizes in case they have changed */
679 received_window_change_signal = 1;
681 /* OK, we have been continued by the user. Reinitialize buffers. */
686 enter_raw_mode(force_tty_flag);
690 client_process_net_input(fd_set *readset)
693 char buf[SSH_IOBUFSZ];
696 * Read input from the server, and add any such data to the buffer of
697 * the packet subsystem.
699 if (FD_ISSET(connection_in, readset)) {
700 /* Read as much as possible. */
701 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
702 if (len == 0 && cont == 0) {
704 * Received EOF. The remote host has closed the
707 snprintf(buf, sizeof buf,
708 "Connection to %.300s closed by remote host.\r\n",
710 buffer_append(&stderr_buffer, buf, strlen(buf));
715 * There is a kernel bug on Solaris that causes select to
716 * sometimes wake up even though there is no data available.
719 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
724 * An error has encountered. Perhaps there is a
727 snprintf(buf, sizeof buf,
728 "Read from remote host %.300s: %.100s\r\n",
729 host, strerror(errno));
730 buffer_append(&stderr_buffer, buf, strlen(buf));
734 packet_process_incoming(buf, len);
739 client_status_confirm(int type, Channel *c, void *ctx)
741 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
745 /* XXX supress on mux _client_ quietmode */
746 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
747 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
749 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
750 debug2("%s request accepted on channel %d",
751 cr->request_type, c->self);
752 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
754 snprintf(errmsg, sizeof(errmsg),
755 "%s request failed\r\n", cr->request_type);
757 snprintf(errmsg, sizeof(errmsg),
758 "%s request failed on channel %d",
759 cr->request_type, c->self);
761 /* If error occurred on primary session channel, then exit */
762 if (cr->do_close && c->self == session_ident)
764 /* If error occurred on mux client, append to their stderr */
766 buffer_append(&c->extended, errmsg, strlen(errmsg));
771 chan_write_failed(c);
778 client_abandon_status_confirm(Channel *c, void *ctx)
784 client_expect_confirm(int id, const char *request, int do_close)
786 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
788 cr->request_type = request;
789 cr->do_close = do_close;
791 channel_register_status_confirm(id, client_status_confirm,
792 client_abandon_status_confirm, cr);
796 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
798 struct global_confirm *gc, *last_gc;
800 /* Coalesce identical callbacks */
801 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
802 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
803 if (++last_gc->ref_count >= INT_MAX)
804 fatal("%s: last_gc->ref_count = %d",
805 __func__, last_gc->ref_count);
809 gc = xmalloc(sizeof(*gc));
813 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
817 process_cmdline(void)
819 void (*handler)(int);
820 char *s, *cmd, *cancel_host;
822 int local = 0, remote = 0, dynamic = 0;
826 bzero(&fwd, sizeof(fwd));
827 fwd.listen_host = fwd.connect_host = NULL;
829 leave_raw_mode(force_tty_flag);
830 handler = signal(SIGINT, SIG_IGN);
831 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
837 s++; /* Skip cmdline '-', if any */
841 if (*s == 'h' || *s == 'H' || *s == '?') {
843 logit(" -L[bind_address:]port:host:hostport "
844 "Request local forward");
845 logit(" -R[bind_address:]port:host:hostport "
846 "Request remote forward");
847 logit(" -D[bind_address:]port "
848 "Request dynamic forward");
849 logit(" -KR[bind_address:]port "
850 "Cancel remote forward");
851 if (!options.permit_local_command)
854 "Execute local command");
858 if (*s == '!' && options.permit_local_command) {
875 logit("Invalid command.");
879 if ((local || dynamic) && delete) {
880 logit("Not supported.");
883 if (remote && delete && !compat20) {
884 logit("Not supported for SSH protocol version 1.");
888 while (isspace(*++s))
891 /* XXX update list of forwards in options */
894 cancel_host = hpdelim(&s); /* may be NULL */
896 cancel_port = a2port(s);
897 cancel_host = cleanhostname(cancel_host);
899 cancel_port = a2port(cancel_host);
902 if (cancel_port <= 0) {
903 logit("Bad forwarding close port");
906 channel_request_rforward_cancel(cancel_host, cancel_port);
908 if (!parse_forward(&fwd, s, dynamic, remote)) {
909 logit("Bad forwarding specification.");
912 if (local || dynamic) {
913 if (channel_setup_local_fwd_listener(fwd.listen_host,
914 fwd.listen_port, fwd.connect_host,
915 fwd.connect_port, options.gateway_ports) < 0) {
916 logit("Port forwarding failed.");
920 if (channel_request_remote_forwarding(fwd.listen_host,
921 fwd.listen_port, fwd.connect_host,
922 fwd.connect_port) < 0) {
923 logit("Port forwarding failed.");
928 logit("Forwarding port.");
932 signal(SIGINT, handler);
933 enter_raw_mode(force_tty_flag);
936 if (fwd.listen_host != NULL)
937 xfree(fwd.listen_host);
938 if (fwd.connect_host != NULL)
939 xfree(fwd.connect_host);
943 * Process the characters one by one, call with c==NULL for proto1 case.
946 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
955 int *escape_pendingp, escape_char;
956 struct escape_filter_ctx *efc;
959 escape_pendingp = &escape_pending1;
960 escape_char = escape_char1;
962 if (c->filter_ctx == NULL)
964 efc = (struct escape_filter_ctx *)c->filter_ctx;
965 escape_pendingp = &efc->escape_pending;
966 escape_char = efc->escape_char;
972 for (i = 0; i < (u_int)len; i++) {
973 /* Get one character at a time. */
976 if (*escape_pendingp) {
977 /* We have previously seen an escape character. */
978 /* Clear the flag now. */
979 *escape_pendingp = 0;
981 /* Process the escaped character. */
984 /* Terminate the connection. */
985 snprintf(string, sizeof string, "%c.\r\n",
987 buffer_append(berr, string, strlen(string));
989 if (c && c->ctl_chan != -1) {
991 chan_write_failed(c);
998 /* XXX support this for mux clients */
999 if (c && c->ctl_chan != -1) {
1001 snprintf(string, sizeof string,
1002 "%c%c escape not available to "
1003 "multiplexed sessions\r\n",
1005 buffer_append(berr, string,
1009 /* Suspend the program. Inform the user */
1010 snprintf(string, sizeof string,
1011 "%c^Z [suspend ssh]\r\n", escape_char);
1012 buffer_append(berr, string, strlen(string));
1014 /* Restore terminal modes and suspend. */
1015 client_suspend_self(bin, bout, berr);
1017 /* We have been continued. */
1022 snprintf(string, sizeof string,
1023 "%cB\r\n", escape_char);
1024 buffer_append(berr, string,
1026 channel_request_start(session_ident,
1028 packet_put_int(1000);
1035 if (datafellows & SSH_BUG_NOREKEY)
1036 logit("Server does not "
1037 "support re-keying");
1044 if (c && c->ctl_chan != -1)
1047 * Detach the program (continue to serve
1048 * connections, but put in background and no
1049 * more new connections).
1051 /* Restore tty modes. */
1052 leave_raw_mode(force_tty_flag);
1054 /* Stop listening for new connections. */
1055 channel_stop_listening();
1057 snprintf(string, sizeof string,
1058 "%c& [backgrounded]\n", escape_char);
1059 buffer_append(berr, string, strlen(string));
1061 /* Fork into background. */
1064 error("fork: %.100s", strerror(errno));
1067 if (pid != 0) { /* This is the parent. */
1068 /* The parent just exits. */
1071 /* The child continues serving connections. */
1073 buffer_append(bin, "\004", 1);
1074 /* fake EOF on stdin */
1076 } else if (!stdin_eof) {
1078 * Sending SSH_CMSG_EOF alone does not
1079 * always appear to be enough. So we
1080 * try to send an EOF character first.
1082 packet_start(SSH_CMSG_STDIN_DATA);
1083 packet_put_string("\004", 1);
1087 if (buffer_len(bin) == 0) {
1088 packet_start(SSH_CMSG_EOF);
1095 if (c && c->ctl_chan != -1) {
1096 snprintf(string, sizeof string,
1098 Supported escape sequences:\r\n\
1099 %c. - terminate session\r\n\
1100 %cB - send a BREAK to the remote system\r\n\
1101 %cR - Request rekey (SSH protocol 2 only)\r\n\
1102 %c# - list forwarded connections\r\n\
1103 %c? - this message\r\n\
1104 %c%c - send the escape character by typing it twice\r\n\
1105 (Note that escapes are only recognized immediately after newline.)\r\n",
1106 escape_char, escape_char,
1107 escape_char, escape_char,
1108 escape_char, escape_char,
1109 escape_char, escape_char);
1111 snprintf(string, sizeof string,
1113 Supported escape sequences:\r\n\
1114 %c. - terminate connection (and any multiplexed sessions)\r\n\
1115 %cB - send a BREAK to the remote system\r\n\
1116 %cC - open a command line\r\n\
1117 %cR - Request rekey (SSH protocol 2 only)\r\n\
1118 %c^Z - suspend ssh\r\n\
1119 %c# - list forwarded connections\r\n\
1120 %c& - background ssh (when waiting for connections to terminate)\r\n\
1121 %c? - this message\r\n\
1122 %c%c - send the escape character by typing it twice\r\n\
1123 (Note that escapes are only recognized immediately after newline.)\r\n",
1124 escape_char, escape_char,
1125 escape_char, escape_char,
1126 escape_char, escape_char,
1127 escape_char, escape_char,
1128 escape_char, escape_char,
1131 buffer_append(berr, string, strlen(string));
1135 snprintf(string, sizeof string, "%c#\r\n",
1137 buffer_append(berr, string, strlen(string));
1138 s = channel_open_message();
1139 buffer_append(berr, s, strlen(s));
1144 if (c && c->ctl_chan != -1)
1150 if (ch != escape_char) {
1151 buffer_put_char(bin, escape_char);
1154 /* Escaped characters fall through here */
1159 * The previous character was not an escape char.
1160 * Check if this is an escape.
1162 if (last_was_cr && ch == escape_char) {
1164 * It is. Set the flag and continue to
1167 *escape_pendingp = 1;
1173 * Normal character. Record whether it was a newline,
1174 * and append it to the buffer.
1176 last_was_cr = (ch == '\r' || ch == '\n');
1177 buffer_put_char(bin, ch);
1184 client_process_input(fd_set *readset)
1187 char buf[SSH_IOBUFSZ];
1189 /* Read input from stdin. */
1190 if (FD_ISSET(fileno(stdin), readset)) {
1191 /* Read as much as possible. */
1192 len = read(fileno(stdin), buf, sizeof(buf));
1194 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1195 return; /* we'll try again later */
1198 * Received EOF or error. They are treated
1199 * similarly, except that an error message is printed
1200 * if it was an error condition.
1203 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1205 buffer_append(&stderr_buffer, buf, strlen(buf));
1207 /* Mark that we have seen EOF. */
1210 * Send an EOF message to the server unless there is
1211 * data in the buffer. If there is data in the
1212 * buffer, no message will be sent now. Code
1213 * elsewhere will send the EOF when the buffer
1214 * becomes empty if stdin_eof is set.
1216 if (buffer_len(&stdin_buffer) == 0) {
1217 packet_start(SSH_CMSG_EOF);
1220 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1222 * Normal successful read, and no escape character.
1223 * Just append the data to buffer.
1225 buffer_append(&stdin_buffer, buf, len);
1228 * Normal, successful read. But we have an escape
1229 * character and have to process the characters one
1232 if (process_escapes(NULL, &stdin_buffer,
1233 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1240 client_process_output(fd_set *writeset)
1245 /* Write buffered output to stdout. */
1246 if (FD_ISSET(fileno(stdout), writeset)) {
1247 /* Write as much data as possible. */
1248 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1249 buffer_len(&stdout_buffer));
1251 if (errno == EINTR || errno == EAGAIN ||
1252 errno == EWOULDBLOCK)
1256 * An error or EOF was encountered. Put an
1257 * error message to stderr buffer.
1259 snprintf(buf, sizeof buf,
1260 "write stdout: %.50s\r\n", strerror(errno));
1261 buffer_append(&stderr_buffer, buf, strlen(buf));
1266 /* Consume printed data from the buffer. */
1267 buffer_consume(&stdout_buffer, len);
1269 /* Write buffered output to stderr. */
1270 if (FD_ISSET(fileno(stderr), writeset)) {
1271 /* Write as much data as possible. */
1272 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1273 buffer_len(&stderr_buffer));
1275 if (errno == EINTR || errno == EAGAIN ||
1276 errno == EWOULDBLOCK)
1280 * EOF or error, but can't even print
1287 /* Consume printed characters from the buffer. */
1288 buffer_consume(&stderr_buffer, len);
1293 * Get packets from the connection input buffer, and process them as long as
1294 * there are packets available.
1296 * Any unknown packets received during the actual
1297 * session cause the session to terminate. This is
1298 * intended to make debugging easier since no
1299 * confirmations are sent. Any compatible protocol
1300 * extensions must be negotiated during the
1301 * preparatory phase.
1305 client_process_buffered_input_packets(void)
1307 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1308 compat20 ? xxx_kex : NULL);
1311 /* scan buf[] for '~' before sending data to the peer */
1313 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1315 client_new_escape_filter_ctx(int escape_char)
1317 struct escape_filter_ctx *ret;
1319 ret = xmalloc(sizeof(*ret));
1320 ret->escape_pending = 0;
1321 ret->escape_char = escape_char;
1325 /* Free the escape filter context on channel free */
1327 client_filter_cleanup(int cid, void *ctx)
1333 client_simple_escape_filter(Channel *c, char *buf, int len)
1335 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1338 return process_escapes(c, &c->input, &c->output, &c->extended,
1343 client_channel_closed(int id, void *arg)
1345 channel_cancel_cleanup(id);
1347 leave_raw_mode(force_tty_flag);
1351 * Implements the interactive session with the server. This is called after
1352 * the user has been authenticated, and a command has been started on the
1353 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1354 * used as an escape character for terminating or suspending the session.
1358 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1360 fd_set *readset = NULL, *writeset = NULL;
1361 double start_time, total_time;
1362 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1363 u_int64_t ibytes, obytes;
1367 debug("Entering interactive session.");
1369 start_time = get_current_time();
1371 /* Initialize variables. */
1372 escape_pending1 = 0;
1376 buffer_high = 64 * 1024;
1377 connection_in = packet_get_connection_in();
1378 connection_out = packet_get_connection_out();
1379 max_fd = MAX(connection_in, connection_out);
1382 /* enable nonblocking unless tty */
1383 if (!isatty(fileno(stdin)))
1384 set_nonblock(fileno(stdin));
1385 if (!isatty(fileno(stdout)))
1386 set_nonblock(fileno(stdout));
1387 if (!isatty(fileno(stderr)))
1388 set_nonblock(fileno(stderr));
1389 max_fd = MAX(max_fd, fileno(stdin));
1390 max_fd = MAX(max_fd, fileno(stdout));
1391 max_fd = MAX(max_fd, fileno(stderr));
1394 escape_char1 = escape_char_arg;
1396 /* Initialize buffers. */
1397 buffer_init(&stdin_buffer);
1398 buffer_init(&stdout_buffer);
1399 buffer_init(&stderr_buffer);
1401 client_init_dispatch();
1404 * Set signal handlers, (e.g. to restore non-blocking mode)
1405 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1407 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1408 signal(SIGHUP, signal_handler);
1409 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1410 signal(SIGINT, signal_handler);
1411 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1412 signal(SIGQUIT, signal_handler);
1413 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1414 signal(SIGTERM, signal_handler);
1415 signal(SIGWINCH, window_change_handler);
1418 enter_raw_mode(force_tty_flag);
1421 session_ident = ssh2_chan_id;
1422 if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1423 channel_register_filter(session_ident,
1424 client_simple_escape_filter, NULL,
1425 client_filter_cleanup,
1426 client_new_escape_filter_ctx(escape_char_arg));
1427 if (session_ident != -1)
1428 channel_register_cleanup(session_ident,
1429 client_channel_closed, 0);
1431 /* Check if we should immediately send eof on stdin. */
1432 client_check_initial_eof_on_stdin();
1435 /* Main loop of the client for the interactive session mode. */
1436 while (!quit_pending) {
1438 /* Process buffered packets sent by the server. */
1439 client_process_buffered_input_packets();
1441 if (compat20 && session_closed && !channel_still_open())
1444 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1447 debug("rekeying in progress");
1450 * Make packets of buffered stdin data, and buffer
1451 * them for sending to the server.
1454 client_make_packets_from_stdin_data();
1457 * Make packets from buffered channel data, and
1458 * enqueue them for sending to the server.
1460 if (packet_not_very_much_data_to_write())
1461 channel_output_poll();
1464 * Check if the window size has changed, and buffer a
1465 * message about it to the server if so.
1467 client_check_window_change();
1473 * Wait until we have something to do (something becomes
1474 * available on one of the descriptors).
1477 client_wait_until_can_do_something(&readset, &writeset,
1478 &max_fd2, &nalloc, rekeying);
1483 /* Do channel operations unless rekeying in progress. */
1485 channel_after_select(readset, writeset);
1486 if (need_rekeying || packet_need_rekeying()) {
1487 debug("need rekeying");
1489 kex_send_kexinit(xxx_kex);
1494 /* Buffer input from the connection. */
1495 client_process_net_input(readset);
1501 /* Buffer data from stdin */
1502 client_process_input(readset);
1504 * Process output to stdout and stderr. Output to
1505 * the connection is processed elsewhere (above).
1507 client_process_output(writeset);
1510 if (session_resumed) {
1511 connection_in = packet_get_connection_in();
1512 connection_out = packet_get_connection_out();
1513 max_fd = MAX(max_fd, connection_out);
1514 max_fd = MAX(max_fd, connection_in);
1515 session_resumed = 0;
1519 * Send as much buffered packet data as possible to the
1522 if (FD_ISSET(connection_out, writeset))
1523 packet_write_poll();
1526 * If we are a backgrounded control master, and the
1527 * timeout has expired without any active client
1528 * connections, then quit.
1530 if (control_persist_exit_time > 0) {
1531 if (time(NULL) >= control_persist_exit_time) {
1532 debug("ControlPersist timeout expired");
1542 /* Terminate the session. */
1544 /* Stop watching for window change. */
1545 signal(SIGWINCH, SIG_DFL);
1548 packet_start(SSH2_MSG_DISCONNECT);
1549 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1550 packet_put_cstring("disconnected by user");
1551 packet_put_cstring(""); /* language tag */
1553 packet_write_wait();
1559 leave_raw_mode(force_tty_flag);
1561 /* restore blocking io */
1562 if (!isatty(fileno(stdin)))
1563 unset_nonblock(fileno(stdin));
1564 if (!isatty(fileno(stdout)))
1565 unset_nonblock(fileno(stdout));
1566 if (!isatty(fileno(stderr)))
1567 unset_nonblock(fileno(stderr));
1570 * If there was no shell or command requested, there will be no remote
1571 * exit status to be returned. In that case, clear error code if the
1572 * connection was deliberately terminated at this end.
1574 if (no_shell_flag && received_signal == SIGTERM) {
1575 received_signal = 0;
1579 if (received_signal)
1580 fatal("Killed by signal %d.", (int) received_signal);
1583 * In interactive mode (with pseudo tty) display a message indicating
1584 * that the connection has been closed.
1586 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1587 snprintf(buf, sizeof buf,
1588 "Connection to %.64s closed.\r\n", host);
1589 buffer_append(&stderr_buffer, buf, strlen(buf));
1592 /* Output any buffered data for stdout. */
1593 if (buffer_len(&stdout_buffer) > 0) {
1594 len = atomicio(vwrite, fileno(stdout),
1595 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1596 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1597 error("Write failed flushing stdout buffer.");
1599 buffer_consume(&stdout_buffer, len);
1602 /* Output any buffered data for stderr. */
1603 if (buffer_len(&stderr_buffer) > 0) {
1604 len = atomicio(vwrite, fileno(stderr),
1605 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1606 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1607 error("Write failed flushing stderr buffer.");
1609 buffer_consume(&stderr_buffer, len);
1612 /* Clear and free any buffers. */
1613 memset(buf, 0, sizeof(buf));
1614 buffer_free(&stdin_buffer);
1615 buffer_free(&stdout_buffer);
1616 buffer_free(&stderr_buffer);
1618 /* Report bytes transferred, and transfer rates. */
1619 total_time = get_current_time() - start_time;
1620 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1621 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1622 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1623 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1625 verbose("Bytes per second: sent %.1f, received %.1f",
1626 obytes / total_time, ibytes / total_time);
1627 /* Return the exit status of the program. */
1628 debug("Exit status %d", exit_status);
1635 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1638 char *data = packet_get_string(&data_len);
1640 buffer_append(&stdout_buffer, data, data_len);
1641 memset(data, 0, data_len);
1645 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1648 char *data = packet_get_string(&data_len);
1650 buffer_append(&stderr_buffer, data, data_len);
1651 memset(data, 0, data_len);
1655 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1657 exit_status = packet_get_int();
1659 /* Acknowledge the exit. */
1660 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1663 * Must wait for packet to be sent since we are
1666 packet_write_wait();
1667 /* Flag that we want to exit. */
1671 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1674 int remote_id, sock;
1676 /* Read the remote channel number from the message. */
1677 remote_id = packet_get_int();
1681 * Get a connection to the local authentication agent (this may again
1684 sock = ssh_get_authentication_socket();
1687 * If we could not connect the agent, send an error message back to
1688 * the server. This should never happen unless the agent dies,
1689 * because authentication forwarding is only enabled if we have an
1693 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1694 -1, 0, 0, 0, "authentication agent connection", 1);
1695 c->remote_id = remote_id;
1699 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1700 packet_put_int(remote_id);
1702 /* Send a confirmation to the remote host. */
1703 debug("Forwarding authentication connection.");
1704 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1705 packet_put_int(remote_id);
1706 packet_put_int(c->self);
1712 client_request_forwarded_tcpip(const char *request_type, int rchan)
1715 char *listen_address, *originator_address;
1716 u_short listen_port, originator_port;
1718 /* Get rest of the packet */
1719 listen_address = packet_get_string(NULL);
1720 listen_port = packet_get_int();
1721 originator_address = packet_get_string(NULL);
1722 originator_port = packet_get_int();
1725 debug("client_request_forwarded_tcpip: listen %s port %d, "
1726 "originator %s port %d", listen_address, listen_port,
1727 originator_address, originator_port);
1729 c = channel_connect_by_listen_address(listen_port,
1730 "forwarded-tcpip", originator_address);
1732 xfree(originator_address);
1733 xfree(listen_address);
1738 client_request_x11(const char *request_type, int rchan)
1742 u_short originator_port;
1745 if (!options.forward_x11) {
1746 error("Warning: ssh server tried X11 forwarding.");
1747 error("Warning: this is probably a break-in attempt by a "
1748 "malicious server.");
1751 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1752 verbose("Rejected X11 connection after ForwardX11Timeout "
1756 originator = packet_get_string(NULL);
1757 if (datafellows & SSH_BUG_X11FWD) {
1758 debug2("buggy server: x11 request w/o originator_port");
1759 originator_port = 0;
1761 originator_port = packet_get_int();
1764 /* XXX check permission */
1765 debug("client_request_x11: request from %s %d", originator,
1768 sock = x11_connect_display();
1771 /* again is this really necessary for X11? */
1772 if (options.hpn_disabled)
1773 c = channel_new("x11",
1774 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1775 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1777 c = channel_new("x11",
1778 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1779 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
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,
1847 #if defined(SSH_TUN_FILTER)
1848 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1849 channel_register_filter(c->self, sys_tun_infilter,
1850 sys_tun_outfilter, NULL, NULL);
1853 packet_start(SSH2_MSG_CHANNEL_OPEN);
1854 packet_put_cstring("tun@openssh.com");
1855 packet_put_int(c->self);
1856 packet_put_int(c->local_window_max);
1857 packet_put_int(c->local_maxpacket);
1858 packet_put_int(tun_mode);
1859 packet_put_int(remote_tun);
1865 /* XXXX move to generic input handler */
1867 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1872 u_int rmaxpack, rwindow, len;
1874 ctype = packet_get_string(&len);
1875 rchan = packet_get_int();
1876 rwindow = packet_get_int();
1877 rmaxpack = packet_get_int();
1879 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1880 ctype, rchan, rwindow, rmaxpack);
1882 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1883 c = client_request_forwarded_tcpip(ctype, rchan);
1884 } else if (strcmp(ctype, "x11") == 0) {
1885 c = client_request_x11(ctype, rchan);
1886 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1887 c = client_request_agent(ctype, rchan);
1889 /* XXX duplicate : */
1891 debug("confirm %s", ctype);
1892 c->remote_id = rchan;
1893 c->remote_window = rwindow;
1894 c->remote_maxpacket = rmaxpack;
1895 if (c->type != SSH_CHANNEL_CONNECTING) {
1896 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1897 packet_put_int(c->remote_id);
1898 packet_put_int(c->self);
1899 packet_put_int(c->local_window);
1900 packet_put_int(c->local_maxpacket);
1904 debug("failure %s", ctype);
1905 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1906 packet_put_int(rchan);
1907 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1908 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1909 packet_put_cstring("open failed");
1910 packet_put_cstring("");
1917 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1920 int exitval, id, reply, success = 0;
1923 id = packet_get_int();
1924 rtype = packet_get_string(NULL);
1925 reply = packet_get_char();
1927 debug("client_input_channel_req: channel %d rtype %s reply %d",
1931 error("client_input_channel_req: request for channel -1");
1932 } else if ((c = channel_lookup(id)) == NULL) {
1933 error("client_input_channel_req: channel %d: "
1934 "unknown channel", id);
1935 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1938 } else if (strcmp(rtype, "exit-status") == 0) {
1939 exitval = packet_get_int();
1940 if (c->ctl_chan != -1) {
1941 mux_exit_message(c, exitval);
1943 } else if (id == session_ident) {
1944 /* Record exit value of local session */
1946 exit_status = exitval;
1948 /* Probably for a mux channel that has already closed */
1949 debug("%s: no sink for exit-status on channel %d",
1954 if (reply && c != NULL) {
1955 packet_start(success ?
1956 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1957 packet_put_int(c->remote_id);
1963 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1969 rtype = packet_get_string(NULL);
1970 want_reply = packet_get_char();
1971 debug("client_input_global_request: rtype %s want_reply %d",
1974 packet_start(success ?
1975 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1977 packet_write_wait();
1983 client_session2_setup(int id, int want_tty, int want_subsystem,
1984 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1989 debug2("%s: id %d", __func__, id);
1991 if ((c = channel_lookup(id)) == NULL)
1992 fatal("client_session2_setup: channel %d: unknown channel", id);
1994 packet_set_interactive(want_tty,
1995 options.ip_qos_interactive, options.ip_qos_bulk);
2000 /* Store window size in the packet. */
2001 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2002 memset(&ws, 0, sizeof(ws));
2004 channel_request_start(id, "pty-req", 1);
2005 client_expect_confirm(id, "PTY allocation", 1);
2006 packet_put_cstring(term != NULL ? term : "");
2007 packet_put_int((u_int)ws.ws_col);
2008 packet_put_int((u_int)ws.ws_row);
2009 packet_put_int((u_int)ws.ws_xpixel);
2010 packet_put_int((u_int)ws.ws_ypixel);
2012 tiop = get_saved_tio();
2013 tty_make_modes(-1, tiop);
2015 /* XXX wait for reply */
2019 /* Transfer any environment variables from client to server */
2020 if (options.num_send_env != 0 && env != NULL) {
2024 debug("Sending environment.");
2025 for (i = 0; env[i] != NULL; i++) {
2027 name = xstrdup(env[i]);
2028 if ((val = strchr(name, '=')) == NULL) {
2035 for (j = 0; j < options.num_send_env; j++) {
2036 if (match_pattern(name, options.send_env[j])) {
2042 debug3("Ignored env %s", name);
2047 debug("Sending env %s = %s", name, val);
2048 channel_request_start(id, "env", 0);
2049 packet_put_cstring(name);
2050 packet_put_cstring(val);
2056 len = buffer_len(cmd);
2060 if (want_subsystem) {
2061 debug("Sending subsystem: %.*s",
2062 len, (u_char*)buffer_ptr(cmd));
2063 channel_request_start(id, "subsystem", 1);
2064 client_expect_confirm(id, "subsystem", 1);
2066 debug("Sending command: %.*s",
2067 len, (u_char*)buffer_ptr(cmd));
2068 channel_request_start(id, "exec", 1);
2069 client_expect_confirm(id, "exec", 1);
2071 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2074 channel_request_start(id, "shell", 1);
2075 client_expect_confirm(id, "shell", 1);
2081 client_init_dispatch_20(void)
2083 dispatch_init(&dispatch_protocol_error);
2085 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2086 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2087 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2088 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2089 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2090 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2091 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2092 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2093 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2094 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2095 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2096 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2099 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2101 /* global request reply messages */
2102 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2103 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2107 client_init_dispatch_13(void)
2109 dispatch_init(NULL);
2110 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2111 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2112 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2113 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2114 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2115 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2116 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2117 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2118 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2120 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2121 &client_input_agent_open : &deny_input_open);
2122 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2123 &x11_input_open : &deny_input_open);
2127 client_init_dispatch_15(void)
2129 client_init_dispatch_13();
2130 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2131 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2135 client_init_dispatch(void)
2138 client_init_dispatch_20();
2140 client_init_dispatch_13();
2142 client_init_dispatch_15();
2145 /* client specific fatal cleanup */
2149 leave_raw_mode(force_tty_flag);
2150 leave_non_blocking();
2151 if (options.control_path != NULL && muxserver_sock != -1)
2152 unlink(options.control_path);
2153 ssh_kill_proxy_command();