1 /* $OpenBSD: clientloop.c,v 1.236 2011/06/22 22:08:42 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"
119 extern Options options;
121 /* Flag indicating that stdin should be redirected from /dev/null. */
122 extern int stdin_null_flag;
124 /* Flag indicating that no shell has been requested */
125 extern int no_shell_flag;
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
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;
184 enum confirm_action action;
187 /* Global request success/failure callbacks */
188 struct global_confirm {
189 TAILQ_ENTRY(global_confirm) entry;
190 global_confirm_cb *cb;
194 TAILQ_HEAD(global_confirms, global_confirm);
195 static struct global_confirms global_confirms =
196 TAILQ_HEAD_INITIALIZER(global_confirms);
201 void ssh_process_session2_setup(int, int, int, Buffer *);
203 /* Restores stdin to blocking mode. */
206 leave_non_blocking(void)
208 if (in_non_blocking_mode) {
209 unset_nonblock(fileno(stdin));
210 in_non_blocking_mode = 0;
214 /* Puts stdin terminal in non-blocking mode. */
217 enter_non_blocking(void)
219 in_non_blocking_mode = 1;
220 set_nonblock(fileno(stdin));
224 * Signal handler for the window change signal (SIGWINCH). This just sets a
225 * flag indicating that the window has changed.
229 window_change_handler(int sig)
231 received_window_change_signal = 1;
232 signal(SIGWINCH, window_change_handler);
236 * Signal handler for signals that cause the program to terminate. These
237 * signals must be trapped to restore terminal modes.
241 signal_handler(int sig)
243 received_signal = sig;
248 * Returns current time in seconds from Jan 1, 1970 with the maximum
249 * available resolution.
253 get_current_time(void)
256 gettimeofday(&tv, NULL);
257 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
261 * Sets control_persist_exit_time to the absolute time when the
262 * backgrounded control master should exit due to expiry of the
263 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
264 * control master process, or if there is no ControlPersist timeout.
267 set_control_persist_exit_time(void)
269 if (muxserver_sock == -1 || !options.control_persist
270 || options.control_persist_timeout == 0) {
271 /* not using a ControlPersist timeout */
272 control_persist_exit_time = 0;
273 } else if (channel_still_open()) {
274 /* some client connections are still open */
275 if (control_persist_exit_time > 0)
276 debug2("%s: cancel scheduled exit", __func__);
277 control_persist_exit_time = 0;
278 } else if (control_persist_exit_time <= 0) {
279 /* a client connection has recently closed */
280 control_persist_exit_time = time(NULL) +
281 (time_t)options.control_persist_timeout;
282 debug2("%s: schedule exit in %d seconds", __func__,
283 options.control_persist_timeout);
285 /* else we are already counting down to the timeout */
288 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
290 client_x11_get_proto(const char *display, const char *xauth_path,
291 u_int trusted, u_int timeout, char **_proto, char **_data)
296 static char proto[512], data[512];
298 int got_data = 0, generated = 0, do_unlink = 0, i;
299 char *xauthdir, *xauthfile;
303 xauthdir = xauthfile = NULL;
306 proto[0] = data[0] = '\0';
308 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
309 debug("No xauth program.");
311 if (display == NULL) {
312 debug("x11_get_proto: DISPLAY not set");
316 * Handle FamilyLocal case where $DISPLAY does
317 * not match an authorization entry. For this we
318 * just try "xauth list unix:displaynum.screennum".
319 * XXX: "localhost" match to determine FamilyLocal
322 if (strncmp(display, "localhost:", 10) == 0) {
323 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
328 xauthdir = xmalloc(MAXPATHLEN);
329 xauthfile = xmalloc(MAXPATHLEN);
330 mktemp_proto(xauthdir, MAXPATHLEN);
331 if (mkdtemp(xauthdir) != NULL) {
333 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
335 snprintf(cmd, sizeof(cmd),
336 "%s -f %s generate %s " SSH_X11_PROTO
337 " untrusted timeout %u 2>" _PATH_DEVNULL,
338 xauth_path, xauthfile, display, timeout);
339 debug2("x11_get_proto: %s", cmd);
340 if (system(cmd) == 0)
342 if (x11_refuse_time == 0) {
343 now = time(NULL) + 1;
344 if (UINT_MAX - timeout < now)
345 x11_refuse_time = UINT_MAX;
347 x11_refuse_time = now + timeout;
353 * When in untrusted mode, we read the cookie only if it was
354 * successfully generated as an untrusted one in the step
357 if (trusted || generated) {
358 snprintf(cmd, sizeof(cmd),
359 "%s %s%s list %s 2>" _PATH_DEVNULL,
361 generated ? "-f " : "" ,
362 generated ? xauthfile : "",
364 debug2("x11_get_proto: %s", cmd);
366 if (f && fgets(line, sizeof(line), f) &&
367 sscanf(line, "%*s %511s %511s", proto, data) == 2)
372 error("Warning: untrusted X11 forwarding setup failed: "
373 "xauth key data not generated");
386 * If we didn't get authentication data, just make up some
387 * data. The forwarding code will check the validity of the
388 * response anyway, and substitute this data. The X11
389 * server, however, will ignore this fake data and use
390 * whatever authentication mechanisms it was using otherwise
391 * for the local connection.
396 logit("Warning: No xauth data; "
397 "using fake authentication data for X11 forwarding.");
398 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
399 for (i = 0; i < 16; i++) {
402 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
410 * This is called when the interactive is entered. This checks if there is
411 * an EOF coming on stdin. We must check this explicitly, as select() does
412 * not appear to wake up when redirecting from /dev/null.
416 client_check_initial_eof_on_stdin(void)
422 * If standard input is to be "redirected from /dev/null", we simply
423 * mark that we have seen an EOF and send an EOF message to the
424 * server. Otherwise, we try to read a single character; it appears
425 * that for some files, such /dev/null, select() never wakes up for
426 * read for this descriptor, which means that we never get EOF. This
427 * way we will get the EOF if stdin comes from /dev/null or similar.
429 if (stdin_null_flag) {
430 /* Fake EOF on stdin. */
431 debug("Sending eof.");
433 packet_start(SSH_CMSG_EOF);
436 enter_non_blocking();
438 /* Check for immediate EOF on stdin. */
439 len = read(fileno(stdin), buf, 1);
442 * EOF. Record that we have seen it and send
445 debug("Sending eof.");
447 packet_start(SSH_CMSG_EOF);
449 } else if (len > 0) {
451 * Got data. We must store the data in the buffer,
452 * and also process it as an escape character if
455 if ((u_char) buf[0] == escape_char1)
458 buffer_append(&stdin_buffer, buf, 1);
460 leave_non_blocking();
466 * Make packets from buffered stdin data, and buffer them for sending to the
471 client_make_packets_from_stdin_data(void)
475 /* Send buffered stdin data to the server. */
476 while (buffer_len(&stdin_buffer) > 0 &&
477 packet_not_very_much_data_to_write()) {
478 len = buffer_len(&stdin_buffer);
479 /* Keep the packets at reasonable size. */
480 if (len > packet_get_maxsize())
481 len = packet_get_maxsize();
482 packet_start(SSH_CMSG_STDIN_DATA);
483 packet_put_string(buffer_ptr(&stdin_buffer), len);
485 buffer_consume(&stdin_buffer, len);
486 /* If we have a pending EOF, send it now. */
487 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
488 packet_start(SSH_CMSG_EOF);
495 * Checks if the client window has changed, and sends a packet about it to
496 * the server if so. The actual change is detected elsewhere (by a software
497 * interrupt on Unix); this just checks the flag and sends a message if
502 client_check_window_change(void)
506 if (! received_window_change_signal)
509 received_window_change_signal = 0;
511 debug2("client_check_window_change: changed");
514 channel_send_window_changes();
516 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
518 packet_start(SSH_CMSG_WINDOW_SIZE);
519 packet_put_int((u_int)ws.ws_row);
520 packet_put_int((u_int)ws.ws_col);
521 packet_put_int((u_int)ws.ws_xpixel);
522 packet_put_int((u_int)ws.ws_ypixel);
528 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
530 struct global_confirm *gc;
532 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
535 gc->cb(type, seq, gc->ctx);
536 if (--gc->ref_count <= 0) {
537 TAILQ_REMOVE(&global_confirms, gc, entry);
538 bzero(gc, sizeof(*gc));
542 packet_set_alive_timeouts(0);
546 server_alive_check(void)
548 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
549 logit("Timeout, server %s not responding.", host);
552 packet_start(SSH2_MSG_GLOBAL_REQUEST);
553 packet_put_cstring("keepalive@openssh.com");
554 packet_put_char(1); /* boolean: want reply */
556 /* Insert an empty placeholder to maintain ordering */
557 client_register_global_confirm(NULL, NULL);
561 * Waits until the client can do something (some data becomes available on
562 * one of the file descriptors).
565 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
566 int *maxfdp, u_int *nallocp, int rekeying)
568 struct timeval tv, *tvp;
572 /* Add any selections by the channel mechanism. */
573 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
576 /* Read from the connection, unless our buffers are full. */
577 if (buffer_len(&stdout_buffer) < buffer_high &&
578 buffer_len(&stderr_buffer) < buffer_high &&
579 channel_not_very_much_buffered_data())
580 FD_SET(connection_in, *readsetp);
582 * Read from stdin, unless we have seen EOF or have very much
583 * buffered data to send to the server.
585 if (!stdin_eof && packet_not_very_much_data_to_write())
586 FD_SET(fileno(stdin), *readsetp);
588 /* Select stdout/stderr if have data in buffer. */
589 if (buffer_len(&stdout_buffer) > 0)
590 FD_SET(fileno(stdout), *writesetp);
591 if (buffer_len(&stderr_buffer) > 0)
592 FD_SET(fileno(stderr), *writesetp);
594 /* channel_prepare_select could have closed the last channel */
595 if (session_closed && !channel_still_open() &&
596 !packet_have_data_to_write()) {
597 /* clear mask since we did not call select() */
598 memset(*readsetp, 0, *nallocp);
599 memset(*writesetp, 0, *nallocp);
602 FD_SET(connection_in, *readsetp);
606 /* Select server connection if have data to write to the server. */
607 if (packet_have_data_to_write())
608 FD_SET(connection_out, *writesetp);
611 * Wait for something to happen. This will suspend the process until
612 * some selected descriptor can be read, written, or has some other
613 * event pending, or a timeout expires.
616 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
617 if (options.server_alive_interval > 0 && compat20)
618 timeout_secs = options.server_alive_interval;
619 set_control_persist_exit_time();
620 if (control_persist_exit_time > 0) {
621 timeout_secs = MIN(timeout_secs,
622 control_persist_exit_time - time(NULL));
623 if (timeout_secs < 0)
626 if (timeout_secs == INT_MAX)
629 tv.tv_sec = timeout_secs;
634 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
639 * We have to clear the select masks, because we return.
640 * We have to return, because the mainloop checks for the flags
641 * set by the signal handlers.
643 memset(*readsetp, 0, *nallocp);
644 memset(*writesetp, 0, *nallocp);
648 /* Note: we might still have data in the buffers. */
649 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
650 buffer_append(&stderr_buffer, buf, strlen(buf));
653 server_alive_check();
657 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
659 /* Flush stdout and stderr buffers. */
660 if (buffer_len(bout) > 0)
661 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
663 if (buffer_len(berr) > 0)
664 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
667 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
670 * Free (and clear) the buffer to reduce the amount of data that gets
677 /* Send the suspend signal to the program itself. */
678 kill(getpid(), SIGTSTP);
680 /* Reset window sizes in case they have changed */
681 received_window_change_signal = 1;
683 /* OK, we have been continued by the user. Reinitialize buffers. */
688 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
692 client_process_net_input(fd_set *readset)
695 char buf[SSH_IOBUFSZ];
698 * Read input from the server, and add any such data to the buffer of
699 * the packet subsystem.
701 if (FD_ISSET(connection_in, readset)) {
702 /* Read as much as possible. */
703 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
704 if (len == 0 && cont == 0) {
706 * Received EOF. The remote host has closed the
709 snprintf(buf, sizeof buf,
710 "Connection to %.300s closed by remote host.\r\n",
712 buffer_append(&stderr_buffer, buf, strlen(buf));
717 * There is a kernel bug on Solaris that causes select to
718 * sometimes wake up even though there is no data available.
721 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
726 * An error has encountered. Perhaps there is a
729 snprintf(buf, sizeof buf,
730 "Read from remote host %.300s: %.100s\r\n",
731 host, strerror(errno));
732 buffer_append(&stderr_buffer, buf, strlen(buf));
736 packet_process_incoming(buf, len);
741 client_status_confirm(int type, Channel *c, void *ctx)
743 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
748 * If a TTY was explicitly requested, then a failure to allocate
751 if (cr->action == CONFIRM_TTY &&
752 (options.request_tty == REQUEST_TTY_FORCE ||
753 options.request_tty == REQUEST_TTY_YES))
754 cr->action = CONFIRM_CLOSE;
756 /* XXX supress on mux _client_ quietmode */
757 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
758 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
760 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
761 debug2("%s request accepted on channel %d",
762 cr->request_type, c->self);
763 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
765 snprintf(errmsg, sizeof(errmsg),
766 "%s request failed\r\n", cr->request_type);
768 snprintf(errmsg, sizeof(errmsg),
769 "%s request failed on channel %d",
770 cr->request_type, c->self);
772 /* If error occurred on primary session channel, then exit */
773 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
776 * If error occurred on mux client, append to
780 buffer_append(&c->extended, errmsg,
784 if (cr->action == CONFIRM_TTY) {
786 * If a TTY allocation error occurred, then arrange
787 * for the correct TTY to leave raw mode.
789 if (c->self == session_ident)
792 mux_tty_alloc_failed(c);
793 } else if (cr->action == CONFIRM_CLOSE) {
795 chan_write_failed(c);
802 client_abandon_status_confirm(Channel *c, void *ctx)
808 client_expect_confirm(int id, const char *request,
809 enum confirm_action action)
811 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
813 cr->request_type = request;
816 channel_register_status_confirm(id, client_status_confirm,
817 client_abandon_status_confirm, cr);
821 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
823 struct global_confirm *gc, *last_gc;
825 /* Coalesce identical callbacks */
826 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
827 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
828 if (++last_gc->ref_count >= INT_MAX)
829 fatal("%s: last_gc->ref_count = %d",
830 __func__, last_gc->ref_count);
834 gc = xmalloc(sizeof(*gc));
838 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
842 process_cmdline(void)
844 void (*handler)(int);
845 char *s, *cmd, *cancel_host;
847 int local = 0, remote = 0, dynamic = 0;
851 bzero(&fwd, sizeof(fwd));
852 fwd.listen_host = fwd.connect_host = NULL;
854 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
855 handler = signal(SIGINT, SIG_IGN);
856 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
862 s++; /* Skip cmdline '-', if any */
866 if (*s == 'h' || *s == 'H' || *s == '?') {
868 logit(" -L[bind_address:]port:host:hostport "
869 "Request local forward");
870 logit(" -R[bind_address:]port:host:hostport "
871 "Request remote forward");
872 logit(" -D[bind_address:]port "
873 "Request dynamic forward");
874 logit(" -KR[bind_address:]port "
875 "Cancel remote forward");
876 if (!options.permit_local_command)
879 "Execute local command");
883 if (*s == '!' && options.permit_local_command) {
900 logit("Invalid command.");
904 if ((local || dynamic) && delete) {
905 logit("Not supported.");
908 if (remote && delete && !compat20) {
909 logit("Not supported for SSH protocol version 1.");
913 while (isspace(*++s))
916 /* XXX update list of forwards in options */
919 cancel_host = hpdelim(&s); /* may be NULL */
921 cancel_port = a2port(s);
922 cancel_host = cleanhostname(cancel_host);
924 cancel_port = a2port(cancel_host);
927 if (cancel_port <= 0) {
928 logit("Bad forwarding close port");
931 channel_request_rforward_cancel(cancel_host, cancel_port);
933 if (!parse_forward(&fwd, s, dynamic, remote)) {
934 logit("Bad forwarding specification.");
937 if (local || dynamic) {
938 if (channel_setup_local_fwd_listener(fwd.listen_host,
939 fwd.listen_port, fwd.connect_host,
940 fwd.connect_port, options.gateway_ports) < 0) {
941 logit("Port forwarding failed.");
945 if (channel_request_remote_forwarding(fwd.listen_host,
946 fwd.listen_port, fwd.connect_host,
947 fwd.connect_port) < 0) {
948 logit("Port forwarding failed.");
953 logit("Forwarding port.");
957 signal(SIGINT, handler);
958 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
961 if (fwd.listen_host != NULL)
962 xfree(fwd.listen_host);
963 if (fwd.connect_host != NULL)
964 xfree(fwd.connect_host);
968 * Process the characters one by one, call with c==NULL for proto1 case.
971 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
980 int *escape_pendingp, escape_char;
981 struct escape_filter_ctx *efc;
984 escape_pendingp = &escape_pending1;
985 escape_char = escape_char1;
987 if (c->filter_ctx == NULL)
989 efc = (struct escape_filter_ctx *)c->filter_ctx;
990 escape_pendingp = &efc->escape_pending;
991 escape_char = efc->escape_char;
997 for (i = 0; i < (u_int)len; i++) {
998 /* Get one character at a time. */
1001 if (*escape_pendingp) {
1002 /* We have previously seen an escape character. */
1003 /* Clear the flag now. */
1004 *escape_pendingp = 0;
1006 /* Process the escaped character. */
1009 /* Terminate the connection. */
1010 snprintf(string, sizeof string, "%c.\r\n",
1012 buffer_append(berr, string, strlen(string));
1014 if (c && c->ctl_chan != -1) {
1015 chan_read_failed(c);
1016 chan_write_failed(c);
1023 /* XXX support this for mux clients */
1024 if (c && c->ctl_chan != -1) {
1026 snprintf(string, sizeof string,
1027 "%c%c escape not available to "
1028 "multiplexed sessions\r\n",
1030 buffer_append(berr, string,
1034 /* Suspend the program. Inform the user */
1035 snprintf(string, sizeof string,
1036 "%c^Z [suspend ssh]\r\n", escape_char);
1037 buffer_append(berr, string, strlen(string));
1039 /* Restore terminal modes and suspend. */
1040 client_suspend_self(bin, bout, berr);
1042 /* We have been continued. */
1047 snprintf(string, sizeof string,
1048 "%cB\r\n", escape_char);
1049 buffer_append(berr, string,
1051 channel_request_start(session_ident,
1053 packet_put_int(1000);
1060 if (datafellows & SSH_BUG_NOREKEY)
1061 logit("Server does not "
1062 "support re-keying");
1069 if (c && c->ctl_chan != -1)
1072 * Detach the program (continue to serve
1073 * connections, but put in background and no
1074 * more new connections).
1076 /* Restore tty modes. */
1078 options.request_tty == REQUEST_TTY_FORCE);
1080 /* Stop listening for new connections. */
1081 channel_stop_listening();
1083 snprintf(string, sizeof string,
1084 "%c& [backgrounded]\n", escape_char);
1085 buffer_append(berr, string, strlen(string));
1087 /* Fork into background. */
1090 error("fork: %.100s", strerror(errno));
1093 if (pid != 0) { /* This is the parent. */
1094 /* The parent just exits. */
1097 /* The child continues serving connections. */
1099 buffer_append(bin, "\004", 1);
1100 /* fake EOF on stdin */
1102 } else if (!stdin_eof) {
1104 * Sending SSH_CMSG_EOF alone does not
1105 * always appear to be enough. So we
1106 * try to send an EOF character first.
1108 packet_start(SSH_CMSG_STDIN_DATA);
1109 packet_put_string("\004", 1);
1113 if (buffer_len(bin) == 0) {
1114 packet_start(SSH_CMSG_EOF);
1121 if (c && c->ctl_chan != -1) {
1122 snprintf(string, sizeof string,
1124 Supported escape sequences:\r\n\
1125 %c. - terminate session\r\n\
1126 %cB - send a BREAK to the remote system\r\n\
1127 %cR - Request rekey (SSH protocol 2 only)\r\n\
1128 %c# - list forwarded connections\r\n\
1129 %c? - this message\r\n\
1130 %c%c - send the escape character by typing it twice\r\n\
1131 (Note that escapes are only recognized immediately after newline.)\r\n",
1132 escape_char, escape_char,
1133 escape_char, escape_char,
1134 escape_char, escape_char,
1135 escape_char, escape_char);
1137 snprintf(string, sizeof string,
1139 Supported escape sequences:\r\n\
1140 %c. - terminate connection (and any multiplexed sessions)\r\n\
1141 %cB - send a BREAK to the remote system\r\n\
1142 %cC - open a command line\r\n\
1143 %cR - Request rekey (SSH protocol 2 only)\r\n\
1144 %c^Z - suspend ssh\r\n\
1145 %c# - list forwarded connections\r\n\
1146 %c& - background ssh (when waiting for connections to terminate)\r\n\
1147 %c? - this message\r\n\
1148 %c%c - send the escape character by typing it twice\r\n\
1149 (Note that escapes are only recognized immediately after newline.)\r\n",
1150 escape_char, escape_char,
1151 escape_char, escape_char,
1152 escape_char, escape_char,
1153 escape_char, escape_char,
1154 escape_char, escape_char,
1157 buffer_append(berr, string, strlen(string));
1161 snprintf(string, sizeof string, "%c#\r\n",
1163 buffer_append(berr, string, strlen(string));
1164 s = channel_open_message();
1165 buffer_append(berr, s, strlen(s));
1170 if (c && c->ctl_chan != -1)
1176 if (ch != escape_char) {
1177 buffer_put_char(bin, escape_char);
1180 /* Escaped characters fall through here */
1185 * The previous character was not an escape char.
1186 * Check if this is an escape.
1188 if (last_was_cr && ch == escape_char) {
1190 * It is. Set the flag and continue to
1193 *escape_pendingp = 1;
1199 * Normal character. Record whether it was a newline,
1200 * and append it to the buffer.
1202 last_was_cr = (ch == '\r' || ch == '\n');
1203 buffer_put_char(bin, ch);
1210 client_process_input(fd_set *readset)
1213 char buf[SSH_IOBUFSZ];
1215 /* Read input from stdin. */
1216 if (FD_ISSET(fileno(stdin), readset)) {
1217 /* Read as much as possible. */
1218 len = read(fileno(stdin), buf, sizeof(buf));
1220 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1221 return; /* we'll try again later */
1224 * Received EOF or error. They are treated
1225 * similarly, except that an error message is printed
1226 * if it was an error condition.
1229 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1231 buffer_append(&stderr_buffer, buf, strlen(buf));
1233 /* Mark that we have seen EOF. */
1236 * Send an EOF message to the server unless there is
1237 * data in the buffer. If there is data in the
1238 * buffer, no message will be sent now. Code
1239 * elsewhere will send the EOF when the buffer
1240 * becomes empty if stdin_eof is set.
1242 if (buffer_len(&stdin_buffer) == 0) {
1243 packet_start(SSH_CMSG_EOF);
1246 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1248 * Normal successful read, and no escape character.
1249 * Just append the data to buffer.
1251 buffer_append(&stdin_buffer, buf, len);
1254 * Normal, successful read. But we have an escape
1255 * character and have to process the characters one
1258 if (process_escapes(NULL, &stdin_buffer,
1259 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1266 client_process_output(fd_set *writeset)
1271 /* Write buffered output to stdout. */
1272 if (FD_ISSET(fileno(stdout), writeset)) {
1273 /* Write as much data as possible. */
1274 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1275 buffer_len(&stdout_buffer));
1277 if (errno == EINTR || errno == EAGAIN ||
1278 errno == EWOULDBLOCK)
1282 * An error or EOF was encountered. Put an
1283 * error message to stderr buffer.
1285 snprintf(buf, sizeof buf,
1286 "write stdout: %.50s\r\n", strerror(errno));
1287 buffer_append(&stderr_buffer, buf, strlen(buf));
1292 /* Consume printed data from the buffer. */
1293 buffer_consume(&stdout_buffer, len);
1295 /* Write buffered output to stderr. */
1296 if (FD_ISSET(fileno(stderr), writeset)) {
1297 /* Write as much data as possible. */
1298 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1299 buffer_len(&stderr_buffer));
1301 if (errno == EINTR || errno == EAGAIN ||
1302 errno == EWOULDBLOCK)
1306 * EOF or error, but can't even print
1313 /* Consume printed characters from the buffer. */
1314 buffer_consume(&stderr_buffer, len);
1319 * Get packets from the connection input buffer, and process them as long as
1320 * there are packets available.
1322 * Any unknown packets received during the actual
1323 * session cause the session to terminate. This is
1324 * intended to make debugging easier since no
1325 * confirmations are sent. Any compatible protocol
1326 * extensions must be negotiated during the
1327 * preparatory phase.
1331 client_process_buffered_input_packets(void)
1333 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1334 compat20 ? xxx_kex : NULL);
1337 /* scan buf[] for '~' before sending data to the peer */
1339 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1341 client_new_escape_filter_ctx(int escape_char)
1343 struct escape_filter_ctx *ret;
1345 ret = xmalloc(sizeof(*ret));
1346 ret->escape_pending = 0;
1347 ret->escape_char = escape_char;
1351 /* Free the escape filter context on channel free */
1353 client_filter_cleanup(int cid, void *ctx)
1359 client_simple_escape_filter(Channel *c, char *buf, int len)
1361 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1364 return process_escapes(c, &c->input, &c->output, &c->extended,
1369 client_channel_closed(int id, void *arg)
1371 channel_cancel_cleanup(id);
1373 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1377 * Implements the interactive session with the server. This is called after
1378 * the user has been authenticated, and a command has been started on the
1379 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1380 * used as an escape character for terminating or suspending the session.
1384 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1386 fd_set *readset = NULL, *writeset = NULL;
1387 double start_time, total_time;
1388 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1389 u_int64_t ibytes, obytes;
1393 debug("Entering interactive session.");
1395 start_time = get_current_time();
1397 /* Initialize variables. */
1398 escape_pending1 = 0;
1402 buffer_high = 64 * 1024;
1403 connection_in = packet_get_connection_in();
1404 connection_out = packet_get_connection_out();
1405 max_fd = MAX(connection_in, connection_out);
1408 /* enable nonblocking unless tty */
1409 if (!isatty(fileno(stdin)))
1410 set_nonblock(fileno(stdin));
1411 if (!isatty(fileno(stdout)))
1412 set_nonblock(fileno(stdout));
1413 if (!isatty(fileno(stderr)))
1414 set_nonblock(fileno(stderr));
1415 max_fd = MAX(max_fd, fileno(stdin));
1416 max_fd = MAX(max_fd, fileno(stdout));
1417 max_fd = MAX(max_fd, fileno(stderr));
1420 escape_char1 = escape_char_arg;
1422 /* Initialize buffers. */
1423 buffer_init(&stdin_buffer);
1424 buffer_init(&stdout_buffer);
1425 buffer_init(&stderr_buffer);
1427 client_init_dispatch();
1430 * Set signal handlers, (e.g. to restore non-blocking mode)
1431 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1433 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1434 signal(SIGHUP, signal_handler);
1435 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1436 signal(SIGINT, signal_handler);
1437 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1438 signal(SIGQUIT, signal_handler);
1439 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1440 signal(SIGTERM, signal_handler);
1441 signal(SIGWINCH, window_change_handler);
1444 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1447 session_ident = ssh2_chan_id;
1448 if (session_ident != -1) {
1449 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1450 channel_register_filter(session_ident,
1451 client_simple_escape_filter, NULL,
1452 client_filter_cleanup,
1453 client_new_escape_filter_ctx(
1456 channel_register_cleanup(session_ident,
1457 client_channel_closed, 0);
1460 /* Check if we should immediately send eof on stdin. */
1461 client_check_initial_eof_on_stdin();
1464 /* Main loop of the client for the interactive session mode. */
1465 while (!quit_pending) {
1467 /* Process buffered packets sent by the server. */
1468 client_process_buffered_input_packets();
1470 if (compat20 && session_closed && !channel_still_open())
1473 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1476 debug("rekeying in progress");
1479 * Make packets of buffered stdin data, and buffer
1480 * them for sending to the server.
1483 client_make_packets_from_stdin_data();
1486 * Make packets from buffered channel data, and
1487 * enqueue them for sending to the server.
1489 if (packet_not_very_much_data_to_write())
1490 channel_output_poll();
1493 * Check if the window size has changed, and buffer a
1494 * message about it to the server if so.
1496 client_check_window_change();
1502 * Wait until we have something to do (something becomes
1503 * available on one of the descriptors).
1506 client_wait_until_can_do_something(&readset, &writeset,
1507 &max_fd2, &nalloc, rekeying);
1512 /* Do channel operations unless rekeying in progress. */
1514 channel_after_select(readset, writeset);
1517 if (options.gss_renewal_rekey &&
1518 ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
1519 debug("credentials updated - forcing rekey");
1524 if (need_rekeying || packet_need_rekeying()) {
1525 debug("need rekeying");
1527 kex_send_kexinit(xxx_kex);
1532 /* Buffer input from the connection. */
1533 client_process_net_input(readset);
1539 /* Buffer data from stdin */
1540 client_process_input(readset);
1542 * Process output to stdout and stderr. Output to
1543 * the connection is processed elsewhere (above).
1545 client_process_output(writeset);
1548 if (session_resumed) {
1549 connection_in = packet_get_connection_in();
1550 connection_out = packet_get_connection_out();
1551 max_fd = MAX(max_fd, connection_out);
1552 max_fd = MAX(max_fd, connection_in);
1553 session_resumed = 0;
1557 * Send as much buffered packet data as possible to the
1560 if (FD_ISSET(connection_out, writeset))
1561 packet_write_poll();
1564 * If we are a backgrounded control master, and the
1565 * timeout has expired without any active client
1566 * connections, then quit.
1568 if (control_persist_exit_time > 0) {
1569 if (time(NULL) >= control_persist_exit_time) {
1570 debug("ControlPersist timeout expired");
1580 /* Terminate the session. */
1582 /* Stop watching for window change. */
1583 signal(SIGWINCH, SIG_DFL);
1586 packet_start(SSH2_MSG_DISCONNECT);
1587 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1588 packet_put_cstring("disconnected by user");
1589 packet_put_cstring(""); /* language tag */
1591 packet_write_wait();
1597 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1599 /* restore blocking io */
1600 if (!isatty(fileno(stdin)))
1601 unset_nonblock(fileno(stdin));
1602 if (!isatty(fileno(stdout)))
1603 unset_nonblock(fileno(stdout));
1604 if (!isatty(fileno(stderr)))
1605 unset_nonblock(fileno(stderr));
1608 * If there was no shell or command requested, there will be no remote
1609 * exit status to be returned. In that case, clear error code if the
1610 * connection was deliberately terminated at this end.
1612 if (no_shell_flag && received_signal == SIGTERM) {
1613 received_signal = 0;
1617 if (received_signal)
1618 fatal("Killed by signal %d.", (int) received_signal);
1621 * In interactive mode (with pseudo tty) display a message indicating
1622 * that the connection has been closed.
1624 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1625 snprintf(buf, sizeof buf,
1626 "Connection to %.64s closed.\r\n", host);
1627 buffer_append(&stderr_buffer, buf, strlen(buf));
1630 /* Output any buffered data for stdout. */
1631 if (buffer_len(&stdout_buffer) > 0) {
1632 len = atomicio(vwrite, fileno(stdout),
1633 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1634 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1635 error("Write failed flushing stdout buffer.");
1637 buffer_consume(&stdout_buffer, len);
1640 /* Output any buffered data for stderr. */
1641 if (buffer_len(&stderr_buffer) > 0) {
1642 len = atomicio(vwrite, fileno(stderr),
1643 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1644 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1645 error("Write failed flushing stderr buffer.");
1647 buffer_consume(&stderr_buffer, len);
1650 /* Clear and free any buffers. */
1651 memset(buf, 0, sizeof(buf));
1652 buffer_free(&stdin_buffer);
1653 buffer_free(&stdout_buffer);
1654 buffer_free(&stderr_buffer);
1656 /* Report bytes transferred, and transfer rates. */
1657 total_time = get_current_time() - start_time;
1658 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1659 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1660 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1661 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1663 verbose("Bytes per second: sent %.1f, received %.1f",
1664 obytes / total_time, ibytes / total_time);
1665 /* Return the exit status of the program. */
1666 debug("Exit status %d", exit_status);
1673 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1676 char *data = packet_get_string(&data_len);
1678 buffer_append(&stdout_buffer, data, data_len);
1679 memset(data, 0, data_len);
1683 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1686 char *data = packet_get_string(&data_len);
1688 buffer_append(&stderr_buffer, data, data_len);
1689 memset(data, 0, data_len);
1693 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1695 exit_status = packet_get_int();
1697 /* Acknowledge the exit. */
1698 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1701 * Must wait for packet to be sent since we are
1704 packet_write_wait();
1705 /* Flag that we want to exit. */
1709 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1712 int remote_id, sock;
1714 /* Read the remote channel number from the message. */
1715 remote_id = packet_get_int();
1719 * Get a connection to the local authentication agent (this may again
1722 sock = ssh_get_authentication_socket();
1725 * If we could not connect the agent, send an error message back to
1726 * the server. This should never happen unless the agent dies,
1727 * because authentication forwarding is only enabled if we have an
1731 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1732 -1, 0, 0, 0, "authentication agent connection", 1);
1733 c->remote_id = remote_id;
1737 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1738 packet_put_int(remote_id);
1740 /* Send a confirmation to the remote host. */
1741 debug("Forwarding authentication connection.");
1742 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1743 packet_put_int(remote_id);
1744 packet_put_int(c->self);
1750 client_request_forwarded_tcpip(const char *request_type, int rchan)
1753 char *listen_address, *originator_address;
1754 u_short listen_port, originator_port;
1756 /* Get rest of the packet */
1757 listen_address = packet_get_string(NULL);
1758 listen_port = packet_get_int();
1759 originator_address = packet_get_string(NULL);
1760 originator_port = packet_get_int();
1763 debug("client_request_forwarded_tcpip: listen %s port %d, "
1764 "originator %s port %d", listen_address, listen_port,
1765 originator_address, originator_port);
1767 c = channel_connect_by_listen_address(listen_port,
1768 "forwarded-tcpip", originator_address);
1770 xfree(originator_address);
1771 xfree(listen_address);
1776 client_request_x11(const char *request_type, int rchan)
1780 u_short originator_port;
1783 if (!options.forward_x11) {
1784 error("Warning: ssh server tried X11 forwarding.");
1785 error("Warning: this is probably a break-in attempt by a "
1786 "malicious server.");
1789 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1790 verbose("Rejected X11 connection after ForwardX11Timeout "
1794 originator = packet_get_string(NULL);
1795 if (datafellows & SSH_BUG_X11FWD) {
1796 debug2("buggy server: x11 request w/o originator_port");
1797 originator_port = 0;
1799 originator_port = packet_get_int();
1802 /* XXX check permission */
1803 debug("client_request_x11: request from %s %d", originator,
1806 sock = x11_connect_display();
1809 c = channel_new("x11",
1810 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1811 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1817 client_request_agent(const char *request_type, int rchan)
1822 if (!options.forward_agent) {
1823 error("Warning: ssh server tried agent forwarding.");
1824 error("Warning: this is probably a break-in attempt by a "
1825 "malicious server.");
1828 sock = ssh_get_authentication_socket();
1831 c = channel_new("authentication agent connection",
1832 SSH_CHANNEL_OPEN, sock, sock, -1,
1833 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1834 "authentication agent connection", 1);
1840 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1845 if (tun_mode == SSH_TUNMODE_NO)
1849 error("Tunnel forwarding is not supported for protocol 1");
1853 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1855 /* Open local tunnel device */
1856 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1857 error("Tunnel device open failed.");
1861 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1862 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1865 #if defined(SSH_TUN_FILTER)
1866 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1867 channel_register_filter(c->self, sys_tun_infilter,
1868 sys_tun_outfilter, NULL, NULL);
1871 packet_start(SSH2_MSG_CHANNEL_OPEN);
1872 packet_put_cstring("tun@openssh.com");
1873 packet_put_int(c->self);
1874 packet_put_int(c->local_window_max);
1875 packet_put_int(c->local_maxpacket);
1876 packet_put_int(tun_mode);
1877 packet_put_int(remote_tun);
1883 /* XXXX move to generic input handler */
1885 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1890 u_int rmaxpack, rwindow, len;
1892 ctype = packet_get_string(&len);
1893 rchan = packet_get_int();
1894 rwindow = packet_get_int();
1895 rmaxpack = packet_get_int();
1897 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1898 ctype, rchan, rwindow, rmaxpack);
1900 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1901 c = client_request_forwarded_tcpip(ctype, rchan);
1902 } else if (strcmp(ctype, "x11") == 0) {
1903 c = client_request_x11(ctype, rchan);
1904 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1905 c = client_request_agent(ctype, rchan);
1907 /* XXX duplicate : */
1909 debug("confirm %s", ctype);
1910 c->remote_id = rchan;
1911 c->remote_window = rwindow;
1912 c->remote_maxpacket = rmaxpack;
1913 if (c->type != SSH_CHANNEL_CONNECTING) {
1914 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1915 packet_put_int(c->remote_id);
1916 packet_put_int(c->self);
1917 packet_put_int(c->local_window);
1918 packet_put_int(c->local_maxpacket);
1922 debug("failure %s", ctype);
1923 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1924 packet_put_int(rchan);
1925 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1926 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1927 packet_put_cstring("open failed");
1928 packet_put_cstring("");
1935 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1938 int exitval, id, reply, success = 0;
1941 id = packet_get_int();
1942 rtype = packet_get_string(NULL);
1943 reply = packet_get_char();
1945 debug("client_input_channel_req: channel %d rtype %s reply %d",
1949 error("client_input_channel_req: request for channel -1");
1950 } else if ((c = channel_lookup(id)) == NULL) {
1951 error("client_input_channel_req: channel %d: "
1952 "unknown channel", id);
1953 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1956 } else if (strcmp(rtype, "exit-status") == 0) {
1957 exitval = packet_get_int();
1958 if (c->ctl_chan != -1) {
1959 mux_exit_message(c, exitval);
1961 } else if (id == session_ident) {
1962 /* Record exit value of local session */
1964 exit_status = exitval;
1966 /* Probably for a mux channel that has already closed */
1967 debug("%s: no sink for exit-status on channel %d",
1972 if (reply && c != NULL) {
1973 packet_start(success ?
1974 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1975 packet_put_int(c->remote_id);
1981 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1987 rtype = packet_get_string(NULL);
1988 want_reply = packet_get_char();
1989 debug("client_input_global_request: rtype %s want_reply %d",
1992 packet_start(success ?
1993 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1995 packet_write_wait();
2001 client_session2_setup(int id, int want_tty, int want_subsystem,
2002 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2007 debug2("%s: id %d", __func__, id);
2009 if ((c = channel_lookup(id)) == NULL)
2010 fatal("client_session2_setup: channel %d: unknown channel", id);
2012 packet_set_interactive(want_tty,
2013 options.ip_qos_interactive, options.ip_qos_bulk);
2018 /* Store window size in the packet. */
2019 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2020 memset(&ws, 0, sizeof(ws));
2022 channel_request_start(id, "pty-req", 1);
2023 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2024 packet_put_cstring(term != NULL ? term : "");
2025 packet_put_int((u_int)ws.ws_col);
2026 packet_put_int((u_int)ws.ws_row);
2027 packet_put_int((u_int)ws.ws_xpixel);
2028 packet_put_int((u_int)ws.ws_ypixel);
2030 tiop = get_saved_tio();
2031 tty_make_modes(-1, tiop);
2033 /* XXX wait for reply */
2037 /* Transfer any environment variables from client to server */
2038 if (options.num_send_env != 0 && env != NULL) {
2042 debug("Sending environment.");
2043 for (i = 0; env[i] != NULL; i++) {
2045 name = xstrdup(env[i]);
2046 if ((val = strchr(name, '=')) == NULL) {
2053 for (j = 0; j < options.num_send_env; j++) {
2054 if (match_pattern(name, options.send_env[j])) {
2060 debug3("Ignored env %s", name);
2065 debug("Sending env %s = %s", name, val);
2066 channel_request_start(id, "env", 0);
2067 packet_put_cstring(name);
2068 packet_put_cstring(val);
2074 len = buffer_len(cmd);
2078 if (want_subsystem) {
2079 debug("Sending subsystem: %.*s",
2080 len, (u_char*)buffer_ptr(cmd));
2081 channel_request_start(id, "subsystem", 1);
2082 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2084 debug("Sending command: %.*s",
2085 len, (u_char*)buffer_ptr(cmd));
2086 channel_request_start(id, "exec", 1);
2087 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2089 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2092 channel_request_start(id, "shell", 1);
2093 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2099 client_init_dispatch_20(void)
2101 dispatch_init(&dispatch_protocol_error);
2103 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2104 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2105 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2106 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2107 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2108 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2109 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2110 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2111 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2112 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2113 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2114 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2117 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2119 /* global request reply messages */
2120 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2121 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2125 client_init_dispatch_13(void)
2127 dispatch_init(NULL);
2128 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2129 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2130 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2131 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2132 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2133 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2134 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2135 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2136 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2138 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2139 &client_input_agent_open : &deny_input_open);
2140 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2141 &x11_input_open : &deny_input_open);
2145 client_init_dispatch_15(void)
2147 client_init_dispatch_13();
2148 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2149 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2153 client_init_dispatch(void)
2156 client_init_dispatch_20();
2158 client_init_dispatch_13();
2160 client_init_dispatch_15();
2164 client_stop_mux(void)
2166 if (options.control_path != NULL && muxserver_sock != -1)
2167 unlink(options.control_path);
2169 * If we are in persist mode, signal that we should close when all
2170 * active channels are closed.
2172 if (options.control_persist) {
2174 setproctitle("[stopped mux]");
2178 /* client specific fatal cleanup */
2182 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2183 leave_non_blocking();
2184 if (options.control_path != NULL && muxserver_sock != -1)
2185 unlink(options.control_path);
2186 ssh_kill_proxy_command();