1 /* $OpenBSD: clientloop.c,v 1.236 2011/06/22 22:08:42 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The main loop for the interactive session (client side).
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #include <sys/param.h>
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
70 #ifdef HAVE_SYS_TIME_H
71 # include <sys/time.h>
73 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
103 #include "readconf.h"
104 #include "clientloop.h"
105 #include "sshconnect.h"
107 #include "atomicio.h"
119 extern Options options;
121 /* Flag indicating that stdin should be redirected from /dev/null. */
122 extern int stdin_null_flag;
124 /* Flag indicating that no shell has been requested */
125 extern int no_shell_flag;
128 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Time when backgrounded control master using ControlPersist should exit */
150 static time_t control_persist_exit_time = 0;
152 /* Common data for the client loop code. */
153 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
154 static int escape_char1; /* Escape character. (proto1 only) */
155 static int escape_pending1; /* Last character was an escape (proto1 only) */
156 static int last_was_cr; /* Last character was a newline. */
157 static int exit_status; /* Used to store the command exit status. */
158 static int stdin_eof; /* EOF has been encountered on stderr. */
159 static Buffer stdin_buffer; /* Buffer for stdin data. */
160 static Buffer stdout_buffer; /* Buffer for stdout data. */
161 static Buffer stderr_buffer; /* Buffer for stderr data. */
162 static u_int buffer_high; /* Soft max buffer size. */
163 static int connection_in; /* Connection to server (input). */
164 static int connection_out; /* Connection to server (output). */
165 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
166 static int session_closed; /* In SSH2: login session closed. */
167 static int x11_refuse_time; /* If >0, refuse x11 opens after this time. */
169 static void client_init_dispatch(void);
170 int session_ident = -1;
172 int session_resumed = 0;
174 /* Track escape per proto2 channel */
175 struct escape_filter_ctx {
180 /* Context for channel confirmation replies */
181 struct channel_reply_ctx {
182 const char *request_type;
184 enum confirm_action action;
187 /* Global request success/failure callbacks */
188 struct global_confirm {
189 TAILQ_ENTRY(global_confirm) entry;
190 global_confirm_cb *cb;
194 TAILQ_HEAD(global_confirms, global_confirm);
195 static struct global_confirms global_confirms =
196 TAILQ_HEAD_INITIALIZER(global_confirms);
201 void ssh_process_session2_setup(int, int, int, Buffer *);
203 /* Restores stdin to blocking mode. */
206 leave_non_blocking(void)
208 if (in_non_blocking_mode) {
209 unset_nonblock(fileno(stdin));
210 in_non_blocking_mode = 0;
214 /* Puts stdin terminal in non-blocking mode. */
217 enter_non_blocking(void)
219 in_non_blocking_mode = 1;
220 set_nonblock(fileno(stdin));
224 * Signal handler for the window change signal (SIGWINCH). This just sets a
225 * flag indicating that the window has changed.
229 window_change_handler(int sig)
231 received_window_change_signal = 1;
232 signal(SIGWINCH, window_change_handler);
236 * Signal handler for signals that cause the program to terminate. These
237 * signals must be trapped to restore terminal modes.
241 signal_handler(int sig)
243 received_signal = sig;
248 * Returns current time in seconds from Jan 1, 1970 with the maximum
249 * available resolution.
253 get_current_time(void)
256 gettimeofday(&tv, NULL);
257 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
261 * Sets control_persist_exit_time to the absolute time when the
262 * backgrounded control master should exit due to expiry of the
263 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
264 * control master process, or if there is no ControlPersist timeout.
267 set_control_persist_exit_time(void)
269 if (muxserver_sock == -1 || !options.control_persist
270 || options.control_persist_timeout == 0) {
271 /* not using a ControlPersist timeout */
272 control_persist_exit_time = 0;
273 } else if (channel_still_open()) {
274 /* some client connections are still open */
275 if (control_persist_exit_time > 0)
276 debug2("%s: cancel scheduled exit", __func__);
277 control_persist_exit_time = 0;
278 } else if (control_persist_exit_time <= 0) {
279 /* a client connection has recently closed */
280 control_persist_exit_time = time(NULL) +
281 (time_t)options.control_persist_timeout;
282 debug2("%s: schedule exit in %d seconds", __func__,
283 options.control_persist_timeout);
285 /* else we are already counting down to the timeout */
288 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
290 client_x11_get_proto(const char *display, const char *xauth_path,
291 u_int trusted, u_int timeout, char **_proto, char **_data)
296 static char proto[512], data[512];
298 int got_data = 0, generated = 0, do_unlink = 0, i;
299 char *xauthdir, *xauthfile;
303 xauthdir = xauthfile = NULL;
306 proto[0] = data[0] = '\0';
308 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
309 debug("No xauth program.");
311 if (display == NULL) {
312 debug("x11_get_proto: DISPLAY not set");
316 * Handle FamilyLocal case where $DISPLAY does
317 * not match an authorization entry. For this we
318 * just try "xauth list unix:displaynum.screennum".
319 * XXX: "localhost" match to determine FamilyLocal
322 if (strncmp(display, "localhost:", 10) == 0) {
323 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
328 xauthdir = xmalloc(MAXPATHLEN);
329 xauthfile = xmalloc(MAXPATHLEN);
330 mktemp_proto(xauthdir, MAXPATHLEN);
331 if (mkdtemp(xauthdir) != NULL) {
333 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
335 snprintf(cmd, sizeof(cmd),
336 "%s -f %s generate %s " SSH_X11_PROTO
337 " untrusted timeout %u 2>" _PATH_DEVNULL,
338 xauth_path, xauthfile, display, timeout);
339 debug2("x11_get_proto: %s", cmd);
340 if (system(cmd) == 0)
342 if (x11_refuse_time == 0) {
343 now = time(NULL) + 1;
344 if (UINT_MAX - timeout < now)
345 x11_refuse_time = UINT_MAX;
347 x11_refuse_time = now + timeout;
353 * When in untrusted mode, we read the cookie only if it was
354 * successfully generated as an untrusted one in the step
357 if (trusted || generated) {
358 snprintf(cmd, sizeof(cmd),
359 "%s %s%s list %s 2>" _PATH_DEVNULL,
361 generated ? "-f " : "" ,
362 generated ? xauthfile : "",
364 debug2("x11_get_proto: %s", cmd);
366 if (f && fgets(line, sizeof(line), f) &&
367 sscanf(line, "%*s %511s %511s", proto, data) == 2)
372 error("Warning: untrusted X11 forwarding setup failed: "
373 "xauth key data not generated");
386 * If we didn't get authentication data, just make up some
387 * data. The forwarding code will check the validity of the
388 * response anyway, and substitute this data. The X11
389 * server, however, will ignore this fake data and use
390 * whatever authentication mechanisms it was using otherwise
391 * for the local connection.
396 logit("Warning: No xauth data; "
397 "using fake authentication data for X11 forwarding.");
398 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
399 for (i = 0; i < 16; i++) {
402 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
410 * This is called when the interactive is entered. This checks if there is
411 * an EOF coming on stdin. We must check this explicitly, as select() does
412 * not appear to wake up when redirecting from /dev/null.
416 client_check_initial_eof_on_stdin(void)
422 * If standard input is to be "redirected from /dev/null", we simply
423 * mark that we have seen an EOF and send an EOF message to the
424 * server. Otherwise, we try to read a single character; it appears
425 * that for some files, such /dev/null, select() never wakes up for
426 * read for this descriptor, which means that we never get EOF. This
427 * way we will get the EOF if stdin comes from /dev/null or similar.
429 if (stdin_null_flag) {
430 /* Fake EOF on stdin. */
431 debug("Sending eof.");
433 packet_start(SSH_CMSG_EOF);
436 enter_non_blocking();
438 /* Check for immediate EOF on stdin. */
439 len = read(fileno(stdin), buf, 1);
442 * EOF. Record that we have seen it and send
445 debug("Sending eof.");
447 packet_start(SSH_CMSG_EOF);
449 } else if (len > 0) {
451 * Got data. We must store the data in the buffer,
452 * and also process it as an escape character if
455 if ((u_char) buf[0] == escape_char1)
458 buffer_append(&stdin_buffer, buf, 1);
460 leave_non_blocking();
466 * Make packets from buffered stdin data, and buffer them for sending to the
471 client_make_packets_from_stdin_data(void)
475 /* Send buffered stdin data to the server. */
476 while (buffer_len(&stdin_buffer) > 0 &&
477 packet_not_very_much_data_to_write()) {
478 len = buffer_len(&stdin_buffer);
479 /* Keep the packets at reasonable size. */
480 if (len > packet_get_maxsize())
481 len = packet_get_maxsize();
482 packet_start(SSH_CMSG_STDIN_DATA);
483 packet_put_string(buffer_ptr(&stdin_buffer), len);
485 buffer_consume(&stdin_buffer, len);
486 /* If we have a pending EOF, send it now. */
487 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
488 packet_start(SSH_CMSG_EOF);
495 * Checks if the client window has changed, and sends a packet about it to
496 * the server if so. The actual change is detected elsewhere (by a software
497 * interrupt on Unix); this just checks the flag and sends a message if
502 client_check_window_change(void)
506 if (! received_window_change_signal)
509 received_window_change_signal = 0;
511 debug2("client_check_window_change: changed");
514 channel_send_window_changes();
516 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
518 packet_start(SSH_CMSG_WINDOW_SIZE);
519 packet_put_int((u_int)ws.ws_row);
520 packet_put_int((u_int)ws.ws_col);
521 packet_put_int((u_int)ws.ws_xpixel);
522 packet_put_int((u_int)ws.ws_ypixel);
528 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
530 struct global_confirm *gc;
532 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
535 gc->cb(type, seq, gc->ctx);
536 if (--gc->ref_count <= 0) {
537 TAILQ_REMOVE(&global_confirms, gc, entry);
538 bzero(gc, sizeof(*gc));
542 packet_set_alive_timeouts(0);
546 server_alive_check(void)
549 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
550 logit("Timeout, server %s not responding.", host);
553 packet_start(SSH2_MSG_GLOBAL_REQUEST);
554 packet_put_cstring("keepalive@openssh.com");
555 packet_put_char(1); /* boolean: want reply */
557 /* Insert an empty placeholder to maintain ordering */
558 client_register_global_confirm(NULL, NULL);
560 packet_send_ignore(0);
566 * Waits until the client can do something (some data becomes available on
567 * one of the file descriptors).
570 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
571 int *maxfdp, u_int *nallocp, int rekeying)
573 struct timeval tv, *tvp;
577 /* Add any selections by the channel mechanism. */
578 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
581 /* Read from the connection, unless our buffers are full. */
582 if (buffer_len(&stdout_buffer) < buffer_high &&
583 buffer_len(&stderr_buffer) < buffer_high &&
584 channel_not_very_much_buffered_data())
585 FD_SET(connection_in, *readsetp);
587 * Read from stdin, unless we have seen EOF or have very much
588 * buffered data to send to the server.
590 if (!stdin_eof && packet_not_very_much_data_to_write())
591 FD_SET(fileno(stdin), *readsetp);
593 /* Select stdout/stderr if have data in buffer. */
594 if (buffer_len(&stdout_buffer) > 0)
595 FD_SET(fileno(stdout), *writesetp);
596 if (buffer_len(&stderr_buffer) > 0)
597 FD_SET(fileno(stderr), *writesetp);
599 /* channel_prepare_select could have closed the last channel */
600 if (session_closed && !channel_still_open() &&
601 !packet_have_data_to_write()) {
602 /* clear mask since we did not call select() */
603 memset(*readsetp, 0, *nallocp);
604 memset(*writesetp, 0, *nallocp);
607 FD_SET(connection_in, *readsetp);
611 /* Select server connection if have data to write to the server. */
612 if (packet_have_data_to_write())
613 FD_SET(connection_out, *writesetp);
616 * Wait for something to happen. This will suspend the process until
617 * some selected descriptor can be read, written, or has some other
618 * event pending, or a timeout expires.
621 timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
622 if (options.server_alive_interval > 0)
623 timeout_secs = options.server_alive_interval;
624 set_control_persist_exit_time();
625 if (control_persist_exit_time > 0) {
626 timeout_secs = MIN(timeout_secs,
627 control_persist_exit_time - time(NULL));
628 if (timeout_secs < 0)
631 if (timeout_secs == INT_MAX)
634 tv.tv_sec = timeout_secs;
639 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
644 * We have to clear the select masks, because we return.
645 * We have to return, because the mainloop checks for the flags
646 * set by the signal handlers.
648 memset(*readsetp, 0, *nallocp);
649 memset(*writesetp, 0, *nallocp);
653 /* Note: we might still have data in the buffers. */
654 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
655 buffer_append(&stderr_buffer, buf, strlen(buf));
658 server_alive_check();
662 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
664 /* Flush stdout and stderr buffers. */
665 if (buffer_len(bout) > 0)
666 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
668 if (buffer_len(berr) > 0)
669 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
672 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
675 * Free (and clear) the buffer to reduce the amount of data that gets
682 /* Send the suspend signal to the program itself. */
683 kill(getpid(), SIGTSTP);
685 /* Reset window sizes in case they have changed */
686 received_window_change_signal = 1;
688 /* OK, we have been continued by the user. Reinitialize buffers. */
693 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
697 client_process_net_input(fd_set *readset)
700 char buf[SSH_IOBUFSZ];
703 * Read input from the server, and add any such data to the buffer of
704 * the packet subsystem.
706 if (FD_ISSET(connection_in, readset)) {
707 /* Read as much as possible. */
708 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
709 if (len == 0 && cont == 0) {
711 * Received EOF. The remote host has closed the
714 snprintf(buf, sizeof buf,
715 "Connection to %.300s closed by remote host.\r\n",
717 buffer_append(&stderr_buffer, buf, strlen(buf));
722 * There is a kernel bug on Solaris that causes select to
723 * sometimes wake up even though there is no data available.
726 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
731 * An error has encountered. Perhaps there is a
734 snprintf(buf, sizeof buf,
735 "Read from remote host %.300s: %.100s\r\n",
736 host, strerror(errno));
737 buffer_append(&stderr_buffer, buf, strlen(buf));
741 packet_process_incoming(buf, len);
746 client_status_confirm(int type, Channel *c, void *ctx)
748 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
753 * If a TTY was explicitly requested, then a failure to allocate
756 if (cr->action == CONFIRM_TTY &&
757 (options.request_tty == REQUEST_TTY_FORCE ||
758 options.request_tty == REQUEST_TTY_YES))
759 cr->action = CONFIRM_CLOSE;
761 /* XXX supress on mux _client_ quietmode */
762 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
763 c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
765 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
766 debug2("%s request accepted on channel %d",
767 cr->request_type, c->self);
768 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
770 snprintf(errmsg, sizeof(errmsg),
771 "%s request failed\r\n", cr->request_type);
773 snprintf(errmsg, sizeof(errmsg),
774 "%s request failed on channel %d",
775 cr->request_type, c->self);
777 /* If error occurred on primary session channel, then exit */
778 if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
781 * If error occurred on mux client, append to
785 buffer_append(&c->extended, errmsg,
789 if (cr->action == CONFIRM_TTY) {
791 * If a TTY allocation error occurred, then arrange
792 * for the correct TTY to leave raw mode.
794 if (c->self == session_ident)
797 mux_tty_alloc_failed(c);
798 } else if (cr->action == CONFIRM_CLOSE) {
800 chan_write_failed(c);
807 client_abandon_status_confirm(Channel *c, void *ctx)
813 client_expect_confirm(int id, const char *request,
814 enum confirm_action action)
816 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
818 cr->request_type = request;
821 channel_register_status_confirm(id, client_status_confirm,
822 client_abandon_status_confirm, cr);
826 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
828 struct global_confirm *gc, *last_gc;
830 /* Coalesce identical callbacks */
831 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
832 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
833 if (++last_gc->ref_count >= INT_MAX)
834 fatal("%s: last_gc->ref_count = %d",
835 __func__, last_gc->ref_count);
839 gc = xmalloc(sizeof(*gc));
843 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
847 process_cmdline(void)
849 void (*handler)(int);
850 char *s, *cmd, *cancel_host;
852 int local = 0, remote = 0, dynamic = 0;
856 bzero(&fwd, sizeof(fwd));
857 fwd.listen_host = fwd.connect_host = NULL;
859 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
860 handler = signal(SIGINT, SIG_IGN);
861 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
867 s++; /* Skip cmdline '-', if any */
871 if (*s == 'h' || *s == 'H' || *s == '?') {
873 logit(" -L[bind_address:]port:host:hostport "
874 "Request local forward");
875 logit(" -R[bind_address:]port:host:hostport "
876 "Request remote forward");
877 logit(" -D[bind_address:]port "
878 "Request dynamic forward");
879 logit(" -KR[bind_address:]port "
880 "Cancel remote forward");
881 if (!options.permit_local_command)
884 "Execute local command");
888 if (*s == '!' && options.permit_local_command) {
905 logit("Invalid command.");
909 if ((local || dynamic) && delete) {
910 logit("Not supported.");
913 if (remote && delete && !compat20) {
914 logit("Not supported for SSH protocol version 1.");
918 while (isspace(*++s))
921 /* XXX update list of forwards in options */
924 cancel_host = hpdelim(&s); /* may be NULL */
926 cancel_port = a2port(s);
927 cancel_host = cleanhostname(cancel_host);
929 cancel_port = a2port(cancel_host);
932 if (cancel_port <= 0) {
933 logit("Bad forwarding close port");
936 channel_request_rforward_cancel(cancel_host, cancel_port);
938 if (!parse_forward(&fwd, s, dynamic, remote)) {
939 logit("Bad forwarding specification.");
942 if (local || dynamic) {
943 if (channel_setup_local_fwd_listener(fwd.listen_host,
944 fwd.listen_port, fwd.connect_host,
945 fwd.connect_port, options.gateway_ports) < 0) {
946 logit("Port forwarding failed.");
950 if (channel_request_remote_forwarding(fwd.listen_host,
951 fwd.listen_port, fwd.connect_host,
952 fwd.connect_port) < 0) {
953 logit("Port forwarding failed.");
958 logit("Forwarding port.");
962 signal(SIGINT, handler);
963 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
966 if (fwd.listen_host != NULL)
967 xfree(fwd.listen_host);
968 if (fwd.connect_host != NULL)
969 xfree(fwd.connect_host);
973 * Process the characters one by one, call with c==NULL for proto1 case.
976 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
985 int *escape_pendingp, escape_char;
986 struct escape_filter_ctx *efc;
989 escape_pendingp = &escape_pending1;
990 escape_char = escape_char1;
992 if (c->filter_ctx == NULL)
994 efc = (struct escape_filter_ctx *)c->filter_ctx;
995 escape_pendingp = &efc->escape_pending;
996 escape_char = efc->escape_char;
1002 for (i = 0; i < (u_int)len; i++) {
1003 /* Get one character at a time. */
1006 if (*escape_pendingp) {
1007 /* We have previously seen an escape character. */
1008 /* Clear the flag now. */
1009 *escape_pendingp = 0;
1011 /* Process the escaped character. */
1014 /* Terminate the connection. */
1015 snprintf(string, sizeof string, "%c.\r\n",
1017 buffer_append(berr, string, strlen(string));
1019 if (c && c->ctl_chan != -1) {
1020 chan_read_failed(c);
1021 chan_write_failed(c);
1028 /* XXX support this for mux clients */
1029 if (c && c->ctl_chan != -1) {
1031 snprintf(string, sizeof string,
1032 "%c%c escape not available to "
1033 "multiplexed sessions\r\n",
1035 buffer_append(berr, string,
1039 /* Suspend the program. Inform the user */
1040 snprintf(string, sizeof string,
1041 "%c^Z [suspend ssh]\r\n", escape_char);
1042 buffer_append(berr, string, strlen(string));
1044 /* Restore terminal modes and suspend. */
1045 client_suspend_self(bin, bout, berr);
1047 /* We have been continued. */
1052 snprintf(string, sizeof string,
1053 "%cB\r\n", escape_char);
1054 buffer_append(berr, string,
1056 channel_request_start(session_ident,
1058 packet_put_int(1000);
1065 if (datafellows & SSH_BUG_NOREKEY)
1066 logit("Server does not "
1067 "support re-keying");
1074 if (c && c->ctl_chan != -1)
1077 * Detach the program (continue to serve
1078 * connections, but put in background and no
1079 * more new connections).
1081 /* Restore tty modes. */
1083 options.request_tty == REQUEST_TTY_FORCE);
1085 /* Stop listening for new connections. */
1086 channel_stop_listening();
1088 snprintf(string, sizeof string,
1089 "%c& [backgrounded]\n", escape_char);
1090 buffer_append(berr, string, strlen(string));
1092 /* Fork into background. */
1095 error("fork: %.100s", strerror(errno));
1098 if (pid != 0) { /* This is the parent. */
1099 /* The parent just exits. */
1102 /* The child continues serving connections. */
1104 buffer_append(bin, "\004", 1);
1105 /* fake EOF on stdin */
1107 } else if (!stdin_eof) {
1109 * Sending SSH_CMSG_EOF alone does not
1110 * always appear to be enough. So we
1111 * try to send an EOF character first.
1113 packet_start(SSH_CMSG_STDIN_DATA);
1114 packet_put_string("\004", 1);
1118 if (buffer_len(bin) == 0) {
1119 packet_start(SSH_CMSG_EOF);
1126 if (c && c->ctl_chan != -1) {
1127 snprintf(string, sizeof string,
1129 Supported escape sequences:\r\n\
1130 %c. - terminate session\r\n\
1131 %cB - send a BREAK to the remote system\r\n\
1132 %cR - Request rekey (SSH protocol 2 only)\r\n\
1133 %c# - list forwarded connections\r\n\
1134 %c? - this message\r\n\
1135 %c%c - send the escape character by typing it twice\r\n\
1136 (Note that escapes are only recognized immediately after newline.)\r\n",
1137 escape_char, escape_char,
1138 escape_char, escape_char,
1139 escape_char, escape_char,
1140 escape_char, escape_char);
1142 snprintf(string, sizeof string,
1144 Supported escape sequences:\r\n\
1145 %c. - terminate connection (and any multiplexed sessions)\r\n\
1146 %cB - send a BREAK to the remote system\r\n\
1147 %cC - open a command line\r\n\
1148 %cR - Request rekey (SSH protocol 2 only)\r\n\
1149 %c^Z - suspend ssh\r\n\
1150 %c# - list forwarded connections\r\n\
1151 %c& - background ssh (when waiting for connections to terminate)\r\n\
1152 %c? - this message\r\n\
1153 %c%c - send the escape character by typing it twice\r\n\
1154 (Note that escapes are only recognized immediately after newline.)\r\n",
1155 escape_char, escape_char,
1156 escape_char, escape_char,
1157 escape_char, escape_char,
1158 escape_char, escape_char,
1159 escape_char, escape_char,
1162 buffer_append(berr, string, strlen(string));
1166 snprintf(string, sizeof string, "%c#\r\n",
1168 buffer_append(berr, string, strlen(string));
1169 s = channel_open_message();
1170 buffer_append(berr, s, strlen(s));
1175 if (c && c->ctl_chan != -1)
1181 if (ch != escape_char) {
1182 buffer_put_char(bin, escape_char);
1185 /* Escaped characters fall through here */
1190 * The previous character was not an escape char.
1191 * Check if this is an escape.
1193 if (last_was_cr && ch == escape_char) {
1195 * It is. Set the flag and continue to
1198 *escape_pendingp = 1;
1204 * Normal character. Record whether it was a newline,
1205 * and append it to the buffer.
1207 last_was_cr = (ch == '\r' || ch == '\n');
1208 buffer_put_char(bin, ch);
1215 client_process_input(fd_set *readset)
1218 char buf[SSH_IOBUFSZ];
1220 /* Read input from stdin. */
1221 if (FD_ISSET(fileno(stdin), readset)) {
1222 /* Read as much as possible. */
1223 len = read(fileno(stdin), buf, sizeof(buf));
1225 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1226 return; /* we'll try again later */
1229 * Received EOF or error. They are treated
1230 * similarly, except that an error message is printed
1231 * if it was an error condition.
1234 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1236 buffer_append(&stderr_buffer, buf, strlen(buf));
1238 /* Mark that we have seen EOF. */
1241 * Send an EOF message to the server unless there is
1242 * data in the buffer. If there is data in the
1243 * buffer, no message will be sent now. Code
1244 * elsewhere will send the EOF when the buffer
1245 * becomes empty if stdin_eof is set.
1247 if (buffer_len(&stdin_buffer) == 0) {
1248 packet_start(SSH_CMSG_EOF);
1251 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1253 * Normal successful read, and no escape character.
1254 * Just append the data to buffer.
1256 buffer_append(&stdin_buffer, buf, len);
1259 * Normal, successful read. But we have an escape
1260 * character and have to process the characters one
1263 if (process_escapes(NULL, &stdin_buffer,
1264 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1271 client_process_output(fd_set *writeset)
1276 /* Write buffered output to stdout. */
1277 if (FD_ISSET(fileno(stdout), writeset)) {
1278 /* Write as much data as possible. */
1279 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1280 buffer_len(&stdout_buffer));
1282 if (errno == EINTR || errno == EAGAIN ||
1283 errno == EWOULDBLOCK)
1287 * An error or EOF was encountered. Put an
1288 * error message to stderr buffer.
1290 snprintf(buf, sizeof buf,
1291 "write stdout: %.50s\r\n", strerror(errno));
1292 buffer_append(&stderr_buffer, buf, strlen(buf));
1297 /* Consume printed data from the buffer. */
1298 buffer_consume(&stdout_buffer, len);
1300 /* Write buffered output to stderr. */
1301 if (FD_ISSET(fileno(stderr), writeset)) {
1302 /* Write as much data as possible. */
1303 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1304 buffer_len(&stderr_buffer));
1306 if (errno == EINTR || errno == EAGAIN ||
1307 errno == EWOULDBLOCK)
1311 * EOF or error, but can't even print
1318 /* Consume printed characters from the buffer. */
1319 buffer_consume(&stderr_buffer, len);
1324 * Get packets from the connection input buffer, and process them as long as
1325 * there are packets available.
1327 * Any unknown packets received during the actual
1328 * session cause the session to terminate. This is
1329 * intended to make debugging easier since no
1330 * confirmations are sent. Any compatible protocol
1331 * extensions must be negotiated during the
1332 * preparatory phase.
1336 client_process_buffered_input_packets(void)
1338 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1339 compat20 ? xxx_kex : NULL);
1342 /* scan buf[] for '~' before sending data to the peer */
1344 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1346 client_new_escape_filter_ctx(int escape_char)
1348 struct escape_filter_ctx *ret;
1350 ret = xmalloc(sizeof(*ret));
1351 ret->escape_pending = 0;
1352 ret->escape_char = escape_char;
1356 /* Free the escape filter context on channel free */
1358 client_filter_cleanup(int cid, void *ctx)
1364 client_simple_escape_filter(Channel *c, char *buf, int len)
1366 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1369 return process_escapes(c, &c->input, &c->output, &c->extended,
1374 client_channel_closed(int id, void *arg)
1376 channel_cancel_cleanup(id);
1378 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1382 * Implements the interactive session with the server. This is called after
1383 * the user has been authenticated, and a command has been started on the
1384 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1385 * used as an escape character for terminating or suspending the session.
1389 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1391 fd_set *readset = NULL, *writeset = NULL;
1392 double start_time, total_time;
1393 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1394 u_int64_t ibytes, obytes;
1398 debug("Entering interactive session.");
1400 start_time = get_current_time();
1402 /* Initialize variables. */
1403 escape_pending1 = 0;
1407 buffer_high = 64 * 1024;
1408 connection_in = packet_get_connection_in();
1409 connection_out = packet_get_connection_out();
1410 max_fd = MAX(connection_in, connection_out);
1413 /* enable nonblocking unless tty */
1414 if (!isatty(fileno(stdin)))
1415 set_nonblock(fileno(stdin));
1416 if (!isatty(fileno(stdout)))
1417 set_nonblock(fileno(stdout));
1418 if (!isatty(fileno(stderr)))
1419 set_nonblock(fileno(stderr));
1420 max_fd = MAX(max_fd, fileno(stdin));
1421 max_fd = MAX(max_fd, fileno(stdout));
1422 max_fd = MAX(max_fd, fileno(stderr));
1425 escape_char1 = escape_char_arg;
1427 /* Initialize buffers. */
1428 buffer_init(&stdin_buffer);
1429 buffer_init(&stdout_buffer);
1430 buffer_init(&stderr_buffer);
1432 client_init_dispatch();
1435 * Set signal handlers, (e.g. to restore non-blocking mode)
1436 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1438 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1439 signal(SIGHUP, signal_handler);
1440 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1441 signal(SIGINT, signal_handler);
1442 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1443 signal(SIGQUIT, signal_handler);
1444 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1445 signal(SIGTERM, signal_handler);
1446 signal(SIGWINCH, window_change_handler);
1449 enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1452 session_ident = ssh2_chan_id;
1453 if (session_ident != -1) {
1454 if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1455 channel_register_filter(session_ident,
1456 client_simple_escape_filter, NULL,
1457 client_filter_cleanup,
1458 client_new_escape_filter_ctx(
1461 channel_register_cleanup(session_ident,
1462 client_channel_closed, 0);
1465 /* Check if we should immediately send eof on stdin. */
1466 client_check_initial_eof_on_stdin();
1469 /* Main loop of the client for the interactive session mode. */
1470 while (!quit_pending) {
1472 /* Process buffered packets sent by the server. */
1473 client_process_buffered_input_packets();
1475 if (compat20 && session_closed && !channel_still_open())
1478 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1481 debug("rekeying in progress");
1484 * Make packets of buffered stdin data, and buffer
1485 * them for sending to the server.
1488 client_make_packets_from_stdin_data();
1491 * Make packets from buffered channel data, and
1492 * enqueue them for sending to the server.
1494 if (packet_not_very_much_data_to_write())
1495 channel_output_poll();
1498 * Check if the window size has changed, and buffer a
1499 * message about it to the server if so.
1501 client_check_window_change();
1507 * Wait until we have something to do (something becomes
1508 * available on one of the descriptors).
1511 client_wait_until_can_do_something(&readset, &writeset,
1512 &max_fd2, &nalloc, rekeying);
1517 /* Do channel operations unless rekeying in progress. */
1519 channel_after_select(readset, writeset);
1522 if (options.gss_renewal_rekey &&
1523 ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
1524 debug("credentials updated - forcing rekey");
1529 if (need_rekeying || packet_need_rekeying()) {
1530 debug("need rekeying");
1532 kex_send_kexinit(xxx_kex);
1537 /* Buffer input from the connection. */
1538 client_process_net_input(readset);
1544 /* Buffer data from stdin */
1545 client_process_input(readset);
1547 * Process output to stdout and stderr. Output to
1548 * the connection is processed elsewhere (above).
1550 client_process_output(writeset);
1553 if (session_resumed) {
1554 connection_in = packet_get_connection_in();
1555 connection_out = packet_get_connection_out();
1556 max_fd = MAX(max_fd, connection_out);
1557 max_fd = MAX(max_fd, connection_in);
1558 session_resumed = 0;
1562 * Send as much buffered packet data as possible to the
1565 if (FD_ISSET(connection_out, writeset))
1566 packet_write_poll();
1569 * If we are a backgrounded control master, and the
1570 * timeout has expired without any active client
1571 * connections, then quit.
1573 if (control_persist_exit_time > 0) {
1574 if (time(NULL) >= control_persist_exit_time) {
1575 debug("ControlPersist timeout expired");
1585 /* Terminate the session. */
1587 /* Stop watching for window change. */
1588 signal(SIGWINCH, SIG_DFL);
1591 packet_start(SSH2_MSG_DISCONNECT);
1592 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1593 packet_put_cstring("disconnected by user");
1594 packet_put_cstring(""); /* language tag */
1596 packet_write_wait();
1602 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1604 /* restore blocking io */
1605 if (!isatty(fileno(stdin)))
1606 unset_nonblock(fileno(stdin));
1607 if (!isatty(fileno(stdout)))
1608 unset_nonblock(fileno(stdout));
1609 if (!isatty(fileno(stderr)))
1610 unset_nonblock(fileno(stderr));
1613 * If there was no shell or command requested, there will be no remote
1614 * exit status to be returned. In that case, clear error code if the
1615 * connection was deliberately terminated at this end.
1617 if (no_shell_flag && received_signal == SIGTERM) {
1618 received_signal = 0;
1622 if (received_signal) {
1623 debug("Killed by signal %d.", (int) received_signal);
1624 cleanup_exit((int) received_signal + 128);
1628 * In interactive mode (with pseudo tty) display a message indicating
1629 * that the connection has been closed.
1631 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1632 snprintf(buf, sizeof buf,
1633 "Connection to %.64s closed.\r\n", host);
1634 buffer_append(&stderr_buffer, buf, strlen(buf));
1637 /* Output any buffered data for stdout. */
1638 if (buffer_len(&stdout_buffer) > 0) {
1639 len = atomicio(vwrite, fileno(stdout),
1640 buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1641 if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1642 error("Write failed flushing stdout buffer.");
1644 buffer_consume(&stdout_buffer, len);
1647 /* Output any buffered data for stderr. */
1648 if (buffer_len(&stderr_buffer) > 0) {
1649 len = atomicio(vwrite, fileno(stderr),
1650 buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1651 if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1652 error("Write failed flushing stderr buffer.");
1654 buffer_consume(&stderr_buffer, len);
1657 /* Clear and free any buffers. */
1658 memset(buf, 0, sizeof(buf));
1659 buffer_free(&stdin_buffer);
1660 buffer_free(&stdout_buffer);
1661 buffer_free(&stderr_buffer);
1663 /* Report bytes transferred, and transfer rates. */
1664 total_time = get_current_time() - start_time;
1665 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1666 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1667 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1668 (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1670 verbose("Bytes per second: sent %.1f, received %.1f",
1671 obytes / total_time, ibytes / total_time);
1672 /* Return the exit status of the program. */
1673 debug("Exit status %d", exit_status);
1680 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1683 char *data = packet_get_string(&data_len);
1685 buffer_append(&stdout_buffer, data, data_len);
1686 memset(data, 0, data_len);
1690 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1693 char *data = packet_get_string(&data_len);
1695 buffer_append(&stderr_buffer, data, data_len);
1696 memset(data, 0, data_len);
1700 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1702 exit_status = packet_get_int();
1704 /* Acknowledge the exit. */
1705 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1708 * Must wait for packet to be sent since we are
1711 packet_write_wait();
1712 /* Flag that we want to exit. */
1716 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1719 int remote_id, sock;
1721 /* Read the remote channel number from the message. */
1722 remote_id = packet_get_int();
1726 * Get a connection to the local authentication agent (this may again
1729 sock = ssh_get_authentication_socket();
1732 * If we could not connect the agent, send an error message back to
1733 * the server. This should never happen unless the agent dies,
1734 * because authentication forwarding is only enabled if we have an
1738 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1739 -1, 0, 0, 0, "authentication agent connection", 1);
1740 c->remote_id = remote_id;
1744 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1745 packet_put_int(remote_id);
1747 /* Send a confirmation to the remote host. */
1748 debug("Forwarding authentication connection.");
1749 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1750 packet_put_int(remote_id);
1751 packet_put_int(c->self);
1757 client_request_forwarded_tcpip(const char *request_type, int rchan)
1760 char *listen_address, *originator_address;
1761 u_short listen_port, originator_port;
1763 /* Get rest of the packet */
1764 listen_address = packet_get_string(NULL);
1765 listen_port = packet_get_int();
1766 originator_address = packet_get_string(NULL);
1767 originator_port = packet_get_int();
1770 debug("client_request_forwarded_tcpip: listen %s port %d, "
1771 "originator %s port %d", listen_address, listen_port,
1772 originator_address, originator_port);
1774 c = channel_connect_by_listen_address(listen_port,
1775 "forwarded-tcpip", originator_address);
1777 xfree(originator_address);
1778 xfree(listen_address);
1783 client_request_x11(const char *request_type, int rchan)
1787 u_short originator_port;
1790 if (!options.forward_x11) {
1791 error("Warning: ssh server tried X11 forwarding.");
1792 error("Warning: this is probably a break-in attempt by a "
1793 "malicious server.");
1796 if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1797 verbose("Rejected X11 connection after ForwardX11Timeout "
1801 originator = packet_get_string(NULL);
1802 if (datafellows & SSH_BUG_X11FWD) {
1803 debug2("buggy server: x11 request w/o originator_port");
1804 originator_port = 0;
1806 originator_port = packet_get_int();
1809 /* XXX check permission */
1810 debug("client_request_x11: request from %s %d", originator,
1813 sock = x11_connect_display();
1816 c = channel_new("x11",
1817 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1818 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1824 client_request_agent(const char *request_type, int rchan)
1829 if (!options.forward_agent) {
1830 error("Warning: ssh server tried agent forwarding.");
1831 error("Warning: this is probably a break-in attempt by a "
1832 "malicious server.");
1835 sock = ssh_get_authentication_socket();
1838 c = channel_new("authentication agent connection",
1839 SSH_CHANNEL_OPEN, sock, sock, -1,
1840 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1841 "authentication agent connection", 1);
1847 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1852 if (tun_mode == SSH_TUNMODE_NO)
1856 error("Tunnel forwarding is not supported for protocol 1");
1860 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1862 /* Open local tunnel device */
1863 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1864 error("Tunnel device open failed.");
1868 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1869 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1872 #if defined(SSH_TUN_FILTER)
1873 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1874 channel_register_filter(c->self, sys_tun_infilter,
1875 sys_tun_outfilter, NULL, NULL);
1878 packet_start(SSH2_MSG_CHANNEL_OPEN);
1879 packet_put_cstring("tun@openssh.com");
1880 packet_put_int(c->self);
1881 packet_put_int(c->local_window_max);
1882 packet_put_int(c->local_maxpacket);
1883 packet_put_int(tun_mode);
1884 packet_put_int(remote_tun);
1890 /* XXXX move to generic input handler */
1892 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1897 u_int rmaxpack, rwindow, len;
1899 ctype = packet_get_string(&len);
1900 rchan = packet_get_int();
1901 rwindow = packet_get_int();
1902 rmaxpack = packet_get_int();
1904 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1905 ctype, rchan, rwindow, rmaxpack);
1907 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1908 c = client_request_forwarded_tcpip(ctype, rchan);
1909 } else if (strcmp(ctype, "x11") == 0) {
1910 c = client_request_x11(ctype, rchan);
1911 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1912 c = client_request_agent(ctype, rchan);
1914 /* XXX duplicate : */
1916 debug("confirm %s", ctype);
1917 c->remote_id = rchan;
1918 c->remote_window = rwindow;
1919 c->remote_maxpacket = rmaxpack;
1920 if (c->type != SSH_CHANNEL_CONNECTING) {
1921 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1922 packet_put_int(c->remote_id);
1923 packet_put_int(c->self);
1924 packet_put_int(c->local_window);
1925 packet_put_int(c->local_maxpacket);
1929 debug("failure %s", ctype);
1930 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1931 packet_put_int(rchan);
1932 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1933 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1934 packet_put_cstring("open failed");
1935 packet_put_cstring("");
1942 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1945 int exitval, id, reply, success = 0;
1948 id = packet_get_int();
1949 rtype = packet_get_string(NULL);
1950 reply = packet_get_char();
1952 debug("client_input_channel_req: channel %d rtype %s reply %d",
1956 error("client_input_channel_req: request for channel -1");
1957 } else if ((c = channel_lookup(id)) == NULL) {
1958 error("client_input_channel_req: channel %d: "
1959 "unknown channel", id);
1960 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1963 } else if (strcmp(rtype, "exit-status") == 0) {
1964 exitval = packet_get_int();
1965 if (c->ctl_chan != -1) {
1966 mux_exit_message(c, exitval);
1968 } else if (id == session_ident) {
1969 /* Record exit value of local session */
1971 exit_status = exitval;
1973 /* Probably for a mux channel that has already closed */
1974 debug("%s: no sink for exit-status on channel %d",
1979 if (reply && c != NULL) {
1980 packet_start(success ?
1981 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1982 packet_put_int(c->remote_id);
1988 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1994 rtype = packet_get_string(NULL);
1995 want_reply = packet_get_char();
1996 debug("client_input_global_request: rtype %s want_reply %d",
1999 packet_start(success ?
2000 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2002 packet_write_wait();
2008 client_session2_setup(int id, int want_tty, int want_subsystem,
2009 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2014 debug2("%s: id %d", __func__, id);
2016 if ((c = channel_lookup(id)) == NULL)
2017 fatal("client_session2_setup: channel %d: unknown channel", id);
2019 packet_set_interactive(want_tty,
2020 options.ip_qos_interactive, options.ip_qos_bulk);
2025 /* Store window size in the packet. */
2026 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2027 memset(&ws, 0, sizeof(ws));
2029 channel_request_start(id, "pty-req", 1);
2030 client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2031 packet_put_cstring(term != NULL ? term : "");
2032 packet_put_int((u_int)ws.ws_col);
2033 packet_put_int((u_int)ws.ws_row);
2034 packet_put_int((u_int)ws.ws_xpixel);
2035 packet_put_int((u_int)ws.ws_ypixel);
2037 tiop = get_saved_tio();
2038 tty_make_modes(-1, tiop);
2040 /* XXX wait for reply */
2044 /* Transfer any environment variables from client to server */
2045 if (options.num_send_env != 0 && env != NULL) {
2049 debug("Sending environment.");
2050 for (i = 0; env[i] != NULL; i++) {
2052 name = xstrdup(env[i]);
2053 if ((val = strchr(name, '=')) == NULL) {
2060 for (j = 0; j < options.num_send_env; j++) {
2061 if (match_pattern(name, options.send_env[j])) {
2067 debug3("Ignored env %s", name);
2072 debug("Sending env %s = %s", name, val);
2073 channel_request_start(id, "env", 0);
2074 packet_put_cstring(name);
2075 packet_put_cstring(val);
2081 len = buffer_len(cmd);
2085 if (want_subsystem) {
2086 debug("Sending subsystem: %.*s",
2087 len, (u_char*)buffer_ptr(cmd));
2088 channel_request_start(id, "subsystem", 1);
2089 client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2091 debug("Sending command: %.*s",
2092 len, (u_char*)buffer_ptr(cmd));
2093 channel_request_start(id, "exec", 1);
2094 client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2096 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2099 channel_request_start(id, "shell", 1);
2100 client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2106 client_init_dispatch_20(void)
2108 dispatch_init(&dispatch_protocol_error);
2110 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2111 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2112 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2113 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2114 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2115 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2116 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2117 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2118 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2119 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2120 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2121 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2124 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2126 /* global request reply messages */
2127 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2128 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2132 client_init_dispatch_13(void)
2134 dispatch_init(NULL);
2135 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2136 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2137 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2138 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2139 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2140 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2141 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2142 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2143 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2145 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2146 &client_input_agent_open : &deny_input_open);
2147 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2148 &x11_input_open : &deny_input_open);
2152 client_init_dispatch_15(void)
2154 client_init_dispatch_13();
2155 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2156 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2160 client_init_dispatch(void)
2163 client_init_dispatch_20();
2165 client_init_dispatch_13();
2167 client_init_dispatch_15();
2171 client_stop_mux(void)
2173 if (options.control_path != NULL && muxserver_sock != -1)
2174 unlink(options.control_path);
2176 * If we are in persist mode, signal that we should close when all
2177 * active channels are closed.
2179 if (options.control_persist) {
2181 setproctitle("[stopped mux]");
2185 /* client specific fatal cleanup */
2189 leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2190 leave_non_blocking();
2191 if (options.control_path != NULL && muxserver_sock != -1)
2192 unlink(options.control_path);
2193 ssh_kill_proxy_command();