1 /* $OpenBSD: clientloop.c,v 1.190 2008/05/08 13:06:10 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"
110 #include "monitor_fdpass.h"
115 extern Options options;
117 /* Flag indicating that stdin should be redirected from /dev/null. */
118 extern int stdin_null_flag;
120 /* Flag indicating that no shell has been requested */
121 extern int no_shell_flag;
124 extern int control_fd;
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the HostName specified for the user-supplied name in a
129 * configuration file.
134 * Flag to indicate that we have received a window change signal which has
135 * not yet been processed. This will cause a message indicating the new
136 * window size to be sent to the server a little later. This is volatile
137 * because this is updated in a signal handler.
139 static volatile sig_atomic_t received_window_change_signal = 0;
140 static volatile sig_atomic_t received_signal = 0;
142 /* Flag indicating whether the user's terminal is in non-blocking mode. */
143 static int in_non_blocking_mode = 0;
145 /* Common data for the client loop code. */
146 static volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
147 static int escape_char; /* Escape character. */
148 static int escape_pending; /* Last character was the escape character */
149 static int last_was_cr; /* Last character was a newline. */
150 static int exit_status; /* Used to store the exit status of the command. */
151 static int stdin_eof; /* EOF has been encountered on standard error. */
152 static Buffer stdin_buffer; /* Buffer for stdin data. */
153 static Buffer stdout_buffer; /* Buffer for stdout data. */
154 static Buffer stderr_buffer; /* Buffer for stderr data. */
155 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
156 static u_int buffer_high;/* Soft max buffer size. */
157 static int connection_in; /* Connection to server (input). */
158 static int connection_out; /* Connection to server (output). */
159 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
160 static int session_closed = 0; /* In SSH2: login session closed. */
162 static void client_init_dispatch(void);
163 int session_ident = -1;
176 struct channel_reply_ctx {
177 const char *request_type;
184 void ssh_process_session2_setup(int, int, int, Buffer *);
186 /* Restores stdin to blocking mode. */
189 leave_non_blocking(void)
191 if (in_non_blocking_mode) {
192 unset_nonblock(fileno(stdin));
193 in_non_blocking_mode = 0;
197 /* Puts stdin terminal in non-blocking mode. */
200 enter_non_blocking(void)
202 in_non_blocking_mode = 1;
203 set_nonblock(fileno(stdin));
207 * Signal handler for the window change signal (SIGWINCH). This just sets a
208 * flag indicating that the window has changed.
212 window_change_handler(int sig)
214 received_window_change_signal = 1;
215 signal(SIGWINCH, window_change_handler);
219 * Signal handler for signals that cause the program to terminate. These
220 * signals must be trapped to restore terminal modes.
224 signal_handler(int sig)
226 received_signal = sig;
231 * Returns current time in seconds from Jan 1, 1970 with the maximum
232 * available resolution.
236 get_current_time(void)
239 gettimeofday(&tv, NULL);
240 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
243 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
245 client_x11_get_proto(const char *display, const char *xauth_path,
246 u_int trusted, char **_proto, char **_data)
251 static char proto[512], data[512];
253 int got_data = 0, generated = 0, do_unlink = 0, i;
254 char *xauthdir, *xauthfile;
257 xauthdir = xauthfile = NULL;
260 proto[0] = data[0] = '\0';
262 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
263 debug("No xauth program.");
265 if (display == NULL) {
266 debug("x11_get_proto: DISPLAY not set");
270 * Handle FamilyLocal case where $DISPLAY does
271 * not match an authorization entry. For this we
272 * just try "xauth list unix:displaynum.screennum".
273 * XXX: "localhost" match to determine FamilyLocal
276 if (strncmp(display, "localhost:", 10) == 0) {
277 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
282 xauthdir = xmalloc(MAXPATHLEN);
283 xauthfile = xmalloc(MAXPATHLEN);
284 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
285 if (mkdtemp(xauthdir) != NULL) {
287 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
289 snprintf(cmd, sizeof(cmd),
290 "%s -f %s generate %s " SSH_X11_PROTO
291 " untrusted timeout 1200 2>" _PATH_DEVNULL,
292 xauth_path, xauthfile, display);
293 debug2("x11_get_proto: %s", cmd);
294 if (system(cmd) == 0)
300 * When in untrusted mode, we read the cookie only if it was
301 * successfully generated as an untrusted one in the step
304 if (trusted || generated) {
305 snprintf(cmd, sizeof(cmd),
306 "%s %s%s list %s 2>" _PATH_DEVNULL,
308 generated ? "-f " : "" ,
309 generated ? xauthfile : "",
311 debug2("x11_get_proto: %s", cmd);
313 if (f && fgets(line, sizeof(line), f) &&
314 sscanf(line, "%*s %511s %511s", proto, data) == 2)
319 error("Warning: untrusted X11 forwarding setup failed: "
320 "xauth key data not generated");
333 * If we didn't get authentication data, just make up some
334 * data. The forwarding code will check the validity of the
335 * response anyway, and substitute this data. The X11
336 * server, however, will ignore this fake data and use
337 * whatever authentication mechanisms it was using otherwise
338 * for the local connection.
343 logit("Warning: No xauth data; "
344 "using fake authentication data for X11 forwarding.");
345 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
346 for (i = 0; i < 16; i++) {
349 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
357 * This is called when the interactive is entered. This checks if there is
358 * an EOF coming on stdin. We must check this explicitly, as select() does
359 * not appear to wake up when redirecting from /dev/null.
363 client_check_initial_eof_on_stdin(void)
369 * If standard input is to be "redirected from /dev/null", we simply
370 * mark that we have seen an EOF and send an EOF message to the
371 * server. Otherwise, we try to read a single character; it appears
372 * that for some files, such /dev/null, select() never wakes up for
373 * read for this descriptor, which means that we never get EOF. This
374 * way we will get the EOF if stdin comes from /dev/null or similar.
376 if (stdin_null_flag) {
377 /* Fake EOF on stdin. */
378 debug("Sending eof.");
380 packet_start(SSH_CMSG_EOF);
383 enter_non_blocking();
385 /* Check for immediate EOF on stdin. */
386 len = read(fileno(stdin), buf, 1);
388 /* EOF. Record that we have seen it and send EOF to server. */
389 debug("Sending eof.");
391 packet_start(SSH_CMSG_EOF);
393 } else if (len > 0) {
395 * Got data. We must store the data in the buffer,
396 * and also process it as an escape character if
399 if ((u_char) buf[0] == escape_char)
402 buffer_append(&stdin_buffer, buf, 1);
404 leave_non_blocking();
410 * Make packets from buffered stdin data, and buffer them for sending to the
415 client_make_packets_from_stdin_data(void)
419 /* Send buffered stdin data to the server. */
420 while (buffer_len(&stdin_buffer) > 0 &&
421 packet_not_very_much_data_to_write()) {
422 len = buffer_len(&stdin_buffer);
423 /* Keep the packets at reasonable size. */
424 if (len > packet_get_maxsize())
425 len = packet_get_maxsize();
426 packet_start(SSH_CMSG_STDIN_DATA);
427 packet_put_string(buffer_ptr(&stdin_buffer), len);
429 buffer_consume(&stdin_buffer, len);
431 /* If we have a pending EOF, send it now. */
432 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
433 packet_start(SSH_CMSG_EOF);
440 * Checks if the client window has changed, and sends a packet about it to
441 * the server if so. The actual change is detected elsewhere (by a software
442 * interrupt on Unix); this just checks the flag and sends a message if
447 client_check_window_change(void)
451 if (! received_window_change_signal)
454 received_window_change_signal = 0;
456 debug2("client_check_window_change: changed");
459 channel_send_window_changes();
461 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
463 packet_start(SSH_CMSG_WINDOW_SIZE);
464 packet_put_int((u_int)ws.ws_row);
465 packet_put_int((u_int)ws.ws_col);
466 packet_put_int((u_int)ws.ws_xpixel);
467 packet_put_int((u_int)ws.ws_ypixel);
473 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
475 keep_alive_timeouts = 0;
476 client_global_request_reply_fwd(type, seq, ctxt);
480 server_alive_check(void)
482 if (++keep_alive_timeouts > options.server_alive_count_max) {
483 logit("Timeout, server not responding.");
486 packet_start(SSH2_MSG_GLOBAL_REQUEST);
487 packet_put_cstring("keepalive@openssh.com");
488 packet_put_char(1); /* boolean: want reply */
493 * Waits until the client can do something (some data becomes available on
494 * one of the file descriptors).
497 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
498 int *maxfdp, u_int *nallocp, int rekeying)
500 struct timeval tv, *tvp;
503 /* Add any selections by the channel mechanism. */
504 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
507 /* Read from the connection, unless our buffers are full. */
508 if (buffer_len(&stdout_buffer) < buffer_high &&
509 buffer_len(&stderr_buffer) < buffer_high &&
510 channel_not_very_much_buffered_data())
511 FD_SET(connection_in, *readsetp);
513 * Read from stdin, unless we have seen EOF or have very much
514 * buffered data to send to the server.
516 if (!stdin_eof && packet_not_very_much_data_to_write())
517 FD_SET(fileno(stdin), *readsetp);
519 /* Select stdout/stderr if have data in buffer. */
520 if (buffer_len(&stdout_buffer) > 0)
521 FD_SET(fileno(stdout), *writesetp);
522 if (buffer_len(&stderr_buffer) > 0)
523 FD_SET(fileno(stderr), *writesetp);
525 /* channel_prepare_select could have closed the last channel */
526 if (session_closed && !channel_still_open() &&
527 !packet_have_data_to_write()) {
528 /* clear mask since we did not call select() */
529 memset(*readsetp, 0, *nallocp);
530 memset(*writesetp, 0, *nallocp);
533 FD_SET(connection_in, *readsetp);
537 /* Select server connection if have data to write to the server. */
538 if (packet_have_data_to_write())
539 FD_SET(connection_out, *writesetp);
541 if (control_fd != -1)
542 FD_SET(control_fd, *readsetp);
545 * Wait for something to happen. This will suspend the process until
546 * some selected descriptor can be read, written, or has some other
550 if (options.server_alive_interval == 0 || !compat20)
553 tv.tv_sec = options.server_alive_interval;
557 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
562 * We have to clear the select masks, because we return.
563 * We have to return, because the mainloop checks for the flags
564 * set by the signal handlers.
566 memset(*readsetp, 0, *nallocp);
567 memset(*writesetp, 0, *nallocp);
571 /* Note: we might still have data in the buffers. */
572 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
573 buffer_append(&stderr_buffer, buf, strlen(buf));
576 server_alive_check();
580 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
582 /* Flush stdout and stderr buffers. */
583 if (buffer_len(bout) > 0)
584 atomicio(vwrite, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
585 if (buffer_len(berr) > 0)
586 atomicio(vwrite, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
591 * Free (and clear) the buffer to reduce the amount of data that gets
598 /* Send the suspend signal to the program itself. */
599 kill(getpid(), SIGTSTP);
601 /* Reset window sizes in case they have changed */
602 received_window_change_signal = 1;
604 /* OK, we have been continued by the user. Reinitialize buffers. */
613 client_process_net_input(fd_set *readset)
619 * Read input from the server, and add any such data to the buffer of
620 * the packet subsystem.
622 if (FD_ISSET(connection_in, readset)) {
623 /* Read as much as possible. */
624 len = read(connection_in, buf, sizeof(buf));
626 /* Received EOF. The remote host has closed the connection. */
627 snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
629 buffer_append(&stderr_buffer, buf, strlen(buf));
634 * There is a kernel bug on Solaris that causes select to
635 * sometimes wake up even though there is no data available.
637 if (len < 0 && (errno == EAGAIN || errno == EINTR))
641 /* An error has encountered. Perhaps there is a network problem. */
642 snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
643 host, strerror(errno));
644 buffer_append(&stderr_buffer, buf, strlen(buf));
648 packet_process_incoming(buf, len);
653 client_status_confirm(int type, Channel *c, void *ctx)
655 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
659 /* XXX supress on mux _client_ quietmode */
660 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
661 c->ctl_fd != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
663 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
664 debug2("%s request accepted on channel %d",
665 cr->request_type, c->self);
666 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
668 snprintf(errmsg, sizeof(errmsg),
669 "%s request failed\r\n", cr->request_type);
671 snprintf(errmsg, sizeof(errmsg),
672 "%s request failed on channel %d",
673 cr->request_type, c->self);
675 /* If error occurred on primary session channel, then exit */
676 if (cr->do_close && c->self == session_ident)
678 /* If error occurred on mux client, append to their stderr */
680 buffer_append(&c->extended, errmsg, strlen(errmsg));
685 chan_write_failed(c);
692 client_abandon_status_confirm(Channel *c, void *ctx)
698 client_expect_confirm(int id, const char *request, int do_close)
700 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
702 cr->request_type = request;
703 cr->do_close = do_close;
705 channel_register_status_confirm(id, client_status_confirm,
706 client_abandon_status_confirm, cr);
710 client_extra_session2_setup(int id, void *arg)
712 struct confirm_ctx *cctx = arg;
718 fatal("%s: cctx == NULL", __func__);
719 if ((c = channel_lookup(id)) == NULL)
720 fatal("%s: no channel for id %d", __func__, id);
722 display = getenv("DISPLAY");
723 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
725 /* Get reasonable local authentication information. */
726 client_x11_get_proto(display, options.xauth_location,
727 options.forward_x11_trusted, &proto, &data);
728 /* Request forwarding with authentication spoofing. */
729 debug("Requesting X11 forwarding with authentication spoofing.");
730 x11_request_forwarding_with_spoofing(id, display, proto, data);
731 /* XXX wait for reply */
734 if (cctx->want_agent_fwd && options.forward_agent) {
735 debug("Requesting authentication agent forwarding.");
736 channel_request_start(id, "auth-agent-req@openssh.com", 0);
740 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
741 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env);
743 c->open_confirm_ctx = NULL;
744 buffer_free(&cctx->cmd);
746 if (cctx->env != NULL) {
747 for (i = 0; cctx->env[i] != NULL; i++)
755 client_process_control(fd_set *readset)
759 int client_fd, new_fd[3], ver, allowed, window, packetmax;
761 struct sockaddr_storage addr;
762 struct confirm_ctx *cctx;
764 u_int i, j, len, env_len, command, flags;
769 * Accept connection on control socket
771 if (control_fd == -1 || !FD_ISSET(control_fd, readset))
774 memset(&addr, 0, sizeof(addr));
775 addrlen = sizeof(addr);
776 if ((client_fd = accept(control_fd,
777 (struct sockaddr*)&addr, &addrlen)) == -1) {
778 error("%s accept: %s", __func__, strerror(errno));
782 if (getpeereid(client_fd, &euid, &egid) < 0) {
783 error("%s getpeereid failed: %s", __func__, strerror(errno));
787 if ((euid != 0) && (getuid() != euid)) {
788 error("control mode uid mismatch: peer euid %u != uid %u",
789 (u_int) euid, (u_int) getuid());
794 unset_nonblock(client_fd);
798 if (ssh_msg_recv(client_fd, &m) == -1) {
799 error("%s: client msg_recv failed", __func__);
804 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
805 error("%s: wrong client version %d", __func__, ver);
812 command = buffer_get_int(&m);
813 flags = buffer_get_int(&m);
818 case SSHMUX_COMMAND_OPEN:
819 if (options.control_master == SSHCTL_MASTER_ASK ||
820 options.control_master == SSHCTL_MASTER_AUTO_ASK)
821 allowed = ask_permission("Allow shared connection "
825 case SSHMUX_COMMAND_TERMINATE:
826 if (options.control_master == SSHCTL_MASTER_ASK ||
827 options.control_master == SSHCTL_MASTER_AUTO_ASK)
828 allowed = ask_permission("Terminate shared connection "
833 case SSHMUX_COMMAND_ALIVE_CHECK:
834 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
836 buffer_put_int(&m, allowed);
837 buffer_put_int(&m, getpid());
838 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
839 error("%s: client msg_send failed", __func__);
848 error("Unsupported command %d", command);
854 /* Reply for SSHMUX_COMMAND_OPEN */
856 buffer_put_int(&m, allowed);
857 buffer_put_int(&m, getpid());
858 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
859 error("%s: client msg_send failed", __func__);
866 error("Refused control connection");
873 if (ssh_msg_recv(client_fd, &m) == -1) {
874 error("%s: client msg_recv failed", __func__);
879 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
880 error("%s: wrong client version %d", __func__, ver);
886 cctx = xcalloc(1, sizeof(*cctx));
887 cctx->want_tty = (flags & SSHMUX_FLAG_TTY) != 0;
888 cctx->want_subsys = (flags & SSHMUX_FLAG_SUBSYS) != 0;
889 cctx->want_x_fwd = (flags & SSHMUX_FLAG_X11_FWD) != 0;
890 cctx->want_agent_fwd = (flags & SSHMUX_FLAG_AGENT_FWD) != 0;
891 cctx->term = buffer_get_string(&m, &len);
893 cmd = buffer_get_string(&m, &len);
894 buffer_init(&cctx->cmd);
895 buffer_append(&cctx->cmd, cmd, strlen(cmd));
897 env_len = buffer_get_int(&m);
898 env_len = MIN(env_len, 4096);
899 debug3("%s: receiving %d env vars", __func__, env_len);
901 cctx->env = xcalloc(env_len + 1, sizeof(*cctx->env));
902 for (i = 0; i < env_len; i++)
903 cctx->env[i] = buffer_get_string(&m, &len);
907 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
908 cctx->want_tty, cctx->want_subsys, cmd);
911 /* Gather fds from client */
912 for(i = 0; i < 3; i++) {
913 if ((new_fd[i] = mm_receive_fd(client_fd)) == -1) {
914 error("%s: failed to receive fd %d from slave",
916 for (j = 0; j < i; j++)
918 for (j = 0; j < env_len; j++)
923 buffer_free(&cctx->cmd);
930 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
931 new_fd[0], new_fd[1], new_fd[2]);
933 /* Try to pick up ttymodes from client before it goes raw */
934 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
935 error("%s: tcgetattr: %s", __func__, strerror(errno));
937 /* This roundtrip is just for synchronisation of ttymodes */
939 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
940 error("%s: client msg_send failed", __func__);
948 for (i = 0; i < env_len; i++)
956 /* enable nonblocking unless tty */
957 if (!isatty(new_fd[0]))
958 set_nonblock(new_fd[0]);
959 if (!isatty(new_fd[1]))
960 set_nonblock(new_fd[1]);
961 if (!isatty(new_fd[2]))
962 set_nonblock(new_fd[2]);
964 set_nonblock(client_fd);
966 window = CHAN_SES_WINDOW_DEFAULT;
967 packetmax = CHAN_SES_PACKET_DEFAULT;
968 if (cctx->want_tty) {
973 c = channel_new("session", SSH_CHANNEL_OPENING,
974 new_fd[0], new_fd[1], new_fd[2], window, packetmax,
975 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
978 c->ctl_fd = client_fd;
980 debug3("%s: channel_new: %d", __func__, c->self);
982 channel_send_open(c->self);
983 channel_register_open_confirm(c->self,
984 client_extra_session2_setup, cctx);
988 process_cmdline(void)
990 void (*handler)(int);
991 char *s, *cmd, *cancel_host;
997 bzero(&fwd, sizeof(fwd));
998 fwd.listen_host = fwd.connect_host = NULL;
1001 handler = signal(SIGINT, SIG_IGN);
1002 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
1008 s++; /* Skip cmdline '-', if any */
1012 if (*s == 'h' || *s == 'H' || *s == '?') {
1014 logit(" -L[bind_address:]port:host:hostport "
1015 "Request local forward");
1016 logit(" -R[bind_address:]port:host:hostport "
1017 "Request remote forward");
1018 logit(" -KR[bind_address:]port "
1019 "Cancel remote forward");
1020 if (!options.permit_local_command)
1023 "Execute local command");
1027 if (*s == '!' && options.permit_local_command) {
1037 if (*s != 'L' && *s != 'R') {
1038 logit("Invalid command.");
1043 if (local && delete) {
1044 logit("Not supported.");
1047 if ((!local || delete) && !compat20) {
1048 logit("Not supported for SSH protocol version 1.");
1052 while (isspace(*++s))
1057 cancel_host = hpdelim(&s); /* may be NULL */
1059 cancel_port = a2port(s);
1060 cancel_host = cleanhostname(cancel_host);
1062 cancel_port = a2port(cancel_host);
1065 if (cancel_port == 0) {
1066 logit("Bad forwarding close port");
1069 channel_request_rforward_cancel(cancel_host, cancel_port);
1071 if (!parse_forward(&fwd, s)) {
1072 logit("Bad forwarding specification.");
1076 if (channel_setup_local_fwd_listener(fwd.listen_host,
1077 fwd.listen_port, fwd.connect_host,
1078 fwd.connect_port, options.gateway_ports) < 0) {
1079 logit("Port forwarding failed.");
1083 if (channel_request_remote_forwarding(fwd.listen_host,
1084 fwd.listen_port, fwd.connect_host,
1085 fwd.connect_port) < 0) {
1086 logit("Port forwarding failed.");
1091 logit("Forwarding port.");
1095 signal(SIGINT, handler);
1099 if (fwd.listen_host != NULL)
1100 xfree(fwd.listen_host);
1101 if (fwd.connect_host != NULL)
1102 xfree(fwd.connect_host);
1105 /* process the characters one by one */
1107 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
1119 for (i = 0; i < (u_int)len; i++) {
1120 /* Get one character at a time. */
1123 if (escape_pending) {
1124 /* We have previously seen an escape character. */
1125 /* Clear the flag now. */
1128 /* Process the escaped character. */
1131 /* Terminate the connection. */
1132 snprintf(string, sizeof string, "%c.\r\n", escape_char);
1133 buffer_append(berr, string, strlen(string));
1139 /* Suspend the program. */
1140 /* Print a message to that effect to the user. */
1141 snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
1142 buffer_append(berr, string, strlen(string));
1144 /* Restore terminal modes and suspend. */
1145 client_suspend_self(bin, bout, berr);
1147 /* We have been continued. */
1152 snprintf(string, sizeof string,
1153 "%cB\r\n", escape_char);
1154 buffer_append(berr, string,
1156 channel_request_start(session_ident,
1158 packet_put_int(1000);
1165 if (datafellows & SSH_BUG_NOREKEY)
1166 logit("Server does not support re-keying");
1174 * Detach the program (continue to serve connections,
1175 * but put in background and no more new connections).
1177 /* Restore tty modes. */
1180 /* Stop listening for new connections. */
1181 channel_stop_listening();
1183 snprintf(string, sizeof string,
1184 "%c& [backgrounded]\n", escape_char);
1185 buffer_append(berr, string, strlen(string));
1187 /* Fork into background. */
1190 error("fork: %.100s", strerror(errno));
1193 if (pid != 0) { /* This is the parent. */
1194 /* The parent just exits. */
1197 /* The child continues serving connections. */
1199 buffer_append(bin, "\004", 1);
1200 /* fake EOF on stdin */
1202 } else if (!stdin_eof) {
1204 * Sending SSH_CMSG_EOF alone does not always appear
1205 * to be enough. So we try to send an EOF character
1208 packet_start(SSH_CMSG_STDIN_DATA);
1209 packet_put_string("\004", 1);
1213 if (buffer_len(bin) == 0) {
1214 packet_start(SSH_CMSG_EOF);
1221 snprintf(string, sizeof string,
1223 Supported escape sequences:\r\n\
1224 %c. - terminate connection\r\n\
1225 %cB - send a BREAK to the remote system\r\n\
1226 %cC - open a command line\r\n\
1227 %cR - Request rekey (SSH protocol 2 only)\r\n\
1228 %c^Z - suspend ssh\r\n\
1229 %c# - list forwarded connections\r\n\
1230 %c& - background ssh (when waiting for connections to terminate)\r\n\
1231 %c? - this message\r\n\
1232 %c%c - send the escape character by typing it twice\r\n\
1233 (Note that escapes are only recognized immediately after newline.)\r\n",
1234 escape_char, escape_char, escape_char, escape_char,
1235 escape_char, escape_char, escape_char, escape_char,
1236 escape_char, escape_char, escape_char);
1237 buffer_append(berr, string, strlen(string));
1241 snprintf(string, sizeof string, "%c#\r\n", escape_char);
1242 buffer_append(berr, string, strlen(string));
1243 s = channel_open_message();
1244 buffer_append(berr, s, strlen(s));
1253 if (ch != escape_char) {
1254 buffer_put_char(bin, escape_char);
1257 /* Escaped characters fall through here */
1262 * The previous character was not an escape char. Check if this
1265 if (last_was_cr && ch == escape_char) {
1266 /* It is. Set the flag and continue to next character. */
1273 * Normal character. Record whether it was a newline,
1274 * and append it to the buffer.
1276 last_was_cr = (ch == '\r' || ch == '\n');
1277 buffer_put_char(bin, ch);
1284 client_process_input(fd_set *readset)
1289 /* Read input from stdin. */
1290 if (FD_ISSET(fileno(stdin), readset)) {
1291 /* Read as much as possible. */
1292 len = read(fileno(stdin), buf, sizeof(buf));
1293 if (len < 0 && (errno == EAGAIN || errno == EINTR))
1294 return; /* we'll try again later */
1297 * Received EOF or error. They are treated
1298 * similarly, except that an error message is printed
1299 * if it was an error condition.
1302 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
1303 buffer_append(&stderr_buffer, buf, strlen(buf));
1305 /* Mark that we have seen EOF. */
1308 * Send an EOF message to the server unless there is
1309 * data in the buffer. If there is data in the
1310 * buffer, no message will be sent now. Code
1311 * elsewhere will send the EOF when the buffer
1312 * becomes empty if stdin_eof is set.
1314 if (buffer_len(&stdin_buffer) == 0) {
1315 packet_start(SSH_CMSG_EOF);
1318 } else if (escape_char == SSH_ESCAPECHAR_NONE) {
1320 * Normal successful read, and no escape character.
1321 * Just append the data to buffer.
1323 buffer_append(&stdin_buffer, buf, len);
1326 * Normal, successful read. But we have an escape character
1327 * and have to process the characters one by one.
1329 if (process_escapes(&stdin_buffer, &stdout_buffer,
1330 &stderr_buffer, buf, len) == -1)
1337 client_process_output(fd_set *writeset)
1342 /* Write buffered output to stdout. */
1343 if (FD_ISSET(fileno(stdout), writeset)) {
1344 /* Write as much data as possible. */
1345 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1346 buffer_len(&stdout_buffer));
1348 if (errno == EINTR || errno == EAGAIN)
1352 * An error or EOF was encountered. Put an
1353 * error message to stderr buffer.
1355 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
1356 buffer_append(&stderr_buffer, buf, strlen(buf));
1361 /* Consume printed data from the buffer. */
1362 buffer_consume(&stdout_buffer, len);
1363 stdout_bytes += len;
1365 /* Write buffered output to stderr. */
1366 if (FD_ISSET(fileno(stderr), writeset)) {
1367 /* Write as much data as possible. */
1368 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1369 buffer_len(&stderr_buffer));
1371 if (errno == EINTR || errno == EAGAIN)
1374 /* EOF or error, but can't even print error message. */
1379 /* Consume printed characters from the buffer. */
1380 buffer_consume(&stderr_buffer, len);
1381 stderr_bytes += len;
1386 * Get packets from the connection input buffer, and process them as long as
1387 * there are packets available.
1389 * Any unknown packets received during the actual
1390 * session cause the session to terminate. This is
1391 * intended to make debugging easier since no
1392 * confirmations are sent. Any compatible protocol
1393 * extensions must be negotiated during the
1394 * preparatory phase.
1398 client_process_buffered_input_packets(void)
1400 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
1403 /* scan buf[] for '~' before sending data to the peer */
1406 simple_escape_filter(Channel *c, char *buf, int len)
1408 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1411 return process_escapes(&c->input, &c->output, &c->extended, buf, len);
1415 client_channel_closed(int id, void *arg)
1417 channel_cancel_cleanup(id);
1423 * Implements the interactive session with the server. This is called after
1424 * the user has been authenticated, and a command has been started on the
1425 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1426 * used as an escape character for terminating or suspending the session.
1430 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1432 fd_set *readset = NULL, *writeset = NULL;
1433 double start_time, total_time;
1434 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1438 debug("Entering interactive session.");
1440 start_time = get_current_time();
1442 /* Initialize variables. */
1447 buffer_high = 64 * 1024;
1448 connection_in = packet_get_connection_in();
1449 connection_out = packet_get_connection_out();
1450 max_fd = MAX(connection_in, connection_out);
1451 if (control_fd != -1)
1452 max_fd = MAX(max_fd, control_fd);
1455 /* enable nonblocking unless tty */
1456 if (!isatty(fileno(stdin)))
1457 set_nonblock(fileno(stdin));
1458 if (!isatty(fileno(stdout)))
1459 set_nonblock(fileno(stdout));
1460 if (!isatty(fileno(stderr)))
1461 set_nonblock(fileno(stderr));
1462 max_fd = MAX(max_fd, fileno(stdin));
1463 max_fd = MAX(max_fd, fileno(stdout));
1464 max_fd = MAX(max_fd, fileno(stderr));
1470 escape_char = escape_char_arg;
1472 /* Initialize buffers. */
1473 buffer_init(&stdin_buffer);
1474 buffer_init(&stdout_buffer);
1475 buffer_init(&stderr_buffer);
1477 client_init_dispatch();
1480 * Set signal handlers, (e.g. to restore non-blocking mode)
1481 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1483 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1484 signal(SIGHUP, signal_handler);
1485 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1486 signal(SIGINT, signal_handler);
1487 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1488 signal(SIGQUIT, signal_handler);
1489 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1490 signal(SIGTERM, signal_handler);
1491 signal(SIGWINCH, window_change_handler);
1497 session_ident = ssh2_chan_id;
1498 if (escape_char != SSH_ESCAPECHAR_NONE)
1499 channel_register_filter(session_ident,
1500 simple_escape_filter, NULL);
1501 if (session_ident != -1)
1502 channel_register_cleanup(session_ident,
1503 client_channel_closed, 0);
1505 /* Check if we should immediately send eof on stdin. */
1506 client_check_initial_eof_on_stdin();
1509 /* Main loop of the client for the interactive session mode. */
1510 while (!quit_pending) {
1512 /* Process buffered packets sent by the server. */
1513 client_process_buffered_input_packets();
1515 if (compat20 && session_closed && !channel_still_open())
1518 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1521 debug("rekeying in progress");
1524 * Make packets of buffered stdin data, and buffer
1525 * them for sending to the server.
1528 client_make_packets_from_stdin_data();
1531 * Make packets from buffered channel data, and
1532 * enqueue them for sending to the server.
1534 if (packet_not_very_much_data_to_write())
1535 channel_output_poll();
1538 * Check if the window size has changed, and buffer a
1539 * message about it to the server if so.
1541 client_check_window_change();
1547 * Wait until we have something to do (something becomes
1548 * available on one of the descriptors).
1551 client_wait_until_can_do_something(&readset, &writeset,
1552 &max_fd2, &nalloc, rekeying);
1557 /* Do channel operations unless rekeying in progress. */
1559 channel_after_select(readset, writeset);
1560 if (need_rekeying || packet_need_rekeying()) {
1561 debug("need rekeying");
1563 kex_send_kexinit(xxx_kex);
1568 /* Buffer input from the connection. */
1569 client_process_net_input(readset);
1571 /* Accept control connections. */
1572 client_process_control(readset);
1578 /* Buffer data from stdin */
1579 client_process_input(readset);
1581 * Process output to stdout and stderr. Output to
1582 * the connection is processed elsewhere (above).
1584 client_process_output(writeset);
1587 /* Send as much buffered packet data as possible to the sender. */
1588 if (FD_ISSET(connection_out, writeset))
1589 packet_write_poll();
1596 /* Terminate the session. */
1598 /* Stop watching for window change. */
1599 signal(SIGWINCH, SIG_DFL);
1606 /* restore blocking io */
1607 if (!isatty(fileno(stdin)))
1608 unset_nonblock(fileno(stdin));
1609 if (!isatty(fileno(stdout)))
1610 unset_nonblock(fileno(stdout));
1611 if (!isatty(fileno(stderr)))
1612 unset_nonblock(fileno(stderr));
1615 * If there was no shell or command requested, there will be no remote
1616 * exit status to be returned. In that case, clear error code if the
1617 * connection was deliberately terminated at this end.
1619 if (no_shell_flag && received_signal == SIGTERM) {
1620 received_signal = 0;
1624 if (received_signal)
1625 fatal("Killed by signal %d.", (int) received_signal);
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, "Connection to %.64s closed.\r\n", host);
1633 buffer_append(&stderr_buffer, buf, strlen(buf));
1636 /* Output any buffered data for stdout. */
1637 while (buffer_len(&stdout_buffer) > 0) {
1638 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1639 buffer_len(&stdout_buffer));
1641 error("Write failed flushing stdout buffer.");
1644 buffer_consume(&stdout_buffer, len);
1645 stdout_bytes += len;
1648 /* Output any buffered data for stderr. */
1649 while (buffer_len(&stderr_buffer) > 0) {
1650 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1651 buffer_len(&stderr_buffer));
1653 error("Write failed flushing stderr buffer.");
1656 buffer_consume(&stderr_buffer, len);
1657 stderr_bytes += len;
1660 /* Clear and free any buffers. */
1661 memset(buf, 0, sizeof(buf));
1662 buffer_free(&stdin_buffer);
1663 buffer_free(&stdout_buffer);
1664 buffer_free(&stderr_buffer);
1666 /* Report bytes transferred, and transfer rates. */
1667 total_time = get_current_time() - start_time;
1668 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
1669 stdin_bytes, stdout_bytes, stderr_bytes, total_time);
1671 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
1672 stdin_bytes / total_time, stdout_bytes / total_time,
1673 stderr_bytes / total_time);
1675 /* Return the exit status of the program. */
1676 debug("Exit status %d", exit_status);
1683 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1686 char *data = packet_get_string(&data_len);
1688 buffer_append(&stdout_buffer, data, data_len);
1689 memset(data, 0, data_len);
1693 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1696 char *data = packet_get_string(&data_len);
1698 buffer_append(&stderr_buffer, data, data_len);
1699 memset(data, 0, data_len);
1703 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1705 exit_status = packet_get_int();
1707 /* Acknowledge the exit. */
1708 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1711 * Must wait for packet to be sent since we are
1714 packet_write_wait();
1715 /* Flag that we want to exit. */
1719 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1722 int remote_id, sock;
1724 /* Read the remote channel number from the message. */
1725 remote_id = packet_get_int();
1729 * Get a connection to the local authentication agent (this may again
1732 sock = ssh_get_authentication_socket();
1735 * If we could not connect the agent, send an error message back to
1736 * the server. This should never happen unless the agent dies,
1737 * because authentication forwarding is only enabled if we have an
1741 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1742 -1, 0, 0, 0, "authentication agent connection", 1);
1743 c->remote_id = remote_id;
1747 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1748 packet_put_int(remote_id);
1750 /* Send a confirmation to the remote host. */
1751 debug("Forwarding authentication connection.");
1752 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1753 packet_put_int(remote_id);
1754 packet_put_int(c->self);
1760 client_request_forwarded_tcpip(const char *request_type, int rchan)
1763 char *listen_address, *originator_address;
1764 int listen_port, originator_port;
1767 /* Get rest of the packet */
1768 listen_address = packet_get_string(NULL);
1769 listen_port = packet_get_int();
1770 originator_address = packet_get_string(NULL);
1771 originator_port = packet_get_int();
1774 debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
1775 listen_address, listen_port, originator_address, originator_port);
1777 sock = channel_connect_by_listen_address(listen_port);
1779 xfree(originator_address);
1780 xfree(listen_address);
1783 c = channel_new("forwarded-tcpip",
1784 SSH_CHANNEL_CONNECTING, sock, sock, -1,
1785 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1786 originator_address, 1);
1787 xfree(originator_address);
1788 xfree(listen_address);
1793 client_request_x11(const char *request_type, int rchan)
1797 int originator_port;
1800 if (!options.forward_x11) {
1801 error("Warning: ssh server tried X11 forwarding.");
1802 error("Warning: this is probably a break-in attempt by a malicious server.");
1805 originator = packet_get_string(NULL);
1806 if (datafellows & SSH_BUG_X11FWD) {
1807 debug2("buggy server: x11 request w/o originator_port");
1808 originator_port = 0;
1810 originator_port = packet_get_int();
1813 /* XXX check permission */
1814 debug("client_request_x11: request from %s %d", originator,
1817 sock = x11_connect_display();
1820 c = channel_new("x11",
1821 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1822 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1828 client_request_agent(const char *request_type, int rchan)
1833 if (!options.forward_agent) {
1834 error("Warning: ssh server tried agent forwarding.");
1835 error("Warning: this is probably a break-in attempt by a malicious server.");
1838 sock = ssh_get_authentication_socket();
1841 c = channel_new("authentication agent connection",
1842 SSH_CHANNEL_OPEN, sock, sock, -1,
1843 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1844 "authentication agent connection", 1);
1850 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1855 if (tun_mode == SSH_TUNMODE_NO)
1859 error("Tunnel forwarding is not support for protocol 1");
1863 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1865 /* Open local tunnel device */
1866 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1867 error("Tunnel device open failed.");
1871 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1872 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1875 #if defined(SSH_TUN_FILTER)
1876 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1877 channel_register_filter(c->self, sys_tun_infilter,
1881 packet_start(SSH2_MSG_CHANNEL_OPEN);
1882 packet_put_cstring("tun@openssh.com");
1883 packet_put_int(c->self);
1884 packet_put_int(c->local_window_max);
1885 packet_put_int(c->local_maxpacket);
1886 packet_put_int(tun_mode);
1887 packet_put_int(remote_tun);
1893 /* XXXX move to generic input handler */
1895 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1900 u_int rmaxpack, rwindow, len;
1902 ctype = packet_get_string(&len);
1903 rchan = packet_get_int();
1904 rwindow = packet_get_int();
1905 rmaxpack = packet_get_int();
1907 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1908 ctype, rchan, rwindow, rmaxpack);
1910 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1911 c = client_request_forwarded_tcpip(ctype, rchan);
1912 } else if (strcmp(ctype, "x11") == 0) {
1913 c = client_request_x11(ctype, rchan);
1914 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1915 c = client_request_agent(ctype, rchan);
1917 /* XXX duplicate : */
1919 debug("confirm %s", ctype);
1920 c->remote_id = rchan;
1921 c->remote_window = rwindow;
1922 c->remote_maxpacket = rmaxpack;
1923 if (c->type != SSH_CHANNEL_CONNECTING) {
1924 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1925 packet_put_int(c->remote_id);
1926 packet_put_int(c->self);
1927 packet_put_int(c->local_window);
1928 packet_put_int(c->local_maxpacket);
1932 debug("failure %s", ctype);
1933 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1934 packet_put_int(rchan);
1935 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1936 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1937 packet_put_cstring("open failed");
1938 packet_put_cstring("");
1945 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1948 int exitval, id, reply, success = 0;
1951 id = packet_get_int();
1952 rtype = packet_get_string(NULL);
1953 reply = packet_get_char();
1955 debug("client_input_channel_req: channel %d rtype %s reply %d",
1959 error("client_input_channel_req: request for channel -1");
1960 } else if ((c = channel_lookup(id)) == NULL) {
1961 error("client_input_channel_req: channel %d: unknown channel", id);
1962 } else if (strcmp(rtype, "exit-status") == 0) {
1963 exitval = packet_get_int();
1964 if (id == session_ident) {
1966 exit_status = exitval;
1967 } else if (c->ctl_fd == -1) {
1968 error("client_input_channel_req: unexpected channel %d",
1971 atomicio(vwrite, c->ctl_fd, &exitval, sizeof(exitval));
1977 packet_start(success ?
1978 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1985 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1991 rtype = packet_get_string(NULL);
1992 want_reply = packet_get_char();
1993 debug("client_input_global_request: rtype %s want_reply %d",
1996 packet_start(success ?
1997 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1999 packet_write_wait();
2005 client_session2_setup(int id, int want_tty, int want_subsystem,
2006 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2011 debug2("%s: id %d", __func__, id);
2013 if ((c = channel_lookup(id)) == NULL)
2014 fatal("client_session2_setup: channel %d: unknown channel", id);
2020 /* Store window size in the packet. */
2021 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2022 memset(&ws, 0, sizeof(ws));
2024 channel_request_start(id, "pty-req", 1);
2025 client_expect_confirm(id, "PTY allocation", 0);
2026 packet_put_cstring(term != NULL ? term : "");
2027 packet_put_int((u_int)ws.ws_col);
2028 packet_put_int((u_int)ws.ws_row);
2029 packet_put_int((u_int)ws.ws_xpixel);
2030 packet_put_int((u_int)ws.ws_ypixel);
2031 tio = get_saved_tio();
2032 tty_make_modes(-1, tiop != NULL ? tiop : &tio);
2034 /* XXX wait for reply */
2038 /* Transfer any environment variables from client to server */
2039 if (options.num_send_env != 0 && env != NULL) {
2043 debug("Sending environment.");
2044 for (i = 0; env[i] != NULL; i++) {
2046 name = xstrdup(env[i]);
2047 if ((val = strchr(name, '=')) == NULL) {
2054 for (j = 0; j < options.num_send_env; j++) {
2055 if (match_pattern(name, options.send_env[j])) {
2061 debug3("Ignored env %s", name);
2066 debug("Sending env %s = %s", name, val);
2067 channel_request_start(id, "env", 0);
2068 packet_put_cstring(name);
2069 packet_put_cstring(val);
2075 len = buffer_len(cmd);
2079 if (want_subsystem) {
2080 debug("Sending subsystem: %.*s",
2081 len, (u_char*)buffer_ptr(cmd));
2082 channel_request_start(id, "subsystem", 1);
2083 client_expect_confirm(id, "subsystem", 1);
2085 debug("Sending command: %.*s",
2086 len, (u_char*)buffer_ptr(cmd));
2087 channel_request_start(id, "exec", 1);
2088 client_expect_confirm(id, "exec", 1);
2090 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2093 channel_request_start(id, "shell", 1);
2094 client_expect_confirm(id, "shell", 1);
2100 client_init_dispatch_20(void)
2102 dispatch_init(&dispatch_protocol_error);
2104 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2105 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2106 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2107 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2108 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2109 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2110 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2111 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2112 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2113 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2114 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2115 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2118 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2120 /* global request reply messages */
2121 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2122 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2125 client_init_dispatch_13(void)
2127 dispatch_init(NULL);
2128 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2129 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2130 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2131 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2132 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2133 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2134 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2135 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2136 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2138 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2139 &client_input_agent_open : &deny_input_open);
2140 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2141 &x11_input_open : &deny_input_open);
2144 client_init_dispatch_15(void)
2146 client_init_dispatch_13();
2147 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2148 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2151 client_init_dispatch(void)
2154 client_init_dispatch_20();
2156 client_init_dispatch_13();
2158 client_init_dispatch_15();
2161 /* client specific fatal cleanup */
2166 leave_non_blocking();
2167 if (options.control_path != NULL && control_fd != -1)
2168 unlink(options.control_path);