1 /* $OpenBSD: clientloop.c,v 1.275 2015/07/10 06:21:53 markus 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"
103 #include "myproposal.h"
106 #include "readconf.h"
107 #include "clientloop.h"
108 #include "sshconnect.h"
110 #include "atomicio.h"
116 #include "hostfile.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 u_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);
198 void ssh_process_session2_setup(int, int, int, Buffer *);
200 /* Restores stdin to blocking mode. */
203 leave_non_blocking(void)
205 if (in_non_blocking_mode) {
206 unset_nonblock(fileno(stdin));
207 in_non_blocking_mode = 0;
211 /* Puts stdin terminal in non-blocking mode. */
214 enter_non_blocking(void)
216 in_non_blocking_mode = 1;
217 set_nonblock(fileno(stdin));
221 * Signal handler for the window change signal (SIGWINCH). This just sets a
222 * flag indicating that the window has changed.
226 window_change_handler(int sig)
228 received_window_change_signal = 1;
229 signal(SIGWINCH, window_change_handler);
233 * Signal handler for signals that cause the program to terminate. These
234 * signals must be trapped to restore terminal modes.
238 signal_handler(int sig)
240 received_signal = sig;
245 * Returns current time in seconds from Jan 1, 1970 with the maximum
246 * available resolution.
250 get_current_time(void)
253 gettimeofday(&tv, NULL);
254 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
258 * Sets control_persist_exit_time to the absolute time when the
259 * backgrounded control master should exit due to expiry of the
260 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
261 * control master process, or if there is no ControlPersist timeout.
264 set_control_persist_exit_time(void)
266 if (muxserver_sock == -1 || !options.control_persist
267 || options.control_persist_timeout == 0) {
268 /* not using a ControlPersist timeout */
269 control_persist_exit_time = 0;
270 } else if (channel_still_open()) {
271 /* some client connections are still open */
272 if (control_persist_exit_time > 0)
273 debug2("%s: cancel scheduled exit", __func__);
274 control_persist_exit_time = 0;
275 } else if (control_persist_exit_time <= 0) {
276 /* a client connection has recently closed */
277 control_persist_exit_time = monotime() +
278 (time_t)options.control_persist_timeout;
279 debug2("%s: schedule exit in %d seconds", __func__,
280 options.control_persist_timeout);
282 /* else we are already counting down to the timeout */
285 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
287 client_x11_display_valid(const char *display)
291 dlen = strlen(display);
292 for (i = 0; i < dlen; i++) {
293 if (!isalnum((u_char)display[i]) &&
294 strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
295 debug("Invalid character '%c' in DISPLAY", display[i]);
302 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
303 #define X11_TIMEOUT_SLACK 60
305 client_x11_get_proto(const char *display, const char *xauth_path,
306 u_int trusted, u_int timeout, char **_proto, char **_data)
311 static char proto[512], data[512];
313 int got_data = 0, generated = 0, do_unlink = 0, i;
314 char *xauthdir, *xauthfile;
316 u_int now, x11_timeout_real;
318 xauthdir = xauthfile = NULL;
321 proto[0] = data[0] = '\0';
323 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
324 debug("No xauth program.");
325 } else if (!client_x11_display_valid(display)) {
326 logit("DISPLAY '%s' invalid, falling back to fake xauth data",
329 if (display == NULL) {
330 debug("x11_get_proto: DISPLAY not set");
334 * Handle FamilyLocal case where $DISPLAY does
335 * not match an authorization entry. For this we
336 * just try "xauth list unix:displaynum.screennum".
337 * XXX: "localhost" match to determine FamilyLocal
340 if (strncmp(display, "localhost:", 10) == 0) {
341 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
346 xauthdir = xmalloc(PATH_MAX);
347 xauthfile = xmalloc(PATH_MAX);
348 mktemp_proto(xauthdir, PATH_MAX);
350 * The authentication cookie should briefly outlive
351 * ssh's willingness to forward X11 connections to
352 * avoid nasty fail-open behaviour in the X server.
354 if (timeout >= UINT_MAX - X11_TIMEOUT_SLACK)
355 x11_timeout_real = UINT_MAX;
357 x11_timeout_real = timeout + X11_TIMEOUT_SLACK;
358 if (mkdtemp(xauthdir) != NULL) {
360 snprintf(xauthfile, PATH_MAX, "%s/xauthfile",
362 snprintf(cmd, sizeof(cmd),
363 "%s -f %s generate %s " SSH_X11_PROTO
364 " untrusted timeout %u 2>" _PATH_DEVNULL,
365 xauth_path, xauthfile, display,
367 debug2("x11_get_proto: %s", cmd);
368 if (x11_refuse_time == 0) {
369 now = monotime() + 1;
370 if (UINT_MAX - timeout < now)
371 x11_refuse_time = UINT_MAX;
373 x11_refuse_time = now + timeout;
374 channel_set_x11_refuse_time(
377 if (system(cmd) == 0)
383 * When in untrusted mode, we read the cookie only if it was
384 * successfully generated as an untrusted one in the step
387 if (trusted || generated) {
388 snprintf(cmd, sizeof(cmd),
389 "%s %s%s list %s 2>" _PATH_DEVNULL,
391 generated ? "-f " : "" ,
392 generated ? xauthfile : "",
394 debug2("x11_get_proto: %s", cmd);
396 if (f && fgets(line, sizeof(line), f) &&
397 sscanf(line, "%*s %511s %511s", proto, data) == 2)
402 error("Warning: untrusted X11 forwarding setup failed: "
403 "xauth key data not generated");
414 * If we didn't get authentication data, just make up some
415 * data. The forwarding code will check the validity of the
416 * response anyway, and substitute this data. The X11
417 * server, however, will ignore this fake data and use
418 * whatever authentication mechanisms it was using otherwise
419 * for the local connection.
424 logit("Warning: No xauth data; "
425 "using fake authentication data for X11 forwarding.");
426 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
427 for (i = 0; i < 16; i++) {
430 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
438 * This is called when the interactive is entered. This checks if there is
439 * an EOF coming on stdin. We must check this explicitly, as select() does
440 * not appear to wake up when redirecting from /dev/null.
444 client_check_initial_eof_on_stdin(void)
450 * If standard input is to be "redirected from /dev/null", we simply
451 * mark that we have seen an EOF and send an EOF message to the
452 * server. Otherwise, we try to read a single character; it appears
453 * that for some files, such /dev/null, select() never wakes up for
454 * read for this descriptor, which means that we never get EOF. This
455 * way we will get the EOF if stdin comes from /dev/null or similar.
457 if (stdin_null_flag) {
458 /* Fake EOF on stdin. */
459 debug("Sending eof.");
461 packet_start(SSH_CMSG_EOF);
464 enter_non_blocking();
466 /* Check for immediate EOF on stdin. */
467 len = read(fileno(stdin), buf, 1);
470 * EOF. Record that we have seen it and send
473 debug("Sending eof.");
475 packet_start(SSH_CMSG_EOF);
477 } else if (len > 0) {
479 * Got data. We must store the data in the buffer,
480 * and also process it as an escape character if
483 if ((u_char) buf[0] == escape_char1)
486 buffer_append(&stdin_buffer, buf, 1);
488 leave_non_blocking();
494 * Make packets from buffered stdin data, and buffer them for sending to the
499 client_make_packets_from_stdin_data(void)
503 /* Send buffered stdin data to the server. */
504 while (buffer_len(&stdin_buffer) > 0 &&
505 packet_not_very_much_data_to_write()) {
506 len = buffer_len(&stdin_buffer);
507 /* Keep the packets at reasonable size. */
508 if (len > packet_get_maxsize())
509 len = packet_get_maxsize();
510 packet_start(SSH_CMSG_STDIN_DATA);
511 packet_put_string(buffer_ptr(&stdin_buffer), len);
513 buffer_consume(&stdin_buffer, len);
514 /* If we have a pending EOF, send it now. */
515 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
516 packet_start(SSH_CMSG_EOF);
523 * Checks if the client window has changed, and sends a packet about it to
524 * the server if so. The actual change is detected elsewhere (by a software
525 * interrupt on Unix); this just checks the flag and sends a message if
530 client_check_window_change(void)
534 if (! received_window_change_signal)
537 received_window_change_signal = 0;
539 debug2("client_check_window_change: changed");
542 channel_send_window_changes();
544 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
546 packet_start(SSH_CMSG_WINDOW_SIZE);
547 packet_put_int((u_int)ws.ws_row);
548 packet_put_int((u_int)ws.ws_col);
549 packet_put_int((u_int)ws.ws_xpixel);
550 packet_put_int((u_int)ws.ws_ypixel);
556 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
558 struct global_confirm *gc;
560 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
563 gc->cb(type, seq, gc->ctx);
564 if (--gc->ref_count <= 0) {
565 TAILQ_REMOVE(&global_confirms, gc, entry);
566 explicit_bzero(gc, sizeof(*gc));
570 packet_set_alive_timeouts(0);
575 server_alive_check(void)
577 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
578 logit("Timeout, server %s not responding.", host);
581 packet_start(SSH2_MSG_GLOBAL_REQUEST);
582 packet_put_cstring("keepalive@openssh.com");
583 packet_put_char(1); /* boolean: want reply */
585 /* Insert an empty placeholder to maintain ordering */
586 client_register_global_confirm(NULL, NULL);
590 * Waits until the client can do something (some data becomes available on
591 * one of the file descriptors).
594 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
595 int *maxfdp, u_int *nallocp, int rekeying)
597 struct timeval tv, *tvp;
599 time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
602 /* Add any selections by the channel mechanism. */
603 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
604 &minwait_secs, rekeying);
607 /* Read from the connection, unless our buffers are full. */
608 if (buffer_len(&stdout_buffer) < buffer_high &&
609 buffer_len(&stderr_buffer) < buffer_high &&
610 channel_not_very_much_buffered_data())
611 FD_SET(connection_in, *readsetp);
613 * Read from stdin, unless we have seen EOF or have very much
614 * buffered data to send to the server.
616 if (!stdin_eof && packet_not_very_much_data_to_write())
617 FD_SET(fileno(stdin), *readsetp);
619 /* Select stdout/stderr if have data in buffer. */
620 if (buffer_len(&stdout_buffer) > 0)
621 FD_SET(fileno(stdout), *writesetp);
622 if (buffer_len(&stderr_buffer) > 0)
623 FD_SET(fileno(stderr), *writesetp);
625 /* channel_prepare_select could have closed the last channel */
626 if (session_closed && !channel_still_open() &&
627 !packet_have_data_to_write()) {
628 /* clear mask since we did not call select() */
629 memset(*readsetp, 0, *nallocp);
630 memset(*writesetp, 0, *nallocp);
633 FD_SET(connection_in, *readsetp);
637 /* Select server connection if have data to write to the server. */
638 if (packet_have_data_to_write())
639 FD_SET(connection_out, *writesetp);
642 * Wait for something to happen. This will suspend the process until
643 * some selected descriptor can be read, written, or has some other
644 * event pending, or a timeout expires.
647 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
648 if (options.server_alive_interval > 0 && compat20) {
649 timeout_secs = options.server_alive_interval;
650 server_alive_time = now + options.server_alive_interval;
652 if (options.rekey_interval > 0 && compat20 && !rekeying)
653 timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
654 set_control_persist_exit_time();
655 if (control_persist_exit_time > 0) {
656 timeout_secs = MIN(timeout_secs,
657 control_persist_exit_time - now);
658 if (timeout_secs < 0)
661 if (minwait_secs != 0)
662 timeout_secs = MIN(timeout_secs, (int)minwait_secs);
663 if (timeout_secs == INT_MAX)
666 tv.tv_sec = timeout_secs;
671 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
676 * We have to clear the select masks, because we return.
677 * We have to return, because the mainloop checks for the flags
678 * set by the signal handlers.
680 memset(*readsetp, 0, *nallocp);
681 memset(*writesetp, 0, *nallocp);
685 /* Note: we might still have data in the buffers. */
686 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
687 buffer_append(&stderr_buffer, buf, strlen(buf));
689 } else if (ret == 0) {
691 * Timeout. Could have been either keepalive or rekeying.
692 * Keepalive we check here, rekeying is checked in clientloop.
694 if (server_alive_time != 0 && server_alive_time <= monotime())
695 server_alive_check();
701 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
703 /* Flush stdout and stderr buffers. */
704 if (buffer_len(bout) > 0)
705 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
707 if (buffer_len(berr) > 0)
708 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
711 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
714 * Free (and clear) the buffer to reduce the amount of data that gets
721 /* Send the suspend signal to the program itself. */
722 kill(getpid(), SIGTSTP);
724 /* Reset window sizes in case they have changed */
725 received_window_change_signal = 1;
727 /* OK, we have been continued by the user. Reinitialize buffers. */
732 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
736 client_process_net_input(fd_set *readset)
739 char buf[SSH_IOBUFSZ];
742 * Read input from the server, and add any such data to the buffer of
743 * the packet subsystem.
745 if (FD_ISSET(connection_in, readset)) {
746 /* Read as much as possible. */
747 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
748 if (len == 0 && cont == 0) {
750 * Received EOF. The remote host has closed the
753 snprintf(buf, sizeof buf,
754 "Connection to %.300s closed by remote host.\r\n",
756 buffer_append(&stderr_buffer, buf, strlen(buf));
761 * There is a kernel bug on Solaris that causes select to
762 * sometimes wake up even though there is no data available.
765 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
770 * An error has encountered. Perhaps there is a
773 snprintf(buf, sizeof buf,
774 "Read from remote host %.300s: %.100s\r\n",
775 host, strerror(errno));
776 buffer_append(&stderr_buffer, buf, strlen(buf));
780 packet_process_incoming(buf, len);
785 client_status_confirm(int type, Channel *c, void *ctx)
787 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
792 * If a TTY was explicitly requested, then a failure to allocate
795 if (cr->action == CONFIRM_TTY &&
796 (options.request_tty == REQUEST_TTY_FORCE ||
797 options.request_tty == REQUEST_TTY_YES))
798 cr->action = CONFIRM_CLOSE;
800 /* XXX supress on mux _client_ quietmode */
801 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
802 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
804 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
805 debug2("%s request accepted on channel %d",
806 cr->request_type, c->self);
807 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
809 snprintf(errmsg, sizeof(errmsg),
810 "%s request failed\r\n", cr->request_type);
812 snprintf(errmsg, sizeof(errmsg),
813 "%s request failed on channel %d",
814 cr->request_type, c->self);
816 /* If error occurred on primary session channel, then exit */
817 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
820 * If error occurred on mux client, append to
824 buffer_append(&c->extended, errmsg,
828 if (cr->action == CONFIRM_TTY) {
830 * If a TTY allocation error occurred, then arrange
831 * for the correct TTY to leave raw mode.
833 if (c->self == session_ident)
836 mux_tty_alloc_failed(c);
837 } else if (cr->action == CONFIRM_CLOSE) {
839 chan_write_failed(c);
846 client_abandon_status_confirm(Channel *c, void *ctx)
852 client_expect_confirm(int id, const char *request,
853 enum confirm_action action)
855 struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
857 cr->request_type = request;
860 channel_register_status_confirm(id, client_status_confirm,
861 client_abandon_status_confirm, cr);
865 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
867 struct global_confirm *gc, *last_gc;
869 /* Coalesce identical callbacks */
870 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
871 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
872 if (++last_gc->ref_count >= INT_MAX)
873 fatal("%s: last_gc->ref_count = %d",
874 __func__, last_gc->ref_count);
878 gc = xcalloc(1, sizeof(*gc));
882 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
886 process_cmdline(void)
888 void (*handler)(int);
890 int ok, delete = 0, local = 0, remote = 0, dynamic = 0;
893 memset(&fwd, 0, sizeof(fwd));
895 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
896 handler = signal(SIGINT, SIG_IGN);
897 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
900 while (isspace((u_char)*s))
903 s++; /* Skip cmdline '-', if any */
907 if (*s == 'h' || *s == 'H' || *s == '?') {
909 logit(" -L[bind_address:]port:host:hostport "
910 "Request local forward");
911 logit(" -R[bind_address:]port:host:hostport "
912 "Request remote forward");
913 logit(" -D[bind_address:]port "
914 "Request dynamic forward");
915 logit(" -KL[bind_address:]port "
916 "Cancel local forward");
917 logit(" -KR[bind_address:]port "
918 "Cancel remote forward");
919 logit(" -KD[bind_address:]port "
920 "Cancel dynamic forward");
921 if (!options.permit_local_command)
924 "Execute local command");
928 if (*s == '!' && options.permit_local_command) {
945 logit("Invalid command.");
949 if (delete && !compat20) {
950 logit("Not supported for SSH protocol version 1.");
954 while (isspace((u_char)*++s))
957 /* XXX update list of forwards in options */
959 /* We pass 1 for dynamicfwd to restrict to 1 or 2 fields. */
960 if (!parse_forward(&fwd, s, 1, 0)) {
961 logit("Bad forwarding close specification.");
965 ok = channel_request_rforward_cancel(&fwd) == 0;
967 ok = channel_cancel_lport_listener(&fwd,
968 0, &options.fwd_opts) > 0;
970 ok = channel_cancel_lport_listener(&fwd,
971 CHANNEL_CANCEL_PORT_STATIC,
972 &options.fwd_opts) > 0;
974 logit("Unkown port forwarding.");
977 logit("Canceled forwarding.");
979 if (!parse_forward(&fwd, s, dynamic, remote)) {
980 logit("Bad forwarding specification.");
983 if (local || dynamic) {
984 if (!channel_setup_local_fwd_listener(&fwd,
985 &options.fwd_opts)) {
986 logit("Port forwarding failed.");
990 if (channel_request_remote_forwarding(&fwd) < 0) {
991 logit("Port forwarding failed.");
995 logit("Forwarding port.");
999 signal(SIGINT, handler);
1000 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1002 free(fwd.listen_host);
1003 free(fwd.listen_path);
1004 free(fwd.connect_host);
1005 free(fwd.connect_path);
1008 /* reasons to suppress output of an escape command in help output */
1009 #define SUPPRESS_NEVER 0 /* never suppress, always show */
1010 #define SUPPRESS_PROTO1 1 /* don't show in protocol 1 sessions */
1011 #define SUPPRESS_MUXCLIENT 2 /* don't show in mux client sessions */
1012 #define SUPPRESS_MUXMASTER 4 /* don't show in mux master sessions */
1013 #define SUPPRESS_SYSLOG 8 /* don't show when logging to syslog */
1014 struct escape_help_text {
1019 static struct escape_help_text esc_txt[] = {
1020 {".", "terminate session", SUPPRESS_MUXMASTER},
1021 {".", "terminate connection (and any multiplexed sessions)",
1022 SUPPRESS_MUXCLIENT},
1023 {"B", "send a BREAK to the remote system", SUPPRESS_PROTO1},
1024 {"C", "open a command line", SUPPRESS_MUXCLIENT},
1025 {"R", "request rekey", SUPPRESS_PROTO1},
1026 {"V/v", "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1027 {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1028 {"#", "list forwarded connections", SUPPRESS_NEVER},
1029 {"&", "background ssh (when waiting for connections to terminate)",
1030 SUPPRESS_MUXCLIENT},
1031 {"?", "this message", SUPPRESS_NEVER},
1035 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1038 unsigned int i, suppress_flags;
1041 snprintf(string, sizeof string, "%c?\r\n"
1042 "Supported escape sequences:\r\n", escape_char);
1043 buffer_append(b, string, strlen(string));
1045 suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1046 (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1047 (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1048 (using_stderr ? 0 : SUPPRESS_SYSLOG);
1050 for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1051 if (esc_txt[i].flags & suppress_flags)
1053 snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1054 escape_char, esc_txt[i].cmd, esc_txt[i].text);
1055 buffer_append(b, string, strlen(string));
1058 snprintf(string, sizeof string,
1059 " %c%c - send the escape character by typing it twice\r\n"
1060 "(Note that escapes are only recognized immediately after "
1061 "newline.)\r\n", escape_char, escape_char);
1062 buffer_append(b, string, strlen(string));
1066 * Process the characters one by one, call with c==NULL for proto1 case.
1069 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1078 int *escape_pendingp, escape_char;
1079 struct escape_filter_ctx *efc;
1082 escape_pendingp = &escape_pending1;
1083 escape_char = escape_char1;
1085 if (c->filter_ctx == NULL)
1087 efc = (struct escape_filter_ctx *)c->filter_ctx;
1088 escape_pendingp = &efc->escape_pending;
1089 escape_char = efc->escape_char;
1095 for (i = 0; i < (u_int)len; i++) {
1096 /* Get one character at a time. */
1099 if (*escape_pendingp) {
1100 /* We have previously seen an escape character. */
1101 /* Clear the flag now. */
1102 *escape_pendingp = 0;
1104 /* Process the escaped character. */
1107 /* Terminate the connection. */
1108 snprintf(string, sizeof string, "%c.\r\n",
1110 buffer_append(berr, string, strlen(string));
1112 if (c && c->ctl_chan != -1) {
1113 chan_read_failed(c);
1114 chan_write_failed(c);
1116 c->detach_user(c->self, NULL);
1117 c->type = SSH_CHANNEL_ABANDONED;
1118 buffer_clear(&c->input);
1126 /* XXX support this for mux clients */
1127 if (c && c->ctl_chan != -1) {
1131 snprintf(b, sizeof b, "^Z");
1133 snprintf(b, sizeof b, "%c", ch);
1134 snprintf(string, sizeof string,
1135 "%c%s escape not available to "
1136 "multiplexed sessions\r\n",
1138 buffer_append(berr, string,
1142 /* Suspend the program. Inform the user */
1143 snprintf(string, sizeof string,
1144 "%c^Z [suspend ssh]\r\n", escape_char);
1145 buffer_append(berr, string, strlen(string));
1147 /* Restore terminal modes and suspend. */
1148 client_suspend_self(bin, bout, berr);
1150 /* We have been continued. */
1155 snprintf(string, sizeof string,
1156 "%cB\r\n", escape_char);
1157 buffer_append(berr, string,
1159 channel_request_start(c->self,
1161 packet_put_int(1000);
1168 if (datafellows & SSH_BUG_NOREKEY)
1169 logit("Server does not "
1170 "support re-keying");
1179 if (c && c->ctl_chan != -1)
1181 if (!log_is_on_stderr()) {
1182 snprintf(string, sizeof string,
1183 "%c%c [Logging to syslog]\r\n",
1185 buffer_append(berr, string,
1189 if (ch == 'V' && options.log_level >
1191 log_change_level(--options.log_level);
1192 if (ch == 'v' && options.log_level <
1193 SYSLOG_LEVEL_DEBUG3)
1194 log_change_level(++options.log_level);
1195 snprintf(string, sizeof string,
1196 "%c%c [LogLevel %s]\r\n", escape_char, ch,
1197 log_level_name(options.log_level));
1198 buffer_append(berr, string, strlen(string));
1202 if (c && c->ctl_chan != -1)
1205 * Detach the program (continue to serve
1206 * connections, but put in background and no
1207 * more new connections).
1209 /* Restore tty modes. */
1211 options.request_tty == REQUEST_TTY_FORCE);
1213 /* Stop listening for new connections. */
1214 channel_stop_listening();
1216 snprintf(string, sizeof string,
1217 "%c& [backgrounded]\n", escape_char);
1218 buffer_append(berr, string, strlen(string));
1220 /* Fork into background. */
1223 error("fork: %.100s", strerror(errno));
1226 if (pid != 0) { /* This is the parent. */
1227 /* The parent just exits. */
1230 /* The child continues serving connections. */
1232 buffer_append(bin, "\004", 1);
1233 /* fake EOF on stdin */
1235 } else if (!stdin_eof) {
1237 * Sending SSH_CMSG_EOF alone does not
1238 * always appear to be enough. So we
1239 * try to send an EOF character first.
1241 packet_start(SSH_CMSG_STDIN_DATA);
1242 packet_put_string("\004", 1);
1246 if (buffer_len(bin) == 0) {
1247 packet_start(SSH_CMSG_EOF);
1254 print_escape_help(berr, escape_char, compat20,
1255 (c && c->ctl_chan != -1),
1256 log_is_on_stderr());
1260 snprintf(string, sizeof string, "%c#\r\n",
1262 buffer_append(berr, string, strlen(string));
1263 s = channel_open_message();
1264 buffer_append(berr, s, strlen(s));
1269 if (c && c->ctl_chan != -1)
1275 if (ch != escape_char) {
1276 buffer_put_char(bin, escape_char);
1279 /* Escaped characters fall through here */
1284 * The previous character was not an escape char.
1285 * Check if this is an escape.
1287 if (last_was_cr && ch == escape_char) {
1289 * It is. Set the flag and continue to
1292 *escape_pendingp = 1;
1298 * Normal character. Record whether it was a newline,
1299 * and append it to the buffer.
1301 last_was_cr = (ch == '\r' || ch == '\n');
1302 buffer_put_char(bin, ch);
1309 client_process_input(fd_set *readset)
1312 char buf[SSH_IOBUFSZ];
1314 /* Read input from stdin. */
1315 if (FD_ISSET(fileno(stdin), readset)) {
1316 /* Read as much as possible. */
1317 len = read(fileno(stdin), buf, sizeof(buf));
1319 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1320 return; /* we'll try again later */
1323 * Received EOF or error. They are treated
1324 * similarly, except that an error message is printed
1325 * if it was an error condition.
1328 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1330 buffer_append(&stderr_buffer, buf, strlen(buf));
1332 /* Mark that we have seen EOF. */
1335 * Send an EOF message to the server unless there is
1336 * data in the buffer. If there is data in the
1337 * buffer, no message will be sent now. Code
1338 * elsewhere will send the EOF when the buffer
1339 * becomes empty if stdin_eof is set.
1341 if (buffer_len(&stdin_buffer) == 0) {
1342 packet_start(SSH_CMSG_EOF);
1345 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1347 * Normal successful read, and no escape character.
1348 * Just append the data to buffer.
1350 buffer_append(&stdin_buffer, buf, len);
1353 * Normal, successful read. But we have an escape
1354 * character and have to process the characters one
1357 if (process_escapes(NULL, &stdin_buffer,
1358 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1365 client_process_output(fd_set *writeset)
1370 /* Write buffered output to stdout. */
1371 if (FD_ISSET(fileno(stdout), writeset)) {
1372 /* Write as much data as possible. */
1373 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1374 buffer_len(&stdout_buffer));
1376 if (errno == EINTR || errno == EAGAIN ||
1377 errno == EWOULDBLOCK)
1381 * An error or EOF was encountered. Put an
1382 * error message to stderr buffer.
1384 snprintf(buf, sizeof buf,
1385 "write stdout: %.50s\r\n", strerror(errno));
1386 buffer_append(&stderr_buffer, buf, strlen(buf));
1391 /* Consume printed data from the buffer. */
1392 buffer_consume(&stdout_buffer, len);
1394 /* Write buffered output to stderr. */
1395 if (FD_ISSET(fileno(stderr), writeset)) {
1396 /* Write as much data as possible. */
1397 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1398 buffer_len(&stderr_buffer));
1400 if (errno == EINTR || errno == EAGAIN ||
1401 errno == EWOULDBLOCK)
1405 * EOF or error, but can't even print
1412 /* Consume printed characters from the buffer. */
1413 buffer_consume(&stderr_buffer, len);
1418 * Get packets from the connection input buffer, and process them as long as
1419 * there are packets available.
1421 * Any unknown packets received during the actual
1422 * session cause the session to terminate. This is
1423 * intended to make debugging easier since no
1424 * confirmations are sent. Any compatible protocol
1425 * extensions must be negotiated during the
1426 * preparatory phase.
1430 client_process_buffered_input_packets(void)
1432 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, active_state);
1435 /* scan buf[] for '~' before sending data to the peer */
1437 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1439 client_new_escape_filter_ctx(int escape_char)
1441 struct escape_filter_ctx *ret;
1443 ret = xcalloc(1, sizeof(*ret));
1444 ret->escape_pending = 0;
1445 ret->escape_char = escape_char;
1449 /* Free the escape filter context on channel free */
1451 client_filter_cleanup(int cid, void *ctx)
1457 client_simple_escape_filter(Channel *c, char *buf, int len)
1459 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1462 return process_escapes(c, &c->input, &c->output, &c->extended,
1467 client_channel_closed(int id, void *arg)
1469 channel_cancel_cleanup(id);
1471 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1475 * Implements the interactive session with the server. This is called after
1476 * the user has been authenticated, and a command has been started on the
1477 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1478 * used as an escape character for terminating or suspending the session.
1482 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1484 fd_set *readset = NULL, *writeset = NULL;
1485 double start_time, total_time;
1486 int r, max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1487 u_int64_t ibytes, obytes;
1491 debug("Entering interactive session.");
1493 start_time = get_current_time();
1495 /* Initialize variables. */
1496 escape_pending1 = 0;
1500 buffer_high = 64 * 1024;
1501 connection_in = packet_get_connection_in();
1502 connection_out = packet_get_connection_out();
1503 max_fd = MAX(connection_in, connection_out);
1506 /* enable nonblocking unless tty */
1507 if (!isatty(fileno(stdin)))
1508 set_nonblock(fileno(stdin));
1509 if (!isatty(fileno(stdout)))
1510 set_nonblock(fileno(stdout));
1511 if (!isatty(fileno(stderr)))
1512 set_nonblock(fileno(stderr));
1513 max_fd = MAX(max_fd, fileno(stdin));
1514 max_fd = MAX(max_fd, fileno(stdout));
1515 max_fd = MAX(max_fd, fileno(stderr));
1518 escape_char1 = escape_char_arg;
1520 /* Initialize buffers. */
1521 buffer_init(&stdin_buffer);
1522 buffer_init(&stdout_buffer);
1523 buffer_init(&stderr_buffer);
1525 client_init_dispatch();
1528 * Set signal handlers, (e.g. to restore non-blocking mode)
1529 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1531 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1532 signal(SIGHUP, signal_handler);
1533 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1534 signal(SIGINT, signal_handler);
1535 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1536 signal(SIGQUIT, signal_handler);
1537 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1538 signal(SIGTERM, signal_handler);
1539 signal(SIGWINCH, window_change_handler);
1542 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1545 session_ident = ssh2_chan_id;
1546 if (session_ident != -1) {
1547 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1548 channel_register_filter(session_ident,
1549 client_simple_escape_filter, NULL,
1550 client_filter_cleanup,
1551 client_new_escape_filter_ctx(
1554 channel_register_cleanup(session_ident,
1555 client_channel_closed, 0);
1558 /* Check if we should immediately send eof on stdin. */
1559 client_check_initial_eof_on_stdin();
1562 /* Main loop of the client for the interactive session mode. */
1563 while (!quit_pending) {
1565 /* Process buffered packets sent by the server. */
1566 client_process_buffered_input_packets();
1568 if (compat20 && session_closed && !channel_still_open())
1571 rekeying = (active_state->kex != NULL && !active_state->kex->done);
1574 debug("rekeying in progress");
1577 * Make packets of buffered stdin data, and buffer
1578 * them for sending to the server.
1581 client_make_packets_from_stdin_data();
1584 * Make packets from buffered channel data, and
1585 * enqueue them for sending to the server.
1587 if (packet_not_very_much_data_to_write())
1588 channel_output_poll();
1591 * Check if the window size has changed, and buffer a
1592 * message about it to the server if so.
1594 client_check_window_change();
1600 * Wait until we have something to do (something becomes
1601 * available on one of the descriptors).
1604 client_wait_until_can_do_something(&readset, &writeset,
1605 &max_fd2, &nalloc, rekeying);
1610 /* Do channel operations unless rekeying in progress. */
1612 channel_after_select(readset, writeset);
1613 if (need_rekeying || packet_need_rekeying()) {
1614 debug("need rekeying");
1615 active_state->kex->done = 0;
1616 if ((r = kex_send_kexinit(active_state)) != 0)
1617 fatal("%s: kex_send_kexinit: %s",
1618 __func__, ssh_err(r));
1623 /* Buffer input from the connection. */
1624 client_process_net_input(readset);
1630 /* Buffer data from stdin */
1631 client_process_input(readset);
1633 * Process output to stdout and stderr. Output to
1634 * the connection is processed elsewhere (above).
1636 client_process_output(writeset);
1639 if (session_resumed) {
1640 connection_in = packet_get_connection_in();
1641 connection_out = packet_get_connection_out();
1642 max_fd = MAX(max_fd, connection_out);
1643 max_fd = MAX(max_fd, connection_in);
1644 session_resumed = 0;
1648 * Send as much buffered packet data as possible to the
1651 if (FD_ISSET(connection_out, writeset))
1652 packet_write_poll();
1655 * If we are a backgrounded control master, and the
1656 * timeout has expired without any active client
1657 * connections, then quit.
1659 if (control_persist_exit_time > 0) {
1660 if (monotime() >= control_persist_exit_time) {
1661 debug("ControlPersist timeout expired");
1669 /* Terminate the session. */
1671 /* Stop watching for window change. */
1672 signal(SIGWINCH, SIG_DFL);
1675 packet_start(SSH2_MSG_DISCONNECT);
1676 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1677 packet_put_cstring("disconnected by user");
1678 packet_put_cstring(""); /* language tag */
1680 packet_write_wait();
1686 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1688 /* restore blocking io */
1689 if (!isatty(fileno(stdin)))
1690 unset_nonblock(fileno(stdin));
1691 if (!isatty(fileno(stdout)))
1692 unset_nonblock(fileno(stdout));
1693 if (!isatty(fileno(stderr)))
1694 unset_nonblock(fileno(stderr));
1697 * If there was no shell or command requested, there will be no remote
1698 * exit status to be returned. In that case, clear error code if the
1699 * connection was deliberately terminated at this end.
1701 if (no_shell_flag && received_signal == SIGTERM) {
1702 received_signal = 0;
1706 if (received_signal)
1707 fatal("Killed by signal %d.", (int) received_signal);
1710 * In interactive mode (with pseudo tty) display a message indicating
1711 * that the connection has been closed.
1713 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1714 snprintf(buf, sizeof buf,
1715 "Connection to %.64s closed.\r\n", host);
1716 buffer_append(&stderr_buffer, buf, strlen(buf));
1719 /* Output any buffered data for stdout. */
1720 if (buffer_len(&stdout_buffer) > 0) {
1721 len = atomicio(vwrite, fileno(stdout),
1722 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1723 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1724 error("Write failed flushing stdout buffer.");
1726 buffer_consume(&stdout_buffer, len);
1729 /* Output any buffered data for stderr. */
1730 if (buffer_len(&stderr_buffer) > 0) {
1731 len = atomicio(vwrite, fileno(stderr),
1732 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1733 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1734 error("Write failed flushing stderr buffer.");
1736 buffer_consume(&stderr_buffer, len);
1739 /* Clear and free any buffers. */
1740 memset(buf, 0, sizeof(buf));
1741 buffer_free(&stdin_buffer);
1742 buffer_free(&stdout_buffer);
1743 buffer_free(&stderr_buffer);
1745 /* Report bytes transferred, and transfer rates. */
1746 total_time = get_current_time() - start_time;
1747 packet_get_bytes(&ibytes, &obytes);
1748 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1749 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1751 verbose("Bytes per second: sent %.1f, received %.1f",
1752 obytes / total_time, ibytes / total_time);
1753 /* Return the exit status of the program. */
1754 debug("Exit status %d", exit_status);
1761 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1764 char *data = packet_get_string(&data_len);
1766 buffer_append(&stdout_buffer, data, data_len);
1767 explicit_bzero(data, data_len);
1772 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1775 char *data = packet_get_string(&data_len);
1777 buffer_append(&stderr_buffer, data, data_len);
1778 explicit_bzero(data, data_len);
1783 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1785 exit_status = packet_get_int();
1787 /* Acknowledge the exit. */
1788 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1791 * Must wait for packet to be sent since we are
1794 packet_write_wait();
1795 /* Flag that we want to exit. */
1801 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1804 int r, remote_id, sock;
1806 /* Read the remote channel number from the message. */
1807 remote_id = packet_get_int();
1811 * Get a connection to the local authentication agent (this may again
1814 if ((r = ssh_get_authentication_socket(&sock)) != 0 &&
1815 r != SSH_ERR_AGENT_NOT_PRESENT)
1816 debug("%s: ssh_get_authentication_socket: %s",
1817 __func__, ssh_err(r));
1821 * If we could not connect the agent, send an error message back to
1822 * the server. This should never happen unless the agent dies,
1823 * because authentication forwarding is only enabled if we have an
1827 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1828 -1, 0, 0, 0, "authentication agent connection", 1);
1829 c->remote_id = remote_id;
1833 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1834 packet_put_int(remote_id);
1836 /* Send a confirmation to the remote host. */
1837 debug("Forwarding authentication connection.");
1838 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1839 packet_put_int(remote_id);
1840 packet_put_int(c->self);
1847 client_request_forwarded_tcpip(const char *request_type, int rchan)
1850 char *listen_address, *originator_address;
1851 u_short listen_port, originator_port;
1853 /* Get rest of the packet */
1854 listen_address = packet_get_string(NULL);
1855 listen_port = packet_get_int();
1856 originator_address = packet_get_string(NULL);
1857 originator_port = packet_get_int();
1860 debug("%s: listen %s port %d, originator %s port %d", __func__,
1861 listen_address, listen_port, originator_address, originator_port);
1863 c = channel_connect_by_listen_address(listen_address, listen_port,
1864 "forwarded-tcpip", originator_address);
1866 free(originator_address);
1867 free(listen_address);
1872 client_request_forwarded_streamlocal(const char *request_type, int rchan)
1877 /* Get the remote path. */
1878 listen_path = packet_get_string(NULL);
1879 /* XXX: Skip reserved field for now. */
1880 if (packet_get_string_ptr(NULL) == NULL)
1881 fatal("%s: packet_get_string_ptr failed", __func__);
1884 debug("%s: %s", __func__, listen_path);
1886 c = channel_connect_by_listen_path(listen_path,
1887 "forwarded-streamlocal@openssh.com", "forwarded-streamlocal");
1893 client_request_x11(const char *request_type, int rchan)
1897 u_short originator_port;
1900 if (!options.forward_x11) {
1901 error("Warning: ssh server tried X11 forwarding.");
1902 error("Warning: this is probably a break-in attempt by a "
1903 "malicious server.");
1906 if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) {
1907 verbose("Rejected X11 connection after ForwardX11Timeout "
1911 originator = packet_get_string(NULL);
1912 if (datafellows & SSH_BUG_X11FWD) {
1913 debug2("buggy server: x11 request w/o originator_port");
1914 originator_port = 0;
1916 originator_port = packet_get_int();
1919 /* XXX check permission */
1920 debug("client_request_x11: request from %s %d", originator,
1923 sock = x11_connect_display();
1926 c = channel_new("x11",
1927 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1928 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1934 client_request_agent(const char *request_type, int rchan)
1939 if (!options.forward_agent) {
1940 error("Warning: ssh server tried agent forwarding.");
1941 error("Warning: this is probably a break-in attempt by a "
1942 "malicious server.");
1945 if ((r = ssh_get_authentication_socket(&sock)) != 0) {
1946 if (r != SSH_ERR_AGENT_NOT_PRESENT)
1947 debug("%s: ssh_get_authentication_socket: %s",
1948 __func__, ssh_err(r));
1951 c = channel_new("authentication agent connection",
1952 SSH_CHANNEL_OPEN, sock, sock, -1,
1953 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1954 "authentication agent connection", 1);
1960 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1965 if (tun_mode == SSH_TUNMODE_NO)
1969 error("Tunnel forwarding is not supported for protocol 1");
1973 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1975 /* Open local tunnel device */
1976 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1977 error("Tunnel device open failed.");
1981 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1982 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1985 #if defined(SSH_TUN_FILTER)
1986 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1987 channel_register_filter(c->self, sys_tun_infilter,
1988 sys_tun_outfilter, NULL, NULL);
1991 packet_start(SSH2_MSG_CHANNEL_OPEN);
1992 packet_put_cstring("tun@openssh.com");
1993 packet_put_int(c->self);
1994 packet_put_int(c->local_window_max);
1995 packet_put_int(c->local_maxpacket);
1996 packet_put_int(tun_mode);
1997 packet_put_int(remote_tun);
2003 /* XXXX move to generic input handler */
2005 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
2010 u_int rmaxpack, rwindow, len;
2012 ctype = packet_get_string(&len);
2013 rchan = packet_get_int();
2014 rwindow = packet_get_int();
2015 rmaxpack = packet_get_int();
2017 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2018 ctype, rchan, rwindow, rmaxpack);
2020 if (strcmp(ctype, "forwarded-tcpip") == 0) {
2021 c = client_request_forwarded_tcpip(ctype, rchan);
2022 } else if (strcmp(ctype, "forwarded-streamlocal@openssh.com") == 0) {
2023 c = client_request_forwarded_streamlocal(ctype, rchan);
2024 } else if (strcmp(ctype, "x11") == 0) {
2025 c = client_request_x11(ctype, rchan);
2026 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2027 c = client_request_agent(ctype, rchan);
2029 /* XXX duplicate : */
2031 debug("confirm %s", ctype);
2032 c->remote_id = rchan;
2033 c->remote_window = rwindow;
2034 c->remote_maxpacket = rmaxpack;
2035 if (c->type != SSH_CHANNEL_CONNECTING) {
2036 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2037 packet_put_int(c->remote_id);
2038 packet_put_int(c->self);
2039 packet_put_int(c->local_window);
2040 packet_put_int(c->local_maxpacket);
2044 debug("failure %s", ctype);
2045 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2046 packet_put_int(rchan);
2047 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2048 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2049 packet_put_cstring("open failed");
2050 packet_put_cstring("");
2059 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2062 int exitval, id, reply, success = 0;
2065 id = packet_get_int();
2066 rtype = packet_get_string(NULL);
2067 reply = packet_get_char();
2069 debug("client_input_channel_req: channel %d rtype %s reply %d",
2073 error("client_input_channel_req: request for channel -1");
2074 } else if ((c = channel_lookup(id)) == NULL) {
2075 error("client_input_channel_req: channel %d: "
2076 "unknown channel", id);
2077 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
2080 } else if (strcmp(rtype, "exit-status") == 0) {
2081 exitval = packet_get_int();
2082 if (c->ctl_chan != -1) {
2083 mux_exit_message(c, exitval);
2085 } else if (id == session_ident) {
2086 /* Record exit value of local session */
2088 exit_status = exitval;
2090 /* Probably for a mux channel that has already closed */
2091 debug("%s: no sink for exit-status on channel %d",
2096 if (reply && c != NULL && !(c->flags & CHAN_CLOSE_SENT)) {
2097 packet_start(success ?
2098 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2099 packet_put_int(c->remote_id);
2106 struct hostkeys_update_ctx {
2107 /* The hostname and (optionally) IP address string for the server */
2108 char *host_str, *ip_str;
2111 * Keys received from the server and a flag for each indicating
2112 * whether they already exist in known_hosts.
2113 * keys_seen is filled in by hostkeys_find() and later (for new
2114 * keys) by client_global_hostkeys_private_confirm().
2116 struct sshkey **keys;
2123 * Keys that are in known_hosts, but were not present in the update
2124 * from the server (i.e. scheduled to be deleted).
2125 * Filled in by hostkeys_find().
2127 struct sshkey **old_keys;
2132 hostkeys_update_ctx_free(struct hostkeys_update_ctx *ctx)
2138 for (i = 0; i < ctx->nkeys; i++)
2139 sshkey_free(ctx->keys[i]);
2141 free(ctx->keys_seen);
2142 for (i = 0; i < ctx->nold; i++)
2143 sshkey_free(ctx->old_keys[i]);
2144 free(ctx->old_keys);
2145 free(ctx->host_str);
2151 hostkeys_find(struct hostkey_foreach_line *l, void *_ctx)
2153 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2155 struct sshkey **tmp;
2157 if (l->status != HKF_STATUS_MATCHED || l->key == NULL ||
2158 l->key->type == KEY_RSA1)
2161 /* Mark off keys we've already seen for this host */
2162 for (i = 0; i < ctx->nkeys; i++) {
2163 if (sshkey_equal(l->key, ctx->keys[i])) {
2164 debug3("%s: found %s key at %s:%ld", __func__,
2165 sshkey_ssh_name(ctx->keys[i]), l->path, l->linenum);
2166 ctx->keys_seen[i] = 1;
2170 /* This line contained a key that not offered by the server */
2171 debug3("%s: deprecated %s key at %s:%ld", __func__,
2172 sshkey_ssh_name(l->key), l->path, l->linenum);
2173 if ((tmp = reallocarray(ctx->old_keys, ctx->nold + 1,
2174 sizeof(*ctx->old_keys))) == NULL)
2175 fatal("%s: reallocarray failed nold = %zu",
2176 __func__, ctx->nold);
2177 ctx->old_keys = tmp;
2178 ctx->old_keys[ctx->nold++] = l->key;
2185 update_known_hosts(struct hostkeys_update_ctx *ctx)
2188 int loglevel = options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK ?
2189 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_VERBOSE;
2190 char *fp, *response;
2193 for (i = 0; i < ctx->nkeys; i++) {
2194 if (ctx->keys_seen[i] != 2)
2196 if ((fp = sshkey_fingerprint(ctx->keys[i],
2197 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2198 fatal("%s: sshkey_fingerprint failed", __func__);
2199 do_log2(loglevel, "Learned new hostkey: %s %s",
2200 sshkey_type(ctx->keys[i]), fp);
2203 for (i = 0; i < ctx->nold; i++) {
2204 if ((fp = sshkey_fingerprint(ctx->old_keys[i],
2205 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL)
2206 fatal("%s: sshkey_fingerprint failed", __func__);
2207 do_log2(loglevel, "Deprecating obsolete hostkey: %s %s",
2208 sshkey_type(ctx->old_keys[i]), fp);
2211 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK) {
2212 if (get_saved_tio() != NULL) {
2217 for (i = 0; !quit_pending && i < 3; i++) {
2219 response = read_passphrase("Accept updated hostkeys? "
2220 "(yes/no): ", RP_ECHO);
2221 if (strcasecmp(response, "yes") == 0)
2223 else if (quit_pending || response == NULL ||
2224 strcasecmp(response, "no") == 0) {
2225 options.update_hostkeys = 0;
2228 do_log2(loglevel, "Please enter "
2229 "\"yes\" or \"no\"");
2232 if (quit_pending || i >= 3 || response == NULL)
2233 options.update_hostkeys = 0;
2240 * Now that all the keys are verified, we can go ahead and replace
2241 * them in known_hosts (assuming SSH_UPDATE_HOSTKEYS_ASK didn't
2242 * cancel the operation).
2244 if (options.update_hostkeys != 0 &&
2245 (r = hostfile_replace_entries(options.user_hostfiles[0],
2246 ctx->host_str, ctx->ip_str, ctx->keys, ctx->nkeys,
2247 options.hash_known_hosts, 0,
2248 options.fingerprint_hash)) != 0)
2249 error("%s: hostfile_replace_entries failed: %s",
2250 __func__, ssh_err(r));
2254 client_global_hostkeys_private_confirm(int type, u_int32_t seq, void *_ctx)
2256 struct ssh *ssh = active_state; /* XXX */
2257 struct hostkeys_update_ctx *ctx = (struct hostkeys_update_ctx *)_ctx;
2259 struct sshbuf *signdata;
2265 fatal("%s: ctx->nnew == 0", __func__); /* sanity */
2266 if (type != SSH2_MSG_REQUEST_SUCCESS) {
2267 error("Server failed to confirm ownership of "
2268 "private host keys");
2269 hostkeys_update_ctx_free(ctx);
2272 if ((signdata = sshbuf_new()) == NULL)
2273 fatal("%s: sshbuf_new failed", __func__);
2274 /* Don't want to accidentally accept an unbound signature */
2275 if (ssh->kex->session_id_len == 0)
2276 fatal("%s: ssh->kex->session_id_len == 0", __func__);
2278 * Expect a signature for each of the ctx->nnew private keys we
2279 * haven't seen before. They will be in the same order as the
2280 * ctx->keys where the corresponding ctx->keys_seen[i] == 0.
2282 for (ndone = i = 0; i < ctx->nkeys; i++) {
2283 if (ctx->keys_seen[i])
2285 /* Prepare data to be signed: session ID, unique string, key */
2286 sshbuf_reset(signdata);
2287 if ( (r = sshbuf_put_cstring(signdata,
2288 "hostkeys-prove-00@openssh.com")) != 0 ||
2289 (r = sshbuf_put_string(signdata, ssh->kex->session_id,
2290 ssh->kex->session_id_len)) != 0 ||
2291 (r = sshkey_puts(ctx->keys[i], signdata)) != 0)
2292 fatal("%s: failed to prepare signature: %s",
2293 __func__, ssh_err(r));
2294 /* Extract and verify signature */
2295 if ((r = sshpkt_get_string_direct(ssh, &sig, &siglen)) != 0) {
2296 error("%s: couldn't parse message: %s",
2297 __func__, ssh_err(r));
2300 if ((r = sshkey_verify(ctx->keys[i], sig, siglen,
2301 sshbuf_ptr(signdata), sshbuf_len(signdata), 0)) != 0) {
2302 error("%s: server gave bad signature for %s key %zu",
2303 __func__, sshkey_type(ctx->keys[i]), i);
2306 /* Key is good. Mark it as 'seen' */
2307 ctx->keys_seen[i] = 2;
2310 if (ndone != ctx->nnew)
2311 fatal("%s: ndone != ctx->nnew (%zu / %zu)", __func__,
2312 ndone, ctx->nnew); /* Shouldn't happen */
2313 ssh_packet_check_eom(ssh);
2315 /* Make the edits to known_hosts */
2316 update_known_hosts(ctx);
2318 hostkeys_update_ctx_free(ctx);
2322 * Handle hostkeys-00@openssh.com global request to inform the client of all
2323 * the server's hostkeys. The keys are checked against the user's
2324 * HostkeyAlgorithms preference before they are accepted.
2327 client_input_hostkeys(void)
2329 struct ssh *ssh = active_state; /* XXX */
2330 const u_char *blob = NULL;
2332 struct sshbuf *buf = NULL;
2333 struct sshkey *key = NULL, **tmp;
2336 static int hostkeys_seen = 0; /* XXX use struct ssh */
2337 extern struct sockaddr_storage hostaddr; /* XXX from ssh.c */
2338 struct hostkeys_update_ctx *ctx = NULL;
2341 fatal("%s: server already sent hostkeys", __func__);
2342 if (options.update_hostkeys == SSH_UPDATE_HOSTKEYS_ASK &&
2344 return 1; /* won't ask in batchmode, so don't even try */
2345 if (!options.update_hostkeys || options.num_user_hostfiles <= 0)
2348 ctx = xcalloc(1, sizeof(*ctx));
2349 while (ssh_packet_remaining(ssh) > 0) {
2352 if ((r = sshpkt_get_string_direct(ssh, &blob, &len)) != 0) {
2353 error("%s: couldn't parse message: %s",
2354 __func__, ssh_err(r));
2357 if ((r = sshkey_from_blob(blob, len, &key)) != 0) {
2358 error("%s: parse key: %s", __func__, ssh_err(r));
2361 fp = sshkey_fingerprint(key, options.fingerprint_hash,
2363 debug3("%s: received %s key %s", __func__,
2364 sshkey_type(key), fp);
2367 /* Check that the key is accepted in HostkeyAlgorithms */
2368 if (match_pattern_list(sshkey_ssh_name(key),
2369 options.hostkeyalgorithms ? options.hostkeyalgorithms :
2370 KEX_DEFAULT_PK_ALG, 0) != 1) {
2371 debug3("%s: %s key not permitted by HostkeyAlgorithms",
2372 __func__, sshkey_ssh_name(key));
2376 if (sshkey_is_cert(key)) {
2377 debug3("%s: %s key is a certificate; skipping",
2378 __func__, sshkey_ssh_name(key));
2381 /* Ensure keys are unique */
2382 for (i = 0; i < ctx->nkeys; i++) {
2383 if (sshkey_equal(key, ctx->keys[i])) {
2384 error("%s: received duplicated %s host key",
2385 __func__, sshkey_ssh_name(key));
2389 /* Key is good, record it */
2390 if ((tmp = reallocarray(ctx->keys, ctx->nkeys + 1,
2391 sizeof(*ctx->keys))) == NULL)
2392 fatal("%s: reallocarray failed nkeys = %zu",
2393 __func__, ctx->nkeys);
2395 ctx->keys[ctx->nkeys++] = key;
2399 if (ctx->nkeys == 0) {
2400 debug("%s: server sent no hostkeys", __func__);
2404 if ((ctx->keys_seen = calloc(ctx->nkeys,
2405 sizeof(*ctx->keys_seen))) == NULL)
2406 fatal("%s: calloc failed", __func__);
2408 get_hostfile_hostname_ipaddr(host,
2409 options.check_host_ip ? (struct sockaddr *)&hostaddr : NULL,
2410 options.port, &ctx->host_str,
2411 options.check_host_ip ? &ctx->ip_str : NULL);
2413 /* Find which keys we already know about. */
2414 if ((r = hostkeys_foreach(options.user_hostfiles[0], hostkeys_find,
2415 ctx, ctx->host_str, ctx->ip_str,
2416 HKF_WANT_PARSE_KEY|HKF_WANT_MATCH)) != 0) {
2417 error("%s: hostkeys_foreach failed: %s", __func__, ssh_err(r));
2421 /* Figure out if we have any new keys to add */
2423 for (i = 0; i < ctx->nkeys; i++) {
2424 if (!ctx->keys_seen[i])
2428 debug3("%s: %zu keys from server: %zu new, %zu retained. %zu to remove",
2429 __func__, ctx->nkeys, ctx->nnew, ctx->nkeys - ctx->nnew, ctx->nold);
2431 if (ctx->nnew == 0 && ctx->nold != 0) {
2432 /* We have some keys to remove. Just do it. */
2433 update_known_hosts(ctx);
2434 } else if (ctx->nnew != 0) {
2436 * We have received hitherto-unseen keys from the server.
2437 * Ask the server to confirm ownership of the private halves.
2439 debug3("%s: asking server to prove ownership for %zu keys",
2440 __func__, ctx->nnew);
2441 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
2442 (r = sshpkt_put_cstring(ssh,
2443 "hostkeys-prove-00@openssh.com")) != 0 ||
2444 (r = sshpkt_put_u8(ssh, 1)) != 0) /* bool: want reply */
2445 fatal("%s: cannot prepare packet: %s",
2446 __func__, ssh_err(r));
2447 if ((buf = sshbuf_new()) == NULL)
2448 fatal("%s: sshbuf_new", __func__);
2449 for (i = 0; i < ctx->nkeys; i++) {
2450 if (ctx->keys_seen[i])
2453 if ((r = sshkey_putb(ctx->keys[i], buf)) != 0)
2454 fatal("%s: sshkey_putb: %s",
2455 __func__, ssh_err(r));
2456 if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
2457 fatal("%s: sshpkt_put_string: %s",
2458 __func__, ssh_err(r));
2460 if ((r = sshpkt_send(ssh)) != 0)
2461 fatal("%s: sshpkt_send: %s", __func__, ssh_err(r));
2462 client_register_global_confirm(
2463 client_global_hostkeys_private_confirm, ctx);
2464 ctx = NULL; /* will be freed in callback */
2469 hostkeys_update_ctx_free(ctx);
2473 * NB. Return success for all cases. The server doesn't need to know
2474 * what the client does with its hosts file.
2480 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2486 rtype = packet_get_cstring(NULL);
2487 want_reply = packet_get_char();
2488 debug("client_input_global_request: rtype %s want_reply %d",
2490 if (strcmp(rtype, "hostkeys-00@openssh.com") == 0)
2491 success = client_input_hostkeys();
2493 packet_start(success ?
2494 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2496 packet_write_wait();
2503 client_session2_setup(int id, int want_tty, int want_subsystem,
2504 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2509 debug2("%s: id %d", __func__, id);
2511 if ((c = channel_lookup(id)) == NULL)
2512 fatal("client_session2_setup: channel %d: unknown channel", id);
2514 packet_set_interactive(want_tty,
2515 options.ip_qos_interactive, options.ip_qos_bulk);
2520 /* Store window size in the packet. */
2521 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2522 memset(&ws, 0, sizeof(ws));
2524 channel_request_start(id, "pty-req", 1);
2525 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2526 packet_put_cstring(term != NULL ? term : "");
2527 packet_put_int((u_int)ws.ws_col);
2528 packet_put_int((u_int)ws.ws_row);
2529 packet_put_int((u_int)ws.ws_xpixel);
2530 packet_put_int((u_int)ws.ws_ypixel);
2532 tiop = get_saved_tio();
2533 tty_make_modes(-1, tiop);
2535 /* XXX wait for reply */
2539 /* Transfer any environment variables from client to server */
2540 if (options.num_send_env != 0 && env != NULL) {
2544 debug("Sending environment.");
2545 for (i = 0; env[i] != NULL; i++) {
2547 name = xstrdup(env[i]);
2548 if ((val = strchr(name, '=')) == NULL) {
2555 for (j = 0; j < options.num_send_env; j++) {
2556 if (match_pattern(name, options.send_env[j])) {
2562 debug3("Ignored env %s", name);
2567 debug("Sending env %s = %s", name, val);
2568 channel_request_start(id, "env", 0);
2569 packet_put_cstring(name);
2570 packet_put_cstring(val);
2576 len = buffer_len(cmd);
2580 if (want_subsystem) {
2581 debug("Sending subsystem: %.*s",
2582 len, (u_char*)buffer_ptr(cmd));
2583 channel_request_start(id, "subsystem", 1);
2584 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2586 debug("Sending command: %.*s",
2587 len, (u_char*)buffer_ptr(cmd));
2588 channel_request_start(id, "exec", 1);
2589 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2591 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2594 channel_request_start(id, "shell", 1);
2595 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2601 client_init_dispatch_20(void)
2603 dispatch_init(&dispatch_protocol_error);
2605 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2606 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2607 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2608 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2609 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2610 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2611 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2612 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2613 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2614 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2615 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2616 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2619 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2621 /* global request reply messages */
2622 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2623 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2627 client_init_dispatch_13(void)
2629 dispatch_init(NULL);
2630 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2631 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2632 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2633 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2634 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2635 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2636 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2637 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2638 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2640 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2641 &client_input_agent_open : &deny_input_open);
2642 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2643 &x11_input_open : &deny_input_open);
2647 client_init_dispatch_15(void)
2649 client_init_dispatch_13();
2650 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2651 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2655 client_init_dispatch(void)
2658 client_init_dispatch_20();
2660 client_init_dispatch_13();
2662 client_init_dispatch_15();
2666 client_stop_mux(void)
2668 if (options.control_path != NULL && muxserver_sock != -1)
2669 unlink(options.control_path);
2671 * If we are in persist mode, or don't have a shell, signal that we
2672 * should close when all active channels are closed.
2674 if (options.control_persist || no_shell_flag) {
2676 setproctitle("[stopped mux]");
2680 /* client specific fatal cleanup */
2684 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2685 leave_non_blocking();
2686 if (options.control_path != NULL && muxserver_sock != -1)
2687 unlink(options.control_path);
2688 ssh_kill_proxy_command();