1 /* $OpenBSD: clientloop.c,v 1.274 2015/07/01 02:26:31 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/param.h> /* MIN MAX */
65 #include <sys/types.h>
66 #include <sys/ioctl.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>
90 #include "openbsd-compat/sys-queue.h"
105 #include "readconf.h"
106 #include "clientloop.h"
107 #include "sshconnect.h"
109 #include "atomicio.h"
115 #include "hostfile.h"
118 extern Options options;
120 /* Flag indicating that stdin should be redirected from /dev/null. */
121 extern int stdin_null_flag;
123 /* Flag indicating that no shell has been requested */
124 extern int no_shell_flag;
127 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
130 * Name of the host we are connecting to. This is the name given on the
131 * command line, or the HostName specified for the user-supplied name in a
132 * configuration file.
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 u_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;
183 enum confirm_action action;
186 /* Global request success/failure callbacks */
187 struct global_confirm {
188 TAILQ_ENTRY(global_confirm) entry;
189 global_confirm_cb *cb;
193 TAILQ_HEAD(global_confirms, global_confirm);
194 static struct global_confirms global_confirms =
195 TAILQ_HEAD_INITIALIZER(global_confirms);
197 void ssh_process_session2_setup(int, int, int, Buffer *);
199 /* Restores stdin to blocking mode. */
202 leave_non_blocking(void)
204 if (in_non_blocking_mode) {
205 unset_nonblock(fileno(stdin));
206 in_non_blocking_mode = 0;
210 /* Puts stdin terminal in non-blocking mode. */
213 enter_non_blocking(void)
215 in_non_blocking_mode = 1;
216 set_nonblock(fileno(stdin));
220 * Signal handler for the window change signal (SIGWINCH). This just sets a
221 * flag indicating that the window has changed.
225 window_change_handler(int sig)
227 received_window_change_signal = 1;
228 signal(SIGWINCH, window_change_handler);
232 * Signal handler for signals that cause the program to terminate. These
233 * signals must be trapped to restore terminal modes.
237 signal_handler(int sig)
239 received_signal = sig;
244 * Returns current time in seconds from Jan 1, 1970 with the maximum
245 * available resolution.
249 get_current_time(void)
252 gettimeofday(&tv, NULL);
253 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
257 * Sets control_persist_exit_time to the absolute time when the
258 * backgrounded control master should exit due to expiry of the
259 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
260 * control master process, or if there is no ControlPersist timeout.
263 set_control_persist_exit_time(void)
265 if (muxserver_sock == -1 || !options.control_persist
266 || options.control_persist_timeout == 0) {
267 /* not using a ControlPersist timeout */
268 control_persist_exit_time = 0;
269 } else if (channel_still_open()) {
270 /* some client connections are still open */
271 if (control_persist_exit_time > 0)
272 debug2("%s: cancel scheduled exit", __func__);
273 control_persist_exit_time = 0;
274 } else if (control_persist_exit_time <= 0) {
275 /* a client connection has recently closed */
276 control_persist_exit_time = monotime() +
277 (time_t)options.control_persist_timeout;
278 debug2("%s: schedule exit in %d seconds", __func__,
279 options.control_persist_timeout);
281 /* else we are already counting down to the timeout */
284 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
286 client_x11_display_valid(const char *display)
290 dlen = strlen(display);
291 for (i = 0; i < dlen; i++) {
292 if (!isalnum((u_char)display[i]) &&
293 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
294 debug("Invalid character '%c' in DISPLAY", display[i]);
301 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
302 #define X11_TIMEOUT_SLACK 60
304 client_x11_get_proto(const char *display, const char *xauth_path,
305 u_int trusted, u_int timeout, char **_proto, char **_data)
310 static char proto[512], data[512];
312 int got_data = 0, generated = 0, do_unlink = 0, i;
313 char *xauthdir, *xauthfile;
315 u_int now, x11_timeout_real;
317 xauthdir = xauthfile = NULL;
320 proto[0] = data[0] = '\0';
322 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
323 debug("No xauth program.");
324 } else if (!client_x11_display_valid(display)) {
325 logit("DISPLAY '%s' invalid, falling back to fake xauth data",
328 if (display == NULL) {
329 debug("x11_get_proto: DISPLAY not set");
333 * Handle FamilyLocal case where $DISPLAY does
334 * not match an authorization entry. For this we
335 * just try "xauth list unix:displaynum.screennum".
336 * XXX: "localhost" match to determine FamilyLocal
339 if (strncmp(display, "localhost:", 10) == 0) {
340 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
345 xauthdir = xmalloc(PATH_MAX);
346 xauthfile = xmalloc(PATH_MAX);
347 mktemp_proto(xauthdir, PATH_MAX);
349 * The authentication cookie should briefly outlive
350 * ssh's willingness to forward X11 connections to
351 * avoid nasty fail-open behaviour in the X server.
353 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
354 x11_timeout_real = UINT_MAX;
356 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
357 if (mkdtemp(xauthdir) != NULL) {
359 snprintf(xauthfile, PATH_MAX, "%s/xauthfile",
361 snprintf(cmd, sizeof(cmd),
362 "%s -f %s generate %s " SSH_X11_PROTO
363 " untrusted timeout %u 2>" _PATH_DEVNULL,
364 xauth_path, xauthfile, display,
366 debug2("x11_get_proto: %s", cmd);
367 if (x11_refuse_time == 0) {
368 now = monotime() + 1;
369 if (UINT_MAX - timeout < now)
370 x11_refuse_time = UINT_MAX;
372 x11_refuse_time = now + timeout;
373 channel_set_x11_refuse_time(
376 if (system(cmd) == 0)
382 * When in untrusted mode, we read the cookie only if it was
383 * successfully generated as an untrusted one in the step
386 if (trusted || generated) {
387 snprintf(cmd, sizeof(cmd),
388 "%s %s%s list %s 2>" _PATH_DEVNULL,
390 generated ? "-f " : "" ,
391 generated ? xauthfile : "",
393 debug2("x11_get_proto: %s", cmd);
395 if (f && fgets(line, sizeof(line), f) &&
396 sscanf(line, "%*s %511s %511s", proto, data) == 2)
401 error("Warning: untrusted X11 forwarding setup failed: "
402 "xauth key data not generated");
413 * If we didn't get authentication data, just make up some
414 * data. The forwarding code will check the validity of the
415 * response anyway, and substitute this data. The X11
416 * server, however, will ignore this fake data and use
417 * whatever authentication mechanisms it was using otherwise
418 * for the local connection.
423 logit("Warning: No xauth data; "
424 "using fake authentication data for X11 forwarding.");
425 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
426 for (i = 0; i < 16; i++) {
429 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
437 * This is called when the interactive is entered. This checks if there is
438 * an EOF coming on stdin. We must check this explicitly, as select() does
439 * not appear to wake up when redirecting from /dev/null.
443 client_check_initial_eof_on_stdin(void)
449 * If standard input is to be "redirected from /dev/null", we simply
450 * mark that we have seen an EOF and send an EOF message to the
451 * server. Otherwise, we try to read a single character; it appears
452 * that for some files, such /dev/null, select() never wakes up for
453 * read for this descriptor, which means that we never get EOF. This
454 * way we will get the EOF if stdin comes from /dev/null or similar.
456 if (stdin_null_flag) {
457 /* Fake EOF on stdin. */
458 debug("Sending eof.");
460 packet_start(SSH_CMSG_EOF);
463 enter_non_blocking();
465 /* Check for immediate EOF on stdin. */
466 len = read(fileno(stdin), buf, 1);
469 * EOF. Record that we have seen it and send
472 debug("Sending eof.");
474 packet_start(SSH_CMSG_EOF);
476 } else if (len > 0) {
478 * Got data. We must store the data in the buffer,
479 * and also process it as an escape character if
482 if ((u_char) buf[0] == escape_char1)
485 buffer_append(&stdin_buffer, buf, 1);
487 leave_non_blocking();
493 * Make packets from buffered stdin data, and buffer them for sending to the
498 client_make_packets_from_stdin_data(void)
502 /* Send buffered stdin data to the server. */
503 while (buffer_len(&stdin_buffer) > 0 &&
504 packet_not_very_much_data_to_write()) {
505 len = buffer_len(&stdin_buffer);
506 /* Keep the packets at reasonable size. */
507 if (len > packet_get_maxsize())
508 len = packet_get_maxsize();
509 packet_start(SSH_CMSG_STDIN_DATA);
510 packet_put_string(buffer_ptr(&stdin_buffer), len);
512 buffer_consume(&stdin_buffer, len);
513 /* If we have a pending EOF, send it now. */
514 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
515 packet_start(SSH_CMSG_EOF);
522 * Checks if the client window has changed, and sends a packet about it to
523 * the server if so. The actual change is detected elsewhere (by a software
524 * interrupt on Unix); this just checks the flag and sends a message if
529 client_check_window_change(void)
533 if (! received_window_change_signal)
536 received_window_change_signal = 0;
538 debug2("client_check_window_change: changed");
541 channel_send_window_changes();
543 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
545 packet_start(SSH_CMSG_WINDOW_SIZE);
546 packet_put_int((u_int)ws.ws_row);
547 packet_put_int((u_int)ws.ws_col);
548 packet_put_int((u_int)ws.ws_xpixel);
549 packet_put_int((u_int)ws.ws_ypixel);
555 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
557 struct global_confirm *gc;
559 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
562 gc->cb(type, seq, gc->ctx);
563 if (--gc->ref_count <= 0) {
564 TAILQ_REMOVE(&global_confirms, gc, entry);
565 explicit_bzero(gc, sizeof(*gc));
569 packet_set_alive_timeouts(0);
574 server_alive_check(void)
576 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
577 logit("Timeout, server %s not responding.", host);
580 packet_start(SSH2_MSG_GLOBAL_REQUEST);
581 packet_put_cstring("keepalive@openssh.com");
582 packet_put_char(1); /* boolean: want reply */
584 /* Insert an empty placeholder to maintain ordering */
585 client_register_global_confirm(NULL, NULL);
589 * Waits until the client can do something (some data becomes available on
590 * one of the file descriptors).
593 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
594 int *maxfdp, u_int *nallocp, int rekeying)
596 struct timeval tv, *tvp;
598 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
601 /* Add any selections by the channel mechanism. */
602 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
603 &minwait_secs, rekeying);
606 /* Read from the connection, unless our buffers are full. */
607 if (buffer_len(&stdout_buffer) < buffer_high &&
608 buffer_len(&stderr_buffer) < buffer_high &&
609 channel_not_very_much_buffered_data())
610 FD_SET(connection_in, *readsetp);
612 * Read from stdin, unless we have seen EOF or have very much
613 * buffered data to send to the server.
615 if (!stdin_eof && packet_not_very_much_data_to_write())
616 FD_SET(fileno(stdin), *readsetp);
618 /* Select stdout/stderr if have data in buffer. */
619 if (buffer_len(&stdout_buffer) > 0)
620 FD_SET(fileno(stdout), *writesetp);
621 if (buffer_len(&stderr_buffer) > 0)
622 FD_SET(fileno(stderr), *writesetp);
624 /* channel_prepare_select could have closed the last channel */
625 if (session_closed && !channel_still_open() &&
626 !packet_have_data_to_write()) {
627 /* clear mask since we did not call select() */
628 memset(*readsetp, 0, *nallocp);
629 memset(*writesetp, 0, *nallocp);
632 FD_SET(connection_in, *readsetp);
636 /* Select server connection if have data to write to the server. */
637 if (packet_have_data_to_write())
638 FD_SET(connection_out, *writesetp);
641 * Wait for something to happen. This will suspend the process until
642 * some selected descriptor can be read, written, or has some other
643 * event pending, or a timeout expires.
646 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
647 if (options.server_alive_interval > 0 && compat20) {
648 timeout_secs = options.server_alive_interval;
649 server_alive_time = now + options.server_alive_interval;
651 if (options.rekey_interval > 0 && compat20 && !rekeying)
652 timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
653 set_control_persist_exit_time();
654 if (control_persist_exit_time > 0) {
655 timeout_secs = MIN(timeout_secs,
656 control_persist_exit_time - now);
657 if (timeout_secs < 0)
660 if (minwait_secs != 0)
661 timeout_secs = MIN(timeout_secs, (int)minwait_secs);
662 if (timeout_secs == INT_MAX)
665 tv.tv_sec = timeout_secs;
670 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
675 * We have to clear the select masks, because we return.
676 * We have to return, because the mainloop checks for the flags
677 * set by the signal handlers.
679 memset(*readsetp, 0, *nallocp);
680 memset(*writesetp, 0, *nallocp);
684 /* Note: we might still have data in the buffers. */
685 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
686 buffer_append(&stderr_buffer, buf, strlen(buf));
688 } else if (ret == 0) {
690 * Timeout. Could have been either keepalive or rekeying.
691 * Keepalive we check here, rekeying is checked in clientloop.
693 if (server_alive_time != 0 && server_alive_time <= monotime())
694 server_alive_check();
700 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
702 /* Flush stdout and stderr buffers. */
703 if (buffer_len(bout) > 0)
704 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
706 if (buffer_len(berr) > 0)
707 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
710 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
713 * Free (and clear) the buffer to reduce the amount of data that gets
720 /* Send the suspend signal to the program itself. */
721 kill(getpid(), SIGTSTP);
723 /* Reset window sizes in case they have changed */
724 received_window_change_signal = 1;
726 /* OK, we have been continued by the user. Reinitialize buffers. */
731 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
735 client_process_net_input(fd_set *readset)
738 char buf[SSH_IOBUFSZ];
741 * Read input from the server, and add any such data to the buffer of
742 * the packet subsystem.
744 if (FD_ISSET(connection_in, readset)) {
745 /* Read as much as possible. */
746 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
747 if (len == 0 && cont == 0) {
749 * Received EOF. The remote host has closed the
752 snprintf(buf, sizeof buf,
753 "Connection to %.300s closed by remote host.\r\n",
755 buffer_append(&stderr_buffer, buf, strlen(buf));
760 * There is a kernel bug on Solaris that causes select to
761 * sometimes wake up even though there is no data available.
764 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
769 * An error has encountered. Perhaps there is a
772 snprintf(buf, sizeof buf,
773 "Read from remote host %.300s: %.100s\r\n",
774 host, strerror(errno));
775 buffer_append(&stderr_buffer, buf, strlen(buf));
779 packet_process_incoming(buf, len);
784 client_status_confirm(int type, Channel *c, void *ctx)
786 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
791 * If a TTY was explicitly requested, then a failure to allocate
794 if (cr->action == CONFIRM_TTY &&
795 (options.request_tty == REQUEST_TTY_FORCE ||
796 options.request_tty == REQUEST_TTY_YES))
797 cr->action = CONFIRM_CLOSE;
799 /* XXX supress on mux _client_ quietmode */
800 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
801 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
803 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
804 debug2("%s request accepted on channel %d",
805 cr->request_type, c->self);
806 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
808 snprintf(errmsg, sizeof(errmsg),
809 "%s request failed\r\n", cr->request_type);
811 snprintf(errmsg, sizeof(errmsg),
812 "%s request failed on channel %d",
813 cr->request_type, c->self);
815 /* If error occurred on primary session channel, then exit */
816 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
819 * If error occurred on mux client, append to
823 buffer_append(&c->extended, errmsg,
827 if (cr->action == CONFIRM_TTY) {
829 * If a TTY allocation error occurred, then arrange
830 * for the correct TTY to leave raw mode.
832 if (c->self == session_ident)
835 mux_tty_alloc_failed(c);
836 } else if (cr->action == CONFIRM_CLOSE) {
838 chan_write_failed(c);
845 client_abandon_status_confirm(Channel *c, void *ctx)
851 client_expect_confirm(int id, const char *request,
852 enum confirm_action action)
854 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
856 cr->request_type = request;
859 channel_register_status_confirm(id, client_status_confirm,
860 client_abandon_status_confirm, cr);
864 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
866 struct global_confirm *gc, *last_gc;
868 /* Coalesce identical callbacks */
869 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
870 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
871 if (++last_gc->ref_count >= INT_MAX)
872 fatal("%s: last_gc->ref_count = %d",
873 __func__, last_gc->ref_count);
877 gc = xcalloc(1, sizeof(*gc));
881 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
885 process_cmdline(void)
887 void (*handler)(int);
889 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
892 memset(&fwd, 0, sizeof(fwd));
894 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
895 handler = signal(SIGINT, SIG_IGN);
896 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
899 while (isspace((u_char)*s))
902 s++; /* Skip cmdline '-', if any */
906 if (*s == 'h' || *s == 'H' || *s == '?') {
908 logit(" -L[bind_address:]port:host:hostport "
909 "Request local forward");
910 logit(" -R[bind_address:]port:host:hostport "
911 "Request remote forward");
912 logit(" -D[bind_address:]port "
913 "Request dynamic forward");
914 logit(" -KL[bind_address:]port "
915 "Cancel local forward");
916 logit(" -KR[bind_address:]port "
917 "Cancel remote forward");
918 logit(" -KD[bind_address:]port "
919 "Cancel dynamic forward");
920 if (!options.permit_local_command)
923 "Execute local command");
927 if (*s == '!' && options.permit_local_command) {
944 logit("Invalid command.");
948 if (delete && !compat20) {
949 logit("Not supported for SSH protocol version 1.");
953 while (isspace((u_char)*++s))
956 /* XXX update list of forwards in options */
958 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
959 if (!parse_forward(&fwd, s, 1, 0)) {
960 logit("Bad forwarding close specification.");
964 ok = channel_request_rforward_cancel(&fwd) == 0;
966 ok = channel_cancel_lport_listener(&fwd,
967 0, &options.fwd_opts) > 0;
969 ok = channel_cancel_lport_listener(&fwd,
970 CHANNEL_CANCEL_PORT_STATIC,
971 &options.fwd_opts) > 0;
973 logit("Unkown port forwarding.");
976 logit("Canceled forwarding.");
978 if (!parse_forward(&fwd, s, dynamic, remote)) {
979 logit("Bad forwarding specification.");
982 if (local || dynamic) {
983 if (!channel_setup_local_fwd_listener(&fwd,
984 &options.fwd_opts)) {
985 logit("Port forwarding failed.");
989 if (channel_request_remote_forwarding(&fwd) < 0) {
990 logit("Port forwarding failed.");
994 logit("Forwarding port.");
998 signal(SIGINT, handler);
999 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1001 free(fwd.listen_host);
1002 free(fwd.listen_path);
1003 free(fwd.connect_host);
1004 free(fwd.connect_path);
1007 /* reasons to suppress output of an escape command in help output */
1008 #define SUPPRESS_NEVER 0 /* never suppress, always show */
1009 #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
1010 #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
1011 #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
1012 #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
1013 struct escape_help_text {
1018 static struct escape_help_text esc_txt[] = {
1019 {".", "terminate session", SUPPRESS_MUXMASTER},
1020 {".", "terminate connection (and any multiplexed sessions)",
1021 SUPPRESS_MUXCLIENT},
1022 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
1023 {"C", "open a command line", SUPPRESS_MUXCLIENT},
1024 {"R", "request rekey", SUPPRESS_PROTO1},
1025 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1026 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1027 {"#", "list forwarded connections", SUPPRESS_NEVER},
1028 {"&", "background ssh (when waiting for connections to terminate)",
1029 SUPPRESS_MUXCLIENT},
1030 {"?", "this message", SUPPRESS_NEVER},
1034 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1037 unsigned int i, suppress_flags;
1040 snprintf(string, sizeof string, "%c?\r\n"
1041 "Supported escape sequences:\r\n", escape_char);
1042 buffer_append(b, string, strlen(string));
1044 suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1045 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1046 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1047 (using_stderr ? 0 : SUPPRESS_SYSLOG);
1049 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1050 if (esc_txt[i].flags & suppress_flags)
1052 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1053 escape_char, esc_txt[i].cmd, esc_txt[i].text);
1054 buffer_append(b, string, strlen(string));
1057 snprintf(string, sizeof string,
1058 " %c%c - send the escape character by typing it twice\r\n"
1059 "(Note that escapes are only recognized immediately after "
1060 "newline.)\r\n", escape_char, escape_char);
1061 buffer_append(b, string, strlen(string));
1065 * Process the characters one by one, call with c==NULL for proto1 case.
1068 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1077 int *escape_pendingp, escape_char;
1078 struct escape_filter_ctx *efc;
1081 escape_pendingp = &escape_pending1;
1082 escape_char = escape_char1;
1084 if (c->filter_ctx == NULL)
1086 efc = (struct escape_filter_ctx *)c->filter_ctx;
1087 escape_pendingp = &efc->escape_pending;
1088 escape_char = efc->escape_char;
1094 for (i = 0; i < (u_int)len; i++) {
1095 /* Get one character at a time. */
1098 if (*escape_pendingp) {
1099 /* We have previously seen an escape character. */
1100 /* Clear the flag now. */
1101 *escape_pendingp = 0;
1103 /* Process the escaped character. */
1106 /* Terminate the connection. */
1107 snprintf(string, sizeof string, "%c.\r\n",
1109 buffer_append(berr, string, strlen(string));
1111 if (c && c->ctl_chan != -1) {
1112 chan_read_failed(c);
1113 chan_write_failed(c);
1115 c->detach_user(c->self, NULL);
1116 c->type = SSH_CHANNEL_ABANDONED;
1117 buffer_clear(&c->input);
1125 /* XXX support this for mux clients */
1126 if (c && c->ctl_chan != -1) {
1130 snprintf(b, sizeof b, "^Z");
1132 snprintf(b, sizeof b, "%c", ch);
1133 snprintf(string, sizeof string,
1134 "%c%s escape not available to "
1135 "multiplexed sessions\r\n",
1137 buffer_append(berr, string,
1141 /* Suspend the program. Inform the user */
1142 snprintf(string, sizeof string,
1143 "%c^Z [suspend ssh]\r\n", escape_char);
1144 buffer_append(berr, string, strlen(string));
1146 /* Restore terminal modes and suspend. */
1147 client_suspend_self(bin, bout, berr);
1149 /* We have been continued. */
1154 snprintf(string, sizeof string,
1155 "%cB\r\n", escape_char);
1156 buffer_append(berr, string,
1158 channel_request_start(c->self,
1160 packet_put_int(1000);
1167 if (datafellows & SSH_BUG_NOREKEY)
1168 logit("Server does not "
1169 "support re-keying");
1178 if (c && c->ctl_chan != -1)
1180 if (!log_is_on_stderr()) {
1181 snprintf(string, sizeof string,
1182 "%c%c [Logging to syslog]\r\n",
1184 buffer_append(berr, string,
1188 if (ch == 'V' && options.log_level >
1190 log_change_level(--options.log_level);
1191 if (ch == 'v' && options.log_level <
1192 SYSLOG_LEVEL_DEBUG3)
1193 log_change_level(++options.log_level);
1194 snprintf(string, sizeof string,
1195 "%c%c [LogLevel %s]\r\n", escape_char, ch,
1196 log_level_name(options.log_level));
1197 buffer_append(berr, string, strlen(string));
1201 if (c && c->ctl_chan != -1)
1204 * Detach the program (continue to serve
1205 * connections, but put in background and no
1206 * more new connections).
1208 /* Restore tty modes. */
1210 options.request_tty == REQUEST_TTY_FORCE);
1212 /* Stop listening for new connections. */
1213 channel_stop_listening();
1215 snprintf(string, sizeof string,
1216 "%c& [backgrounded]\n", escape_char);
1217 buffer_append(berr, string, strlen(string));
1219 /* Fork into background. */
1222 error("fork: %.100s", strerror(errno));
1225 if (pid != 0) { /* This is the parent. */
1226 /* The parent just exits. */
1229 /* The child continues serving connections. */
1231 buffer_append(bin, "\004", 1);
1232 /* fake EOF on stdin */
1234 } else if (!stdin_eof) {
1236 * Sending SSH_CMSG_EOF alone does not
1237 * always appear to be enough. So we
1238 * try to send an EOF character first.
1240 packet_start(SSH_CMSG_STDIN_DATA);
1241 packet_put_string("\004", 1);
1245 if (buffer_len(bin) == 0) {
1246 packet_start(SSH_CMSG_EOF);
1253 print_escape_help(berr, escape_char, compat20,
1254 (c && c->ctl_chan != -1),
1255 log_is_on_stderr());
1259 snprintf(string, sizeof string, "%c#\r\n",
1261 buffer_append(berr, string, strlen(string));
1262 s = channel_open_message();
1263 buffer_append(berr, s, strlen(s));
1268 if (c && c->ctl_chan != -1)
1274 if (ch != escape_char) {
1275 buffer_put_char(bin, escape_char);
1278 /* Escaped characters fall through here */
1283 * The previous character was not an escape char.
1284 * Check if this is an escape.
1286 if (last_was_cr && ch == escape_char) {
1288 * It is. Set the flag and continue to
1291 *escape_pendingp = 1;
1297 * Normal character. Record whether it was a newline,
1298 * and append it to the buffer.
1300 last_was_cr = (ch == '\r' || ch == '\n');
1301 buffer_put_char(bin, ch);
1308 client_process_input(fd_set *readset)
1311 char buf[SSH_IOBUFSZ];
1313 /* Read input from stdin. */
1314 if (FD_ISSET(fileno(stdin), readset)) {
1315 /* Read as much as possible. */
1316 len = read(fileno(stdin), buf, sizeof(buf));
1318 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1319 return; /* we'll try again later */
1322 * Received EOF or error. They are treated
1323 * similarly, except that an error message is printed
1324 * if it was an error condition.
1327 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1329 buffer_append(&stderr_buffer, buf, strlen(buf));
1331 /* Mark that we have seen EOF. */
1334 * Send an EOF message to the server unless there is
1335 * data in the buffer. If there is data in the
1336 * buffer, no message will be sent now. Code
1337 * elsewhere will send the EOF when the buffer
1338 * becomes empty if stdin_eof is set.
1340 if (buffer_len(&stdin_buffer) == 0) {
1341 packet_start(SSH_CMSG_EOF);
1344 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1346 * Normal successful read, and no escape character.
1347 * Just append the data to buffer.
1349 buffer_append(&stdin_buffer, buf, len);
1352 * Normal, successful read. But we have an escape
1353 * character and have to process the characters one
1356 if (process_escapes(NULL, &stdin_buffer,
1357 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1364 client_process_output(fd_set *writeset)
1369 /* Write buffered output to stdout. */
1370 if (FD_ISSET(fileno(stdout), writeset)) {
1371 /* Write as much data as possible. */
1372 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1373 buffer_len(&stdout_buffer));
1375 if (errno == EINTR || errno == EAGAIN ||
1376 errno == EWOULDBLOCK)
1380 * An error or EOF was encountered. Put an
1381 * error message to stderr buffer.
1383 snprintf(buf, sizeof buf,
1384 "write stdout: %.50s\r\n", strerror(errno));
1385 buffer_append(&stderr_buffer, buf, strlen(buf));
1390 /* Consume printed data from the buffer. */
1391 buffer_consume(&stdout_buffer, len);
1393 /* Write buffered output to stderr. */
1394 if (FD_ISSET(fileno(stderr), writeset)) {
1395 /* Write as much data as possible. */
1396 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1397 buffer_len(&stderr_buffer));
1399 if (errno == EINTR || errno == EAGAIN ||
1400 errno == EWOULDBLOCK)
1404 * EOF or error, but can't even print
1411 /* Consume printed characters from the buffer. */
1412 buffer_consume(&stderr_buffer, len);
1417 * Get packets from the connection input buffer, and process them as long as
1418 * there are packets available.
1420 * Any unknown packets received during the actual
1421 * session cause the session to terminate. This is
1422 * intended to make debugging easier since no
1423 * confirmations are sent. Any compatible protocol
1424 * extensions must be negotiated during the
1425 * preparatory phase.
1429 client_process_buffered_input_packets(void)
1431 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
1434 /* scan buf[] for '~' before sending data to the peer */
1436 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1438 client_new_escape_filter_ctx(int escape_char)
1440 struct escape_filter_ctx *ret;
1442 ret = xcalloc(1, sizeof(*ret));
1443 ret->escape_pending = 0;
1444 ret->escape_char = escape_char;
1448 /* Free the escape filter context on channel free */
1450 client_filter_cleanup(int cid, void *ctx)
1456 client_simple_escape_filter(Channel *c, char *buf, int len)
1458 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1461 return process_escapes(c, &c->input, &c->output, &c->extended,
1466 client_channel_closed(int id, void *arg)
1468 channel_cancel_cleanup(id);
1470 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1474 * Implements the interactive session with the server. This is called after
1475 * the user has been authenticated, and a command has been started on the
1476 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1477 * used as an escape character for terminating or suspending the session.
1481 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1483 fd_set *readset = NULL, *writeset = NULL;
1484 double start_time, total_time;
1485 int r, max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1486 u_int64_t ibytes, obytes;
1490 debug("Entering interactive session.");
1492 start_time = get_current_time();
1494 /* Initialize variables. */
1495 escape_pending1 = 0;
1499 buffer_high = 64 * 1024;
1500 connection_in = packet_get_connection_in();
1501 connection_out = packet_get_connection_out();
1502 max_fd = MAX(connection_in, connection_out);
1505 /* enable nonblocking unless tty */
1506 if (!isatty(fileno(stdin)))
1507 set_nonblock(fileno(stdin));
1508 if (!isatty(fileno(stdout)))
1509 set_nonblock(fileno(stdout));
1510 if (!isatty(fileno(stderr)))
1511 set_nonblock(fileno(stderr));
1512 max_fd = MAX(max_fd, fileno(stdin));
1513 max_fd = MAX(max_fd, fileno(stdout));
1514 max_fd = MAX(max_fd, fileno(stderr));
1517 escape_char1 = escape_char_arg;
1519 /* Initialize buffers. */
1520 buffer_init(&stdin_buffer);
1521 buffer_init(&stdout_buffer);
1522 buffer_init(&stderr_buffer);
1524 client_init_dispatch();
1527 * Set signal handlers, (e.g. to restore non-blocking mode)
1528 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1530 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1531 signal(SIGHUP, signal_handler);
1532 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1533 signal(SIGINT, signal_handler);
1534 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1535 signal(SIGQUIT, signal_handler);
1536 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1537 signal(SIGTERM, signal_handler);
1538 signal(SIGWINCH, window_change_handler);
1541 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1544 session_ident = ssh2_chan_id;
1545 if (session_ident != -1) {
1546 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1547 channel_register_filter(session_ident,
1548 client_simple_escape_filter, NULL,
1549 client_filter_cleanup,
1550 client_new_escape_filter_ctx(
1553 channel_register_cleanup(session_ident,
1554 client_channel_closed, 0);
1557 /* Check if we should immediately send eof on stdin. */
1558 client_check_initial_eof_on_stdin();
1561 /* Main loop of the client for the interactive session mode. */
1562 while (!quit_pending) {
1564 /* Process buffered packets sent by the server. */
1565 client_process_buffered_input_packets();
1567 if (compat20 && session_closed && !channel_still_open())
1570 rekeying = (active_state->kex != NULL && !active_state->kex->done);
1573 debug("rekeying in progress");
1576 * Make packets of buffered stdin data, and buffer
1577 * them for sending to the server.
1580 client_make_packets_from_stdin_data();
1583 * Make packets from buffered channel data, and
1584 * enqueue them for sending to the server.
1586 if (packet_not_very_much_data_to_write())
1587 channel_output_poll();
1590 * Check if the window size has changed, and buffer a
1591 * message about it to the server if so.
1593 client_check_window_change();
1599 * Wait until we have something to do (something becomes
1600 * available on one of the descriptors).
1603 client_wait_until_can_do_something(&readset, &writeset,
1604 &max_fd2, &nalloc, rekeying);
1609 /* Do channel operations unless rekeying in progress. */
1611 channel_after_select(readset, writeset);
1612 if (need_rekeying || packet_need_rekeying()) {
1613 debug("need rekeying");
1614 active_state->kex->done = 0;
1615 if ((r = kex_send_kexinit(active_state)) != 0)
1616 fatal("%s: kex_send_kexinit: %s",
1617 __func__, ssh_err(r));
1622 /* Buffer input from the connection. */
1623 client_process_net_input(readset);
1629 /* Buffer data from stdin */
1630 client_process_input(readset);
1632 * Process output to stdout and stderr. Output to
1633 * the connection is processed elsewhere (above).
1635 client_process_output(writeset);
1638 if (session_resumed) {
1639 connection_in = packet_get_connection_in();
1640 connection_out = packet_get_connection_out();
1641 max_fd = MAX(max_fd, connection_out);
1642 max_fd = MAX(max_fd, connection_in);
1643 session_resumed = 0;
1647 * Send as much buffered packet data as possible to the
1650 if (FD_ISSET(connection_out, writeset))
1651 packet_write_poll();
1654 * If we are a backgrounded control master, and the
1655 * timeout has expired without any active client
1656 * connections, then quit.
1658 if (control_persist_exit_time > 0) {
1659 if (monotime() >= control_persist_exit_time) {
1660 debug("ControlPersist timeout expired");
1668 /* Terminate the session. */
1670 /* Stop watching for window change. */
1671 signal(SIGWINCH, SIG_DFL);
1674 packet_start(SSH2_MSG_DISCONNECT);
1675 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1676 packet_put_cstring("disconnected by user");
1677 packet_put_cstring(""); /* language tag */
1679 packet_write_wait();
1685 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1687 /* restore blocking io */
1688 if (!isatty(fileno(stdin)))
1689 unset_nonblock(fileno(stdin));
1690 if (!isatty(fileno(stdout)))
1691 unset_nonblock(fileno(stdout));
1692 if (!isatty(fileno(stderr)))
1693 unset_nonblock(fileno(stderr));
1696 * If there was no shell or command requested, there will be no remote
1697 * exit status to be returned. In that case, clear error code if the
1698 * connection was deliberately terminated at this end.
1700 if (no_shell_flag && received_signal == SIGTERM) {
1701 received_signal = 0;
1705 if (received_signal)
1706 fatal("Killed by signal %d.", (int) received_signal);
1709 * In interactive mode (with pseudo tty) display a message indicating
1710 * that the connection has been closed.
1712 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1713 snprintf(buf, sizeof buf,
1714 "Connection to %.64s closed.\r\n", host);
1715 buffer_append(&stderr_buffer, buf, strlen(buf));
1718 /* Output any buffered data for stdout. */
1719 if (buffer_len(&stdout_buffer) > 0) {
1720 len = atomicio(vwrite, fileno(stdout),
1721 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1722 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1723 error("Write failed flushing stdout buffer.");
1725 buffer_consume(&stdout_buffer, len);
1728 /* Output any buffered data for stderr. */
1729 if (buffer_len(&stderr_buffer) > 0) {
1730 len = atomicio(vwrite, fileno(stderr),
1731 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1732 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1733 error("Write failed flushing stderr buffer.");
1735 buffer_consume(&stderr_buffer, len);
1738 /* Clear and free any buffers. */
1739 memset(buf, 0, sizeof(buf));
1740 buffer_free(&stdin_buffer);
1741 buffer_free(&stdout_buffer);
1742 buffer_free(&stderr_buffer);
1744 /* Report bytes transferred, and transfer rates. */
1745 total_time = get_current_time() - start_time;
1746 packet_get_bytes(&ibytes, &obytes);
1747 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1748 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1750 verbose("Bytes per second: sent %.1f, received %.1f",
1751 obytes / total_time, ibytes / total_time);
1752 /* Return the exit status of the program. */
1753 debug("Exit status %d", exit_status);
1760 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1763 char *data = packet_get_string(&data_len);
1765 buffer_append(&stdout_buffer, data, data_len);
1766 explicit_bzero(data, data_len);
1771 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1774 char *data = packet_get_string(&data_len);
1776 buffer_append(&stderr_buffer, data, data_len);
1777 explicit_bzero(data, data_len);
1782 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1784 exit_status = packet_get_int();
1786 /* Acknowledge the exit. */
1787 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1790 * Must wait for packet to be sent since we are
1793 packet_write_wait();
1794 /* Flag that we want to exit. */
1800 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1803 int r, remote_id, sock;
1805 /* Read the remote channel number from the message. */
1806 remote_id = packet_get_int();
1810 * Get a connection to the local authentication agent (this may again
1813 if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1814 r != SSH_ERR_AGENT_NOT_PRESENT)
1815 debug("%s: ssh_get_authentication_socket: %s",
1816 __func__, ssh_err(r));
1820 * If we could not connect the agent, send an error message back to
1821 * the server. This should never happen unless the agent dies,
1822 * because authentication forwarding is only enabled if we have an
1826 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1827 -1, 0, 0, 0, "authentication agent connection", 1);
1828 c->remote_id = remote_id;
1832 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1833 packet_put_int(remote_id);
1835 /* Send a confirmation to the remote host. */
1836 debug("Forwarding authentication connection.");
1837 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1838 packet_put_int(remote_id);
1839 packet_put_int(c->self);
1846 client_request_forwarded_tcpip(const char *request_type, int rchan)
1849 char *listen_address, *originator_address;
1850 u_short listen_port, originator_port;
1852 /* Get rest of the packet */
1853 listen_address = packet_get_string(NULL);
1854 listen_port = packet_get_int();
1855 originator_address = packet_get_string(NULL);
1856 originator_port = packet_get_int();
1859 debug("%s: listen %s port %d, originator %s port %d", __func__,
1860 listen_address, listen_port, originator_address, originator_port);
1862 c = channel_connect_by_listen_address(listen_address, listen_port,
1863 "forwarded-tcpip", originator_address);
1865 free(originator_address);
1866 free(listen_address);
1871 client_request_forwarded_streamlocal(const char *request_type, int rchan)
1876 /* Get the remote path. */
1877 listen_path = packet_get_string(NULL);
1878 /* XXX: Skip reserved field for now. */
1879 if (packet_get_string_ptr(NULL) == NULL)
1880 fatal("%s: packet_get_string_ptr failed", __func__);
1883 debug("%s: %s", __func__, listen_path);
1885 c = channel_connect_by_listen_path(listen_path,
1886 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1892 client_request_x11(const char *request_type, int rchan)
1896 u_short originator_port;
1899 if (!options.forward_x11) {
1900 error("Warning: ssh server tried X11 forwarding.");
1901 error("Warning: this is probably a break-in attempt by a "
1902 "malicious server.");
1905 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1906 verbose("Rejected X11 connection after ForwardX11Timeout "
1910 originator = packet_get_string(NULL);
1911 if (datafellows & SSH_BUG_X11FWD) {
1912 debug2("buggy server: x11 request w/o originator_port");
1913 originator_port = 0;
1915 originator_port = packet_get_int();
1918 /* XXX check permission */
1919 debug("client_request_x11: request from %s %d", originator,
1922 sock = x11_connect_display();
1925 c = channel_new("x11",
1926 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1927 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1933 client_request_agent(const char *request_type, int rchan)
1938 if (!options.forward_agent) {
1939 error("Warning: ssh server tried agent forwarding.");
1940 error("Warning: this is probably a break-in attempt by a "
1941 "malicious server.");
1944 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1945 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1946 debug("%s: ssh_get_authentication_socket: %s",
1947 __func__, ssh_err(r));
1950 c = channel_new("authentication agent connection",
1951 SSH_CHANNEL_OPEN, sock, sock, -1,
1952 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1953 "authentication agent connection", 1);
1959 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1964 if (tun_mode == SSH_TUNMODE_NO)
1968 error("Tunnel forwarding is not supported for protocol 1");
1972 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1974 /* Open local tunnel device */
1975 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1976 error("Tunnel device open failed.");
1980 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1981 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1984 #if defined(SSH_TUN_FILTER)
1985 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1986 channel_register_filter(c->self, sys_tun_infilter,
1987 sys_tun_outfilter, NULL, NULL);
1990 packet_start(SSH2_MSG_CHANNEL_OPEN);
1991 packet_put_cstring("tun@openssh.com");
1992 packet_put_int(c->self);
1993 packet_put_int(c->local_window_max);
1994 packet_put_int(c->local_maxpacket);
1995 packet_put_int(tun_mode);
1996 packet_put_int(remote_tun);
2002 /* XXXX move to generic input handler */
2004 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
2009 u_int rmaxpack, rwindow, len;
2011 ctype = packet_get_string(&len);
2012 rchan = packet_get_int();
2013 rwindow = packet_get_int();
2014 rmaxpack = packet_get_int();
2016 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2017 ctype, rchan, rwindow, rmaxpack);
2019 if (strcmp(ctype, "forwarded-tcpip") == 0) {
2020 c = client_request_forwarded_tcpip(ctype, rchan);
2021 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
2022 c = client_request_forwarded_streamlocal(ctype, rchan);
2023 } else if (strcmp(ctype, "x11") == 0) {
2024 c = client_request_x11(ctype, rchan);
2025 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2026 c = client_request_agent(ctype, rchan);
2028 /* XXX duplicate : */
2030 debug("confirm %s", ctype);
2031 c->remote_id = rchan;
2032 c->remote_window = rwindow;
2033 c->remote_maxpacket = rmaxpack;
2034 if (c->type != SSH_CHANNEL_CONNECTING) {
2035 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2036 packet_put_int(c->remote_id);
2037 packet_put_int(c->self);
2038 packet_put_int(c->local_window);
2039 packet_put_int(c->local_maxpacket);
2043 debug("failure %s", ctype);
2044 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2045 packet_put_int(rchan);
2046 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2047 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2048 packet_put_cstring("open failed");
2049 packet_put_cstring("");
2058 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2061 int exitval, id, reply, success = 0;
2064 id = packet_get_int();
2065 rtype = packet_get_string(NULL);
2066 reply = packet_get_char();
2068 debug("client_input_channel_req: channel %d rtype %s reply %d",
2072 error("client_input_channel_req: request for channel -1");
2073 } else if ((c = channel_lookup(id)) == NULL) {
2074 error("client_input_channel_req: channel %d: "
2075 "unknown channel", id);
2076 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2079 } else if (strcmp(rtype, "exit-status") == 0) {
2080 exitval = packet_get_int();
2081 if (c->ctl_chan != -1) {
2082 mux_exit_message(c, exitval);
2084 } else if (id == session_ident) {
2085 /* Record exit value of local session */
2087 exit_status = exitval;
2089 /* Probably for a mux channel that has already closed */
2090 debug("%s: no sink for exit-status on channel %d",
2095 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2096 packet_start(success ?
2097 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2098 packet_put_int(c->remote_id);
2105 struct hostkeys_update_ctx {
2106 /* The hostname and (optionally) IP address string for the server */
2107 char *host_str, *ip_str;
2110 * Keys received from the server and a flag for each indicating
2111 * whether they already exist in known_hosts.
2112 * keys_seen is filled in by hostkeys_find() and later (for new
2113 * keys) by client_global_hostkeys_private_confirm().
2115 struct sshkey **keys;
2122 * Keys that are in known_hosts, but were not present in the update
2123 * from the server (i.e. scheduled to be deleted).
2124 * Filled in by hostkeys_find().
2126 struct sshkey **old_keys;
2131 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2137 for (i = 0; i < ctx->nkeys; i++)
2138 sshkey_free(ctx->keys[i]);
2140 free(ctx->keys_seen);
2141 for (i = 0; i < ctx->nold; i++)
2142 sshkey_free(ctx->old_keys[i]);
2143 free(ctx->old_keys);
2144 free(ctx->host_str);
2150 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2152 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2154 struct sshkey **tmp;
2156 if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
2157 l->key->type == KEY_RSA1)
2160 /* Mark off keys we've already seen for this host */
2161 for (i = 0; i < ctx->nkeys; i++) {
2162 if (sshkey_equal(l->key, ctx->keys[i])) {
2163 debug3("%s: found %s key at %s:%ld", __func__,
2164 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2165 ctx->keys_seen[i] = 1;
2169 /* This line contained a key that not offered by the server */
2170 debug3("%s: deprecated %s key at %s:%ld", __func__,
2171 sshkey_ssh_name(l->key), l->path, l->linenum);
2172 if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
2173 sizeof(*ctx->old_keys))) == NULL)
2174 fatal("%s: reallocarray failed nold = %zu",
2175 __func__, ctx->nold);
2176 ctx->old_keys = tmp;
2177 ctx->old_keys[ctx->nold++] = l->key;
2184 update_known_hosts(struct hostkeys_update_ctx *ctx)
2187 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
2188 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2189 char *fp, *response;
2192 for (i = 0; i < ctx->nkeys; i++) {
2193 if (ctx->keys_seen[i] != 2)
2195 if ((fp = sshkey_fingerprint(ctx->keys[i],
2196 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2197 fatal("%s: sshkey_fingerprint failed", __func__);
2198 do_log2(loglevel, "Learned new hostkey: %s %s",
2199 sshkey_type(ctx->keys[i]), fp);
2202 for (i = 0; i < ctx->nold; i++) {
2203 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2204 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2205 fatal("%s: sshkey_fingerprint failed", __func__);
2206 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2207 sshkey_type(ctx->old_keys[i]), fp);
2210 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2211 if (get_saved_tio() != NULL) {
2216 for (i = 0; !quit_pending && i < 3; i++) {
2218 response = read_passphrase("Accept updated hostkeys? "
2219 "(yes/no): ", RP_ECHO);
2220 if (strcasecmp(response, "yes") == 0)
2222 else if (quit_pending || response == NULL ||
2223 strcasecmp(response, "no") == 0) {
2224 options.update_hostkeys = 0;
2227 do_log2(loglevel, "Please enter "
2228 "\"yes\" or \"no\"");
2231 if (quit_pending || i >= 3 || response == NULL)
2232 options.update_hostkeys = 0;
2239 * Now that all the keys are verified, we can go ahead and replace
2240 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2241 * cancel the operation).
2243 if (options.update_hostkeys != 0 &&
2244 (r = hostfile_replace_entries(options.user_hostfiles[0],
2245 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
2246 options.hash_known_hosts, 0,
2247 options.fingerprint_hash)) != 0)
2248 error("%s: hostfile_replace_entries failed: %s",
2249 __func__, ssh_err(r));
2253 client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
2255 struct ssh *ssh = active_state; /* XXX */
2256 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2258 struct sshbuf *signdata;
2264 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
2265 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2266 error("Server failed to confirm ownership of "
2267 "private host keys");
2268 hostkeys_update_ctx_free(ctx);
2271 if ((signdata = sshbuf_new()) == NULL)
2272 fatal("%s: sshbuf_new failed", __func__);
2273 /* Don't want to accidentally accept an unbound signature */
2274 if (ssh->kex->session_id_len == 0)
2275 fatal("%s: ssh->kex->session_id_len == 0", __func__);
2277 * Expect a signature for each of the ctx->nnew private keys we
2278 * haven't seen before. They will be in the same order as the
2279 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
2281 for (ndone = i = 0; i < ctx->nkeys; i++) {
2282 if (ctx->keys_seen[i])
2284 /* Prepare data to be signed: session ID, unique string, key */
2285 sshbuf_reset(signdata);
2286 if ( (r = sshbuf_put_cstring(signdata,
2287 "hostkeys-prove-00@openssh.com")) != 0 ||
2288 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
2289 ssh->kex->session_id_len)) != 0 ||
2290 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2291 fatal("%s: failed to prepare signature: %s",
2292 __func__, ssh_err(r));
2293 /* Extract and verify signature */
2294 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2295 error("%s: couldn't parse message: %s",
2296 __func__, ssh_err(r));
2299 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2300 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
2301 error("%s: server gave bad signature for %s key %zu",
2302 __func__, sshkey_type(ctx->keys[i]), i);
2305 /* Key is good. Mark it as 'seen' */
2306 ctx->keys_seen[i] = 2;
2309 if (ndone != ctx->nnew)
2310 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2311 ndone, ctx->nnew); /* Shouldn't happen */
2312 ssh_packet_check_eom(ssh);
2314 /* Make the edits to known_hosts */
2315 update_known_hosts(ctx);
2317 hostkeys_update_ctx_free(ctx);
2321 * Handle hostkeys-00@openssh.com global request to inform the client of all
2322 * the server's hostkeys. The keys are checked against the user's
2323 * HostkeyAlgorithms preference before they are accepted.
2326 client_input_hostkeys(void)
2328 struct ssh *ssh = active_state; /* XXX */
2329 const u_char *blob = NULL;
2331 struct sshbuf *buf = NULL;
2332 struct sshkey *key = NULL, **tmp;
2335 static int hostkeys_seen = 0; /* XXX use struct ssh */
2336 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2337 struct hostkeys_update_ctx *ctx = NULL;
2340 fatal("%s: server already sent hostkeys", __func__);
2341 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2343 return 1; /* won't ask in batchmode, so don't even try */
2344 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2347 ctx = xcalloc(1, sizeof(*ctx));
2348 while (ssh_packet_remaining(ssh) > 0) {
2351 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2352 error("%s: couldn't parse message: %s",
2353 __func__, ssh_err(r));
2356 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2357 error("%s: parse key: %s", __func__, ssh_err(r));
2360 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2362 debug3("%s: received %s key %s", __func__,
2363 sshkey_type(key), fp);
2365 /* Check that the key is accepted in HostkeyAlgorithms */
2366 if (options.hostkeyalgorithms != NULL &&
2367 match_pattern_list(sshkey_ssh_name(key),
2368 options.hostkeyalgorithms, 0) != 1) {
2369 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2370 __func__, sshkey_ssh_name(key));
2374 if (sshkey_is_cert(key)) {
2375 debug3("%s: %s key is a certificate; skipping",
2376 __func__, sshkey_ssh_name(key));
2379 /* Ensure keys are unique */
2380 for (i = 0; i < ctx->nkeys; i++) {
2381 if (sshkey_equal(key, ctx->keys[i])) {
2382 error("%s: received duplicated %s host key",
2383 __func__, sshkey_ssh_name(key));
2387 /* Key is good, record it */
2388 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2389 sizeof(*ctx->keys))) == NULL)
2390 fatal("%s: reallocarray failed nkeys = %zu",
2391 __func__, ctx->nkeys);
2393 ctx->keys[ctx->nkeys++] = key;
2397 if (ctx->nkeys == 0) {
2398 debug("%s: server sent no hostkeys", __func__);
2402 if ((ctx->keys_seen = calloc(ctx->nkeys,
2403 sizeof(*ctx->keys_seen))) == NULL)
2404 fatal("%s: calloc failed", __func__);
2406 get_hostfile_hostname_ipaddr(host,
2407 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2408 options.port, &ctx->host_str,
2409 options.check_host_ip ? &ctx->ip_str : NULL);
2411 /* Find which keys we already know about. */
2412 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2413 ctx, ctx->host_str, ctx->ip_str,
2414 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2415 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2419 /* Figure out if we have any new keys to add */
2421 for (i = 0; i < ctx->nkeys; i++) {
2422 if (!ctx->keys_seen[i])
2426 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2427 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2429 if (ctx->nnew == 0 && ctx->nold != 0) {
2430 /* We have some keys to remove. Just do it. */
2431 update_known_hosts(ctx);
2432 } else if (ctx->nnew != 0) {
2434 * We have received hitherto-unseen keys from the server.
2435 * Ask the server to confirm ownership of the private halves.
2437 debug3("%s: asking server to prove ownership for %zu keys",
2438 __func__, ctx->nnew);
2439 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2440 (r = sshpkt_put_cstring(ssh,
2441 "hostkeys-prove-00@openssh.com")) != 0 ||
2442 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2443 fatal("%s: cannot prepare packet: %s",
2444 __func__, ssh_err(r));
2445 if ((buf = sshbuf_new()) == NULL)
2446 fatal("%s: sshbuf_new", __func__);
2447 for (i = 0; i < ctx->nkeys; i++) {
2448 if (ctx->keys_seen[i])
2451 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2452 fatal("%s: sshkey_putb: %s",
2453 __func__, ssh_err(r));
2454 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2455 fatal("%s: sshpkt_put_string: %s",
2456 __func__, ssh_err(r));
2458 if ((r = sshpkt_send(ssh)) != 0)
2459 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2460 client_register_global_confirm(
2461 client_global_hostkeys_private_confirm, ctx);
2462 ctx = NULL; /* will be freed in callback */
2467 hostkeys_update_ctx_free(ctx);
2471 * NB. Return success for all cases. The server doesn't need to know
2472 * what the client does with its hosts file.
2478 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2484 rtype = packet_get_cstring(NULL);
2485 want_reply = packet_get_char();
2486 debug("client_input_global_request: rtype %s want_reply %d",
2488 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2489 success = client_input_hostkeys();
2491 packet_start(success ?
2492 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2494 packet_write_wait();
2501 client_session2_setup(int id, int want_tty, int want_subsystem,
2502 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2507 debug2("%s: id %d", __func__, id);
2509 if ((c = channel_lookup(id)) == NULL)
2510 fatal("client_session2_setup: channel %d: unknown channel", id);
2512 packet_set_interactive(want_tty,
2513 options.ip_qos_interactive, options.ip_qos_bulk);
2518 /* Store window size in the packet. */
2519 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2520 memset(&ws, 0, sizeof(ws));
2522 channel_request_start(id, "pty-req", 1);
2523 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2524 packet_put_cstring(term != NULL ? term : "");
2525 packet_put_int((u_int)ws.ws_col);
2526 packet_put_int((u_int)ws.ws_row);
2527 packet_put_int((u_int)ws.ws_xpixel);
2528 packet_put_int((u_int)ws.ws_ypixel);
2530 tiop = get_saved_tio();
2531 tty_make_modes(-1, tiop);
2533 /* XXX wait for reply */
2537 /* Transfer any environment variables from client to server */
2538 if (options.num_send_env != 0 && env != NULL) {
2542 debug("Sending environment.");
2543 for (i = 0; env[i] != NULL; i++) {
2545 name = xstrdup(env[i]);
2546 if ((val = strchr(name, '=')) == NULL) {
2553 for (j = 0; j < options.num_send_env; j++) {
2554 if (match_pattern(name, options.send_env[j])) {
2560 debug3("Ignored env %s", name);
2565 debug("Sending env %s = %s", name, val);
2566 channel_request_start(id, "env", 0);
2567 packet_put_cstring(name);
2568 packet_put_cstring(val);
2574 len = buffer_len(cmd);
2578 if (want_subsystem) {
2579 debug("Sending subsystem: %.*s",
2580 len, (u_char*)buffer_ptr(cmd));
2581 channel_request_start(id, "subsystem", 1);
2582 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2584 debug("Sending command: %.*s",
2585 len, (u_char*)buffer_ptr(cmd));
2586 channel_request_start(id, "exec", 1);
2587 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2589 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2592 channel_request_start(id, "shell", 1);
2593 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2599 client_init_dispatch_20(void)
2601 dispatch_init(&dispatch_protocol_error);
2603 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2604 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2605 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2606 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2607 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2608 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2609 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2610 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2611 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2612 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2613 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2614 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2617 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2619 /* global request reply messages */
2620 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2621 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2625 client_init_dispatch_13(void)
2627 dispatch_init(NULL);
2628 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2629 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2630 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2631 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2632 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2633 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2634 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2635 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2636 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2638 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2639 &client_input_agent_open : &deny_input_open);
2640 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2641 &x11_input_open : &deny_input_open);
2645 client_init_dispatch_15(void)
2647 client_init_dispatch_13();
2648 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2649 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2653 client_init_dispatch(void)
2656 client_init_dispatch_20();
2658 client_init_dispatch_13();
2660 client_init_dispatch_15();
2664 client_stop_mux(void)
2666 if (options.control_path != NULL && muxserver_sock != -1)
2667 unlink(options.control_path);
2669 * If we are in persist mode, or don't have a shell, signal that we
2670 * should close when all active channels are closed.
2672 if (options.control_persist || no_shell_flag) {
2674 setproctitle("[stopped mux]");
2678 /* client specific fatal cleanup */
2682 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2683 leave_non_blocking();
2684 if (options.control_path != NULL && muxserver_sock != -1)
2685 unlink(options.control_path);
2686 ssh_kill_proxy_command();