1 /* $OpenBSD: clientloop.c,v 1.236 2011/06/22 22:08:42 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * The main loop for the interactive session (client side).
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
16 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
27 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 * SSH2 support added by Markus Friedl.
40 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
51 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
52 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
53 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
54 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
55 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
60 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65 #include <sys/types.h>
66 #include <sys/ioctl.h>
67 #include <sys/param.h>
68 #ifdef HAVE_SYS_STAT_H
69 # include <sys/stat.h>
71 #ifdef HAVE_SYS_TIME_H
72 # include <sys/time.h>
74 #include <sys/socket.h>
90 #include "openbsd-compat/sys-queue.h"
104 #include "readconf.h"
105 #include "clientloop.h"
106 #include "sshconnect.h"
108 #include "atomicio.h"
116 extern Options options;
118 /* Flag indicating that stdin should be redirected from /dev/null. */
119 extern int stdin_null_flag;
121 /* Flag indicating that no shell has been requested */
122 extern int no_shell_flag;
125 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
128 * Name of the host we are connecting to. This is the name given on the
129 * command line, or the HostName specified for the user-supplied name in a
130 * configuration file.
135 * Flag to indicate that we have received a window change signal which has
136 * not yet been processed. This will cause a message indicating the new
137 * window size to be sent to the server a little later. This is volatile
138 * because this is updated in a signal handler.
140 static volatile sig_atomic_t received_window_change_signal = 0;
141 static volatile sig_atomic_t received_signal = 0;
143 /* Flag indicating whether the user's terminal is in non-blocking mode. */
144 static int in_non_blocking_mode = 0;
146 /* Time when backgrounded control master using ControlPersist should exit */
147 static time_t control_persist_exit_time = 0;
149 /* Common data for the client loop code. */
150 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
151 static int escape_char1; /* Escape character. (proto1 only) */
152 static int escape_pending1; /* Last character was an escape (proto1 only) */
153 static int last_was_cr; /* Last character was a newline. */
154 static int exit_status; /* Used to store the command exit status. */
155 static int stdin_eof; /* EOF has been encountered on stderr. */
156 static Buffer stdin_buffer; /* Buffer for stdin data. */
157 static Buffer stdout_buffer; /* Buffer for stdout data. */
158 static Buffer stderr_buffer; /* Buffer for stderr data. */
159 static u_int buffer_high; /* Soft max buffer size. */
160 static int connection_in; /* Connection to server (input). */
161 static int connection_out; /* Connection to server (output). */
162 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
163 static int session_closed; /* In SSH2: login session closed. */
164 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
166 static void client_init_dispatch(void);
167 int session_ident = -1;
169 int session_resumed = 0;
171 /* Track escape per proto2 channel */
172 struct escape_filter_ctx {
177 /* Context for channel confirmation replies */
178 struct channel_reply_ctx {
179 const char *request_type;
181 enum confirm_action action;
184 /* Global request success/failure callbacks */
185 struct global_confirm {
186 TAILQ_ENTRY(global_confirm) entry;
187 global_confirm_cb *cb;
191 TAILQ_HEAD(global_confirms, global_confirm);
192 static struct global_confirms global_confirms =
193 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 = time(NULL) +
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_PROTO "MIT-MAGIC-COOKIE-1"
287 client_x11_get_proto(const char *display, const char *xauth_path,
288 u_int trusted, u_int timeout, char **_proto, char **_data)
293 static char proto[512], data[512];
295 int got_data = 0, generated = 0, do_unlink = 0, i;
296 char *xauthdir, *xauthfile;
300 xauthdir = xauthfile = NULL;
303 proto[0] = data[0] = '\0';
305 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
306 debug("No xauth program.");
308 if (display == NULL) {
309 debug("x11_get_proto: DISPLAY not set");
313 * Handle FamilyLocal case where $DISPLAY does
314 * not match an authorization entry. For this we
315 * just try "xauth list unix:displaynum.screennum".
316 * XXX: "localhost" match to determine FamilyLocal
319 if (strncmp(display, "localhost:", 10) == 0) {
320 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
325 xauthdir = xmalloc(MAXPATHLEN);
326 xauthfile = xmalloc(MAXPATHLEN);
327 mktemp_proto(xauthdir, MAXPATHLEN);
328 if (mkdtemp(xauthdir) != NULL) {
330 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
332 snprintf(cmd, sizeof(cmd),
333 "%s -f %s generate %s " SSH_X11_PROTO
334 " untrusted timeout %u 2>" _PATH_DEVNULL,
335 xauth_path, xauthfile, display, timeout);
336 debug2("x11_get_proto: %s", cmd);
337 if (system(cmd) == 0)
339 if (x11_refuse_time == 0) {
340 now = time(NULL) + 1;
341 if (UINT_MAX - timeout < now)
342 x11_refuse_time = UINT_MAX;
344 x11_refuse_time = now + timeout;
350 * When in untrusted mode, we read the cookie only if it was
351 * successfully generated as an untrusted one in the step
354 if (trusted || generated) {
355 snprintf(cmd, sizeof(cmd),
356 "%s %s%s list %s 2>" _PATH_DEVNULL,
358 generated ? "-f " : "" ,
359 generated ? xauthfile : "",
361 debug2("x11_get_proto: %s", cmd);
363 if (f && fgets(line, sizeof(line), f) &&
364 sscanf(line, "%*s %511s %511s", proto, data) == 2)
369 error("Warning: untrusted X11 forwarding setup failed: "
370 "xauth key data not generated");
383 * If we didn't get authentication data, just make up some
384 * data. The forwarding code will check the validity of the
385 * response anyway, and substitute this data. The X11
386 * server, however, will ignore this fake data and use
387 * whatever authentication mechanisms it was using otherwise
388 * for the local connection.
393 logit("Warning: No xauth data; "
394 "using fake authentication data for X11 forwarding.");
395 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
396 for (i = 0; i < 16; i++) {
399 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
407 * This is called when the interactive is entered. This checks if there is
408 * an EOF coming on stdin. We must check this explicitly, as select() does
409 * not appear to wake up when redirecting from /dev/null.
413 client_check_initial_eof_on_stdin(void)
419 * If standard input is to be "redirected from /dev/null", we simply
420 * mark that we have seen an EOF and send an EOF message to the
421 * server. Otherwise, we try to read a single character; it appears
422 * that for some files, such /dev/null, select() never wakes up for
423 * read for this descriptor, which means that we never get EOF. This
424 * way we will get the EOF if stdin comes from /dev/null or similar.
426 if (stdin_null_flag) {
427 /* Fake EOF on stdin. */
428 debug("Sending eof.");
430 packet_start(SSH_CMSG_EOF);
433 enter_non_blocking();
435 /* Check for immediate EOF on stdin. */
436 len = read(fileno(stdin), buf, 1);
439 * EOF. Record that we have seen it and send
442 debug("Sending eof.");
444 packet_start(SSH_CMSG_EOF);
446 } else if (len > 0) {
448 * Got data. We must store the data in the buffer,
449 * and also process it as an escape character if
452 if ((u_char) buf[0] == escape_char1)
455 buffer_append(&stdin_buffer, buf, 1);
457 leave_non_blocking();
463 * Make packets from buffered stdin data, and buffer them for sending to the
468 client_make_packets_from_stdin_data(void)
472 /* Send buffered stdin data to the server. */
473 while (buffer_len(&stdin_buffer) > 0 &&
474 packet_not_very_much_data_to_write()) {
475 len = buffer_len(&stdin_buffer);
476 /* Keep the packets at reasonable size. */
477 if (len > packet_get_maxsize())
478 len = packet_get_maxsize();
479 packet_start(SSH_CMSG_STDIN_DATA);
480 packet_put_string(buffer_ptr(&stdin_buffer), len);
482 buffer_consume(&stdin_buffer, len);
483 /* If we have a pending EOF, send it now. */
484 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
485 packet_start(SSH_CMSG_EOF);
492 * Checks if the client window has changed, and sends a packet about it to
493 * the server if so. The actual change is detected elsewhere (by a software
494 * interrupt on Unix); this just checks the flag and sends a message if
499 client_check_window_change(void)
503 if (! received_window_change_signal)
506 received_window_change_signal = 0;
508 debug2("client_check_window_change: changed");
511 channel_send_window_changes();
513 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
515 packet_start(SSH_CMSG_WINDOW_SIZE);
516 packet_put_int((u_int)ws.ws_row);
517 packet_put_int((u_int)ws.ws_col);
518 packet_put_int((u_int)ws.ws_xpixel);
519 packet_put_int((u_int)ws.ws_ypixel);
525 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
527 struct global_confirm *gc;
529 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
532 gc->cb(type, seq, gc->ctx);
533 if (--gc->ref_count <= 0) {
534 TAILQ_REMOVE(&global_confirms, gc, entry);
535 bzero(gc, sizeof(*gc));
539 packet_set_alive_timeouts(0);
543 server_alive_check(void)
545 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
546 logit("Timeout, server %s not responding.", host);
549 packet_start(SSH2_MSG_GLOBAL_REQUEST);
550 packet_put_cstring("keepalive@openssh.com");
551 packet_put_char(1); /* boolean: want reply */
553 /* Insert an empty placeholder to maintain ordering */
554 client_register_global_confirm(NULL, NULL);
558 * Waits until the client can do something (some data becomes available on
559 * one of the file descriptors).
562 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
563 int *maxfdp, u_int *nallocp, int rekeying)
565 struct timeval tv, *tvp;
569 /* Add any selections by the channel mechanism. */
570 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
573 /* Read from the connection, unless our buffers are full. */
574 if (buffer_len(&stdout_buffer) < buffer_high &&
575 buffer_len(&stderr_buffer) < buffer_high &&
576 channel_not_very_much_buffered_data())
577 FD_SET(connection_in, *readsetp);
579 * Read from stdin, unless we have seen EOF or have very much
580 * buffered data to send to the server.
582 if (!stdin_eof && packet_not_very_much_data_to_write())
583 FD_SET(fileno(stdin), *readsetp);
585 /* Select stdout/stderr if have data in buffer. */
586 if (buffer_len(&stdout_buffer) > 0)
587 FD_SET(fileno(stdout), *writesetp);
588 if (buffer_len(&stderr_buffer) > 0)
589 FD_SET(fileno(stderr), *writesetp);
591 /* channel_prepare_select could have closed the last channel */
592 if (session_closed && !channel_still_open() &&
593 !packet_have_data_to_write()) {
594 /* clear mask since we did not call select() */
595 memset(*readsetp, 0, *nallocp);
596 memset(*writesetp, 0, *nallocp);
599 FD_SET(connection_in, *readsetp);
603 /* Select server connection if have data to write to the server. */
604 if (packet_have_data_to_write())
605 FD_SET(connection_out, *writesetp);
608 * Wait for something to happen. This will suspend the process until
609 * some selected descriptor can be read, written, or has some other
610 * event pending, or a timeout expires.
613 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
614 if (options.server_alive_interval > 0 && compat20)
615 timeout_secs = options.server_alive_interval;
616 set_control_persist_exit_time();
617 if (control_persist_exit_time > 0) {
618 timeout_secs = MIN(timeout_secs,
619 control_persist_exit_time - time(NULL));
620 if (timeout_secs < 0)
623 if (timeout_secs == INT_MAX)
626 tv.tv_sec = timeout_secs;
631 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
636 * We have to clear the select masks, because we return.
637 * We have to return, because the mainloop checks for the flags
638 * set by the signal handlers.
640 memset(*readsetp, 0, *nallocp);
641 memset(*writesetp, 0, *nallocp);
645 /* Note: we might still have data in the buffers. */
646 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
647 buffer_append(&stderr_buffer, buf, strlen(buf));
650 server_alive_check();
654 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
656 /* Flush stdout and stderr buffers. */
657 if (buffer_len(bout) > 0)
658 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
660 if (buffer_len(berr) > 0)
661 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
664 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
667 * Free (and clear) the buffer to reduce the amount of data that gets
674 /* Send the suspend signal to the program itself. */
675 kill(getpid(), SIGTSTP);
677 /* Reset window sizes in case they have changed */
678 received_window_change_signal = 1;
680 /* OK, we have been continued by the user. Reinitialize buffers. */
685 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
689 client_process_net_input(fd_set *readset)
692 char buf[SSH_IOBUFSZ];
695 * Read input from the server, and add any such data to the buffer of
696 * the packet subsystem.
698 if (FD_ISSET(connection_in, readset)) {
699 /* Read as much as possible. */
700 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
701 if (len == 0 && cont == 0) {
703 * Received EOF. The remote host has closed the
706 snprintf(buf, sizeof buf,
707 "Connection to %.300s closed by remote host.\r\n",
709 buffer_append(&stderr_buffer, buf, strlen(buf));
714 * There is a kernel bug on Solaris that causes select to
715 * sometimes wake up even though there is no data available.
718 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
723 * An error has encountered. Perhaps there is a
726 snprintf(buf, sizeof buf,
727 "Read from remote host %.300s: %.100s\r\n",
728 host, strerror(errno));
729 buffer_append(&stderr_buffer, buf, strlen(buf));
733 packet_process_incoming(buf, len);
738 client_status_confirm(int type, Channel *c, void *ctx)
740 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
745 * If a TTY was explicitly requested, then a failure to allocate
748 if (cr->action == CONFIRM_TTY &&
749 (options.request_tty == REQUEST_TTY_FORCE ||
750 options.request_tty == REQUEST_TTY_YES))
751 cr->action = CONFIRM_CLOSE;
753 /* XXX supress on mux _client_ quietmode */
754 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
755 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
757 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
758 debug2("%s request accepted on channel %d",
759 cr->request_type, c->self);
760 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
762 snprintf(errmsg, sizeof(errmsg),
763 "%s request failed\r\n", cr->request_type);
765 snprintf(errmsg, sizeof(errmsg),
766 "%s request failed on channel %d",
767 cr->request_type, c->self);
769 /* If error occurred on primary session channel, then exit */
770 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
773 * If error occurred on mux client, append to
777 buffer_append(&c->extended, errmsg,
781 if (cr->action == CONFIRM_TTY) {
783 * If a TTY allocation error occurred, then arrange
784 * for the correct TTY to leave raw mode.
786 if (c->self == session_ident)
789 mux_tty_alloc_failed(c);
790 } else if (cr->action == CONFIRM_CLOSE) {
792 chan_write_failed(c);
799 client_abandon_status_confirm(Channel *c, void *ctx)
805 client_expect_confirm(int id, const char *request,
806 enum confirm_action action)
808 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
810 cr->request_type = request;
813 channel_register_status_confirm(id, client_status_confirm,
814 client_abandon_status_confirm, cr);
818 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
820 struct global_confirm *gc, *last_gc;
822 /* Coalesce identical callbacks */
823 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
824 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
825 if (++last_gc->ref_count >= INT_MAX)
826 fatal("%s: last_gc->ref_count = %d",
827 __func__, last_gc->ref_count);
831 gc = xmalloc(sizeof(*gc));
835 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
839 process_cmdline(void)
841 void (*handler)(int);
842 char *s, *cmd, *cancel_host;
844 int local = 0, remote = 0, dynamic = 0;
848 bzero(&fwd, sizeof(fwd));
849 fwd.listen_host = fwd.connect_host = NULL;
851 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
852 handler = signal(SIGINT, SIG_IGN);
853 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
859 s++; /* Skip cmdline '-', if any */
863 if (*s == 'h' || *s == 'H' || *s == '?') {
865 logit(" -L[bind_address:]port:host:hostport "
866 "Request local forward");
867 logit(" -R[bind_address:]port:host:hostport "
868 "Request remote forward");
869 logit(" -D[bind_address:]port "
870 "Request dynamic forward");
871 logit(" -KR[bind_address:]port "
872 "Cancel remote forward");
873 if (!options.permit_local_command)
876 "Execute local command");
880 if (*s == '!' && options.permit_local_command) {
897 logit("Invalid command.");
901 if ((local || dynamic) && delete) {
902 logit("Not supported.");
905 if (remote && delete && !compat20) {
906 logit("Not supported for SSH protocol version 1.");
910 while (isspace(*++s))
913 /* XXX update list of forwards in options */
916 cancel_host = hpdelim(&s); /* may be NULL */
918 cancel_port = a2port(s);
919 cancel_host = cleanhostname(cancel_host);
921 cancel_port = a2port(cancel_host);
924 if (cancel_port <= 0) {
925 logit("Bad forwarding close port");
928 channel_request_rforward_cancel(cancel_host, cancel_port);
930 if (!parse_forward(&fwd, s, dynamic, remote)) {
931 logit("Bad forwarding specification.");
934 if (local || dynamic) {
935 if (channel_setup_local_fwd_listener(fwd.listen_host,
936 fwd.listen_port, fwd.connect_host,
937 fwd.connect_port, options.gateway_ports) < 0) {
938 logit("Port forwarding failed.");
942 if (channel_request_remote_forwarding(fwd.listen_host,
943 fwd.listen_port, fwd.connect_host,
944 fwd.connect_port) < 0) {
945 logit("Port forwarding failed.");
950 logit("Forwarding port.");
954 signal(SIGINT, handler);
955 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
958 if (fwd.listen_host != NULL)
959 xfree(fwd.listen_host);
960 if (fwd.connect_host != NULL)
961 xfree(fwd.connect_host);
965 * Process the characters one by one, call with c==NULL for proto1 case.
968 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
977 int *escape_pendingp, escape_char;
978 struct escape_filter_ctx *efc;
981 escape_pendingp = &escape_pending1;
982 escape_char = escape_char1;
984 if (c->filter_ctx == NULL)
986 efc = (struct escape_filter_ctx *)c->filter_ctx;
987 escape_pendingp = &efc->escape_pending;
988 escape_char = efc->escape_char;
994 for (i = 0; i < (u_int)len; i++) {
995 /* Get one character at a time. */
998 if (*escape_pendingp) {
999 /* We have previously seen an escape character. */
1000 /* Clear the flag now. */
1001 *escape_pendingp = 0;
1003 /* Process the escaped character. */
1006 /* Terminate the connection. */
1007 snprintf(string, sizeof string, "%c.\r\n",
1009 buffer_append(berr, string, strlen(string));
1011 if (c && c->ctl_chan != -1) {
1012 chan_read_failed(c);
1013 chan_write_failed(c);
1020 /* XXX support this for mux clients */
1021 if (c && c->ctl_chan != -1) {
1023 snprintf(string, sizeof string,
1024 "%c%c escape not available to "
1025 "multiplexed sessions\r\n",
1027 buffer_append(berr, string,
1031 /* Suspend the program. Inform the user */
1032 snprintf(string, sizeof string,
1033 "%c^Z [suspend ssh]\r\n", escape_char);
1034 buffer_append(berr, string, strlen(string));
1036 /* Restore terminal modes and suspend. */
1037 client_suspend_self(bin, bout, berr);
1039 /* We have been continued. */
1044 snprintf(string, sizeof string,
1045 "%cB\r\n", escape_char);
1046 buffer_append(berr, string,
1048 channel_request_start(session_ident,
1050 packet_put_int(1000);
1057 if (datafellows & SSH_BUG_NOREKEY)
1058 logit("Server does not "
1059 "support re-keying");
1066 if (c && c->ctl_chan != -1)
1069 * Detach the program (continue to serve
1070 * connections, but put in background and no
1071 * more new connections).
1073 /* Restore tty modes. */
1075 options.request_tty == REQUEST_TTY_FORCE);
1077 /* Stop listening for new connections. */
1078 channel_stop_listening();
1080 snprintf(string, sizeof string,
1081 "%c& [backgrounded]\n", escape_char);
1082 buffer_append(berr, string, strlen(string));
1084 /* Fork into background. */
1087 error("fork: %.100s", strerror(errno));
1090 if (pid != 0) { /* This is the parent. */
1091 /* The parent just exits. */
1094 /* The child continues serving connections. */
1096 buffer_append(bin, "\004", 1);
1097 /* fake EOF on stdin */
1099 } else if (!stdin_eof) {
1101 * Sending SSH_CMSG_EOF alone does not
1102 * always appear to be enough. So we
1103 * try to send an EOF character first.
1105 packet_start(SSH_CMSG_STDIN_DATA);
1106 packet_put_string("\004", 1);
1110 if (buffer_len(bin) == 0) {
1111 packet_start(SSH_CMSG_EOF);
1118 if (c && c->ctl_chan != -1) {
1119 snprintf(string, sizeof string,
1121 Supported escape sequences:\r\n\
1122 %c. - terminate session\r\n\
1123 %cB - send a BREAK to the remote system\r\n\
1124 %cR - Request rekey (SSH protocol 2 only)\r\n\
1125 %c# - list forwarded connections\r\n\
1126 %c? - this message\r\n\
1127 %c%c - send the escape character by typing it twice\r\n\
1128 (Note that escapes are only recognized immediately after newline.)\r\n",
1129 escape_char, escape_char,
1130 escape_char, escape_char,
1131 escape_char, escape_char,
1132 escape_char, escape_char);
1134 snprintf(string, sizeof string,
1136 Supported escape sequences:\r\n\
1137 %c. - terminate connection (and any multiplexed sessions)\r\n\
1138 %cB - send a BREAK to the remote system\r\n\
1139 %cC - open a command line\r\n\
1140 %cR - Request rekey (SSH protocol 2 only)\r\n\
1141 %c^Z - suspend ssh\r\n\
1142 %c# - list forwarded connections\r\n\
1143 %c& - background ssh (when waiting for connections to terminate)\r\n\
1144 %c? - this message\r\n\
1145 %c%c - send the escape character by typing it twice\r\n\
1146 (Note that escapes are only recognized immediately after newline.)\r\n",
1147 escape_char, escape_char,
1148 escape_char, escape_char,
1149 escape_char, escape_char,
1150 escape_char, escape_char,
1151 escape_char, escape_char,
1154 buffer_append(berr, string, strlen(string));
1158 snprintf(string, sizeof string, "%c#\r\n",
1160 buffer_append(berr, string, strlen(string));
1161 s = channel_open_message();
1162 buffer_append(berr, s, strlen(s));
1167 if (c && c->ctl_chan != -1)
1173 if (ch != escape_char) {
1174 buffer_put_char(bin, escape_char);
1177 /* Escaped characters fall through here */
1182 * The previous character was not an escape char.
1183 * Check if this is an escape.
1185 if (last_was_cr && ch == escape_char) {
1187 * It is. Set the flag and continue to
1190 *escape_pendingp = 1;
1196 * Normal character. Record whether it was a newline,
1197 * and append it to the buffer.
1199 last_was_cr = (ch == '\r' || ch == '\n');
1200 buffer_put_char(bin, ch);
1207 client_process_input(fd_set *readset)
1210 char buf[SSH_IOBUFSZ];
1212 /* Read input from stdin. */
1213 if (FD_ISSET(fileno(stdin), readset)) {
1214 /* Read as much as possible. */
1215 len = read(fileno(stdin), buf, sizeof(buf));
1217 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1218 return; /* we'll try again later */
1221 * Received EOF or error. They are treated
1222 * similarly, except that an error message is printed
1223 * if it was an error condition.
1226 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1228 buffer_append(&stderr_buffer, buf, strlen(buf));
1230 /* Mark that we have seen EOF. */
1233 * Send an EOF message to the server unless there is
1234 * data in the buffer. If there is data in the
1235 * buffer, no message will be sent now. Code
1236 * elsewhere will send the EOF when the buffer
1237 * becomes empty if stdin_eof is set.
1239 if (buffer_len(&stdin_buffer) == 0) {
1240 packet_start(SSH_CMSG_EOF);
1243 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1245 * Normal successful read, and no escape character.
1246 * Just append the data to buffer.
1248 buffer_append(&stdin_buffer, buf, len);
1251 * Normal, successful read. But we have an escape
1252 * character and have to process the characters one
1255 if (process_escapes(NULL, &stdin_buffer,
1256 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1263 client_process_output(fd_set *writeset)
1268 /* Write buffered output to stdout. */
1269 if (FD_ISSET(fileno(stdout), writeset)) {
1270 /* Write as much data as possible. */
1271 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1272 buffer_len(&stdout_buffer));
1274 if (errno == EINTR || errno == EAGAIN ||
1275 errno == EWOULDBLOCK)
1279 * An error or EOF was encountered. Put an
1280 * error message to stderr buffer.
1282 snprintf(buf, sizeof buf,
1283 "write stdout: %.50s\r\n", strerror(errno));
1284 buffer_append(&stderr_buffer, buf, strlen(buf));
1289 /* Consume printed data from the buffer. */
1290 buffer_consume(&stdout_buffer, len);
1292 /* Write buffered output to stderr. */
1293 if (FD_ISSET(fileno(stderr), writeset)) {
1294 /* Write as much data as possible. */
1295 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1296 buffer_len(&stderr_buffer));
1298 if (errno == EINTR || errno == EAGAIN ||
1299 errno == EWOULDBLOCK)
1303 * EOF or error, but can't even print
1310 /* Consume printed characters from the buffer. */
1311 buffer_consume(&stderr_buffer, len);
1316 * Get packets from the connection input buffer, and process them as long as
1317 * there are packets available.
1319 * Any unknown packets received during the actual
1320 * session cause the session to terminate. This is
1321 * intended to make debugging easier since no
1322 * confirmations are sent. Any compatible protocol
1323 * extensions must be negotiated during the
1324 * preparatory phase.
1328 client_process_buffered_input_packets(void)
1330 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1331 compat20 ? xxx_kex : NULL);
1334 /* scan buf[] for '~' before sending data to the peer */
1336 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1338 client_new_escape_filter_ctx(int escape_char)
1340 struct escape_filter_ctx *ret;
1342 ret = xmalloc(sizeof(*ret));
1343 ret->escape_pending = 0;
1344 ret->escape_char = escape_char;
1348 /* Free the escape filter context on channel free */
1350 client_filter_cleanup(int cid, void *ctx)
1356 client_simple_escape_filter(Channel *c, char *buf, int len)
1358 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1361 return process_escapes(c, &c->input, &c->output, &c->extended,
1366 client_channel_closed(int id, void *arg)
1368 channel_cancel_cleanup(id);
1370 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1374 * Implements the interactive session with the server. This is called after
1375 * the user has been authenticated, and a command has been started on the
1376 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1377 * used as an escape character for terminating or suspending the session.
1381 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1383 fd_set *readset = NULL, *writeset = NULL;
1384 double start_time, total_time;
1385 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1386 u_int64_t ibytes, obytes;
1390 debug("Entering interactive session.");
1392 start_time = get_current_time();
1394 /* Initialize variables. */
1395 escape_pending1 = 0;
1399 buffer_high = 64 * 1024;
1400 connection_in = packet_get_connection_in();
1401 connection_out = packet_get_connection_out();
1402 max_fd = MAX(connection_in, connection_out);
1405 /* enable nonblocking unless tty */
1406 if (!isatty(fileno(stdin)))
1407 set_nonblock(fileno(stdin));
1408 if (!isatty(fileno(stdout)))
1409 set_nonblock(fileno(stdout));
1410 if (!isatty(fileno(stderr)))
1411 set_nonblock(fileno(stderr));
1412 max_fd = MAX(max_fd, fileno(stdin));
1413 max_fd = MAX(max_fd, fileno(stdout));
1414 max_fd = MAX(max_fd, fileno(stderr));
1417 escape_char1 = escape_char_arg;
1419 /* Initialize buffers. */
1420 buffer_init(&stdin_buffer);
1421 buffer_init(&stdout_buffer);
1422 buffer_init(&stderr_buffer);
1424 client_init_dispatch();
1427 * Set signal handlers, (e.g. to restore non-blocking mode)
1428 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1430 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1431 signal(SIGHUP, signal_handler);
1432 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1433 signal(SIGINT, signal_handler);
1434 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1435 signal(SIGQUIT, signal_handler);
1436 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1437 signal(SIGTERM, signal_handler);
1438 signal(SIGWINCH, window_change_handler);
1441 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1444 session_ident = ssh2_chan_id;
1445 if (session_ident != -1) {
1446 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1447 channel_register_filter(session_ident,
1448 client_simple_escape_filter, NULL,
1449 client_filter_cleanup,
1450 client_new_escape_filter_ctx(
1453 channel_register_cleanup(session_ident,
1454 client_channel_closed, 0);
1457 /* Check if we should immediately send eof on stdin. */
1458 client_check_initial_eof_on_stdin();
1461 /* Main loop of the client for the interactive session mode. */
1462 while (!quit_pending) {
1464 /* Process buffered packets sent by the server. */
1465 client_process_buffered_input_packets();
1467 if (compat20 && session_closed && !channel_still_open())
1470 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1473 debug("rekeying in progress");
1476 * Make packets of buffered stdin data, and buffer
1477 * them for sending to the server.
1480 client_make_packets_from_stdin_data();
1483 * Make packets from buffered channel data, and
1484 * enqueue them for sending to the server.
1486 if (packet_not_very_much_data_to_write())
1487 channel_output_poll();
1490 * Check if the window size has changed, and buffer a
1491 * message about it to the server if so.
1493 client_check_window_change();
1499 * Wait until we have something to do (something becomes
1500 * available on one of the descriptors).
1503 client_wait_until_can_do_something(&readset, &writeset,
1504 &max_fd2, &nalloc, rekeying);
1509 /* Do channel operations unless rekeying in progress. */
1511 channel_after_select(readset, writeset);
1512 if (need_rekeying || packet_need_rekeying()) {
1513 debug("need rekeying");
1515 kex_send_kexinit(xxx_kex);
1520 /* Buffer input from the connection. */
1521 client_process_net_input(readset);
1527 /* Buffer data from stdin */
1528 client_process_input(readset);
1530 * Process output to stdout and stderr. Output to
1531 * the connection is processed elsewhere (above).
1533 client_process_output(writeset);
1536 if (session_resumed) {
1537 connection_in = packet_get_connection_in();
1538 connection_out = packet_get_connection_out();
1539 max_fd = MAX(max_fd, connection_out);
1540 max_fd = MAX(max_fd, connection_in);
1541 session_resumed = 0;
1545 * Send as much buffered packet data as possible to the
1548 if (FD_ISSET(connection_out, writeset))
1549 packet_write_poll();
1552 * If we are a backgrounded control master, and the
1553 * timeout has expired without any active client
1554 * connections, then quit.
1556 if (control_persist_exit_time > 0) {
1557 if (time(NULL) >= control_persist_exit_time) {
1558 debug("ControlPersist timeout expired");
1568 /* Terminate the session. */
1570 /* Stop watching for window change. */
1571 signal(SIGWINCH, SIG_DFL);
1574 packet_start(SSH2_MSG_DISCONNECT);
1575 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1576 packet_put_cstring("disconnected by user");
1577 packet_put_cstring(""); /* language tag */
1579 packet_write_wait();
1585 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1587 /* restore blocking io */
1588 if (!isatty(fileno(stdin)))
1589 unset_nonblock(fileno(stdin));
1590 if (!isatty(fileno(stdout)))
1591 unset_nonblock(fileno(stdout));
1592 if (!isatty(fileno(stderr)))
1593 unset_nonblock(fileno(stderr));
1596 * If there was no shell or command requested, there will be no remote
1597 * exit status to be returned. In that case, clear error code if the
1598 * connection was deliberately terminated at this end.
1600 if (no_shell_flag && received_signal == SIGTERM) {
1601 received_signal = 0;
1605 if (received_signal)
1606 fatal("Killed by signal %d.", (int) received_signal);
1609 * In interactive mode (with pseudo tty) display a message indicating
1610 * that the connection has been closed.
1612 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1613 snprintf(buf, sizeof buf,
1614 "Connection to %.64s closed.\r\n", host);
1615 buffer_append(&stderr_buffer, buf, strlen(buf));
1618 /* Output any buffered data for stdout. */
1619 if (buffer_len(&stdout_buffer) > 0) {
1620 len = atomicio(vwrite, fileno(stdout),
1621 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1622 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1623 error("Write failed flushing stdout buffer.");
1625 buffer_consume(&stdout_buffer, len);
1628 /* Output any buffered data for stderr. */
1629 if (buffer_len(&stderr_buffer) > 0) {
1630 len = atomicio(vwrite, fileno(stderr),
1631 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1632 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1633 error("Write failed flushing stderr buffer.");
1635 buffer_consume(&stderr_buffer, len);
1638 /* Clear and free any buffers. */
1639 memset(buf, 0, sizeof(buf));
1640 buffer_free(&stdin_buffer);
1641 buffer_free(&stdout_buffer);
1642 buffer_free(&stderr_buffer);
1644 /* Report bytes transferred, and transfer rates. */
1645 total_time = get_current_time() - start_time;
1646 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1647 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1648 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1649 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1651 verbose("Bytes per second: sent %.1f, received %.1f",
1652 obytes / total_time, ibytes / total_time);
1653 /* Return the exit status of the program. */
1654 debug("Exit status %d", exit_status);
1661 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1664 char *data = packet_get_string(&data_len);
1666 buffer_append(&stdout_buffer, data, data_len);
1667 memset(data, 0, data_len);
1671 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1674 char *data = packet_get_string(&data_len);
1676 buffer_append(&stderr_buffer, data, data_len);
1677 memset(data, 0, data_len);
1681 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1683 exit_status = packet_get_int();
1685 /* Acknowledge the exit. */
1686 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1689 * Must wait for packet to be sent since we are
1692 packet_write_wait();
1693 /* Flag that we want to exit. */
1697 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1700 int remote_id, sock;
1702 /* Read the remote channel number from the message. */
1703 remote_id = packet_get_int();
1707 * Get a connection to the local authentication agent (this may again
1710 sock = ssh_get_authentication_socket();
1713 * If we could not connect the agent, send an error message back to
1714 * the server. This should never happen unless the agent dies,
1715 * because authentication forwarding is only enabled if we have an
1719 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1720 -1, 0, 0, 0, "authentication agent connection", 1);
1721 c->remote_id = remote_id;
1725 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1726 packet_put_int(remote_id);
1728 /* Send a confirmation to the remote host. */
1729 debug("Forwarding authentication connection.");
1730 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1731 packet_put_int(remote_id);
1732 packet_put_int(c->self);
1738 client_request_forwarded_tcpip(const char *request_type, int rchan)
1741 char *listen_address, *originator_address;
1742 u_short listen_port, originator_port;
1744 /* Get rest of the packet */
1745 listen_address = packet_get_string(NULL);
1746 listen_port = packet_get_int();
1747 originator_address = packet_get_string(NULL);
1748 originator_port = packet_get_int();
1751 debug("client_request_forwarded_tcpip: listen %s port %d, "
1752 "originator %s port %d", listen_address, listen_port,
1753 originator_address, originator_port);
1755 c = channel_connect_by_listen_address(listen_port,
1756 "forwarded-tcpip", originator_address);
1758 xfree(originator_address);
1759 xfree(listen_address);
1764 client_request_x11(const char *request_type, int rchan)
1768 u_short originator_port;
1771 if (!options.forward_x11) {
1772 error("Warning: ssh server tried X11 forwarding.");
1773 error("Warning: this is probably a break-in attempt by a "
1774 "malicious server.");
1777 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1778 verbose("Rejected X11 connection after ForwardX11Timeout "
1782 originator = packet_get_string(NULL);
1783 if (datafellows & SSH_BUG_X11FWD) {
1784 debug2("buggy server: x11 request w/o originator_port");
1785 originator_port = 0;
1787 originator_port = packet_get_int();
1790 /* XXX check permission */
1791 debug("client_request_x11: request from %s %d", originator,
1794 sock = x11_connect_display();
1797 if (options.hpn_disabled)
1798 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1799 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1802 c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1803 options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
1810 client_request_agent(const char *request_type, int rchan)
1815 if (!options.forward_agent) {
1816 error("Warning: ssh server tried agent forwarding.");
1817 error("Warning: this is probably a break-in attempt by a "
1818 "malicious server.");
1821 sock = ssh_get_authentication_socket();
1824 if (options.hpn_disabled)
1825 c = channel_new("authentication agent connection",
1826 SSH_CHANNEL_OPEN, sock, sock, -1,
1827 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1828 "authentication agent connection", 1);
1830 c = channel_new("authentication agent connection",
1831 SSH_CHANNEL_OPEN, sock, sock, -1,
1832 options.hpn_buffer_size, options.hpn_buffer_size, 0,
1833 "authentication agent connection", 1);
1839 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1844 if (tun_mode == SSH_TUNMODE_NO)
1848 error("Tunnel forwarding is not supported for protocol 1");
1852 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1854 /* Open local tunnel device */
1855 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1856 error("Tunnel device open failed.");
1860 if (options.hpn_disabled)
1861 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1862 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1865 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1866 options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1870 #if defined(SSH_TUN_FILTER)
1871 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1872 channel_register_filter(c->self, sys_tun_infilter,
1873 sys_tun_outfilter, NULL, NULL);
1876 packet_start(SSH2_MSG_CHANNEL_OPEN);
1877 packet_put_cstring("tun@openssh.com");
1878 packet_put_int(c->self);
1879 packet_put_int(c->local_window_max);
1880 packet_put_int(c->local_maxpacket);
1881 packet_put_int(tun_mode);
1882 packet_put_int(remote_tun);
1888 /* XXXX move to generic input handler */
1890 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1895 u_int rmaxpack, rwindow, len;
1897 ctype = packet_get_string(&len);
1898 rchan = packet_get_int();
1899 rwindow = packet_get_int();
1900 rmaxpack = packet_get_int();
1902 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1903 ctype, rchan, rwindow, rmaxpack);
1905 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1906 c = client_request_forwarded_tcpip(ctype, rchan);
1907 } else if (strcmp(ctype, "x11") == 0) {
1908 c = client_request_x11(ctype, rchan);
1909 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1910 c = client_request_agent(ctype, rchan);
1912 /* XXX duplicate : */
1914 debug("confirm %s", ctype);
1915 c->remote_id = rchan;
1916 c->remote_window = rwindow;
1917 c->remote_maxpacket = rmaxpack;
1918 if (c->type != SSH_CHANNEL_CONNECTING) {
1919 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1920 packet_put_int(c->remote_id);
1921 packet_put_int(c->self);
1922 packet_put_int(c->local_window);
1923 packet_put_int(c->local_maxpacket);
1927 debug("failure %s", ctype);
1928 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1929 packet_put_int(rchan);
1930 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1931 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1932 packet_put_cstring("open failed");
1933 packet_put_cstring("");
1940 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1943 int exitval, id, reply, success = 0;
1946 id = packet_get_int();
1947 rtype = packet_get_string(NULL);
1948 reply = packet_get_char();
1950 debug("client_input_channel_req: channel %d rtype %s reply %d",
1954 error("client_input_channel_req: request for channel -1");
1955 } else if ((c = channel_lookup(id)) == NULL) {
1956 error("client_input_channel_req: channel %d: "
1957 "unknown channel", id);
1958 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1961 } else if (strcmp(rtype, "exit-status") == 0) {
1962 exitval = packet_get_int();
1963 if (c->ctl_chan != -1) {
1964 mux_exit_message(c, exitval);
1966 } else if (id == session_ident) {
1967 /* Record exit value of local session */
1969 exit_status = exitval;
1971 /* Probably for a mux channel that has already closed */
1972 debug("%s: no sink for exit-status on channel %d",
1977 if (reply && c != NULL) {
1978 packet_start(success ?
1979 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1980 packet_put_int(c->remote_id);
1986 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1992 rtype = packet_get_string(NULL);
1993 want_reply = packet_get_char();
1994 debug("client_input_global_request: rtype %s want_reply %d",
1997 packet_start(success ?
1998 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2000 packet_write_wait();
2006 client_session2_setup(int id, int want_tty, int want_subsystem,
2007 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2012 debug2("%s: id %d", __func__, id);
2014 if ((c = channel_lookup(id)) == NULL)
2015 fatal("client_session2_setup: channel %d: unknown channel", id);
2017 packet_set_interactive(want_tty,
2018 options.ip_qos_interactive, options.ip_qos_bulk);
2023 /* Store window size in the packet. */
2024 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2025 memset(&ws, 0, sizeof(ws));
2027 channel_request_start(id, "pty-req", 1);
2028 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2029 packet_put_cstring(term != NULL ? term : "");
2030 packet_put_int((u_int)ws.ws_col);
2031 packet_put_int((u_int)ws.ws_row);
2032 packet_put_int((u_int)ws.ws_xpixel);
2033 packet_put_int((u_int)ws.ws_ypixel);
2035 tiop = get_saved_tio();
2036 tty_make_modes(-1, tiop);
2038 /* XXX wait for reply */
2042 /* Transfer any environment variables from client to server */
2043 if (options.num_send_env != 0 && env != NULL) {
2047 debug("Sending environment.");
2048 for (i = 0; env[i] != NULL; i++) {
2050 name = xstrdup(env[i]);
2051 if ((val = strchr(name, '=')) == NULL) {
2058 for (j = 0; j < options.num_send_env; j++) {
2059 if (match_pattern(name, options.send_env[j])) {
2065 debug3("Ignored env %s", name);
2070 debug("Sending env %s = %s", name, val);
2071 channel_request_start(id, "env", 0);
2072 packet_put_cstring(name);
2073 packet_put_cstring(val);
2079 len = buffer_len(cmd);
2083 if (want_subsystem) {
2084 debug("Sending subsystem: %.*s",
2085 len, (u_char*)buffer_ptr(cmd));
2086 channel_request_start(id, "subsystem", 1);
2087 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2089 debug("Sending command: %.*s",
2090 len, (u_char*)buffer_ptr(cmd));
2091 channel_request_start(id, "exec", 1);
2092 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2094 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2097 channel_request_start(id, "shell", 1);
2098 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2104 client_init_dispatch_20(void)
2106 dispatch_init(&dispatch_protocol_error);
2108 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2109 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2110 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2111 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2112 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2113 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2114 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2115 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2116 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2117 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2118 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2119 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2122 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2124 /* global request reply messages */
2125 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2126 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2130 client_init_dispatch_13(void)
2132 dispatch_init(NULL);
2133 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2134 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2135 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2136 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2137 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2138 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2139 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2140 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2141 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2143 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2144 &client_input_agent_open : &deny_input_open);
2145 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2146 &x11_input_open : &deny_input_open);
2150 client_init_dispatch_15(void)
2152 client_init_dispatch_13();
2153 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2154 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2158 client_init_dispatch(void)
2161 client_init_dispatch_20();
2163 client_init_dispatch_13();
2165 client_init_dispatch_15();
2169 client_stop_mux(void)
2171 if (options.control_path != NULL && muxserver_sock != -1)
2172 unlink(options.control_path);
2174 * If we are in persist mode, signal that we should close when all
2175 * active channels are closed.
2177 if (options.control_persist) {
2179 setproctitle("[stopped mux]");
2183 /* client specific fatal cleanup */
2187 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2188 leave_non_blocking();
2189 if (options.control_path != NULL && muxserver_sock != -1)
2190 unlink(options.control_path);
2191 ssh_kill_proxy_command();