1 /* $OpenBSD: clientloop.c,v 1.171 2006/07/25 02:59:21 stevesk 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 #ifdef HAVE_SYS_STAT_H
67 # include <sys/stat.h>
69 #ifdef HAVE_SYS_TIME_H
70 # include <sys/time.h>
72 #include <sys/socket.h>
99 #include "clientloop.h"
100 #include "sshconnect.h"
102 #include "atomicio.h"
105 #include "monitor_fdpass.h"
110 extern Options options;
112 /* Flag indicating that stdin should be redirected from /dev/null. */
113 extern int stdin_null_flag;
115 /* Flag indicating that no shell has been requested */
116 extern int no_shell_flag;
119 extern int control_fd;
122 * Name of the host we are connecting to. This is the name given on the
123 * command line, or the HostName specified for the user-supplied name in a
124 * configuration file.
129 * Flag to indicate that we have received a window change signal which has
130 * not yet been processed. This will cause a message indicating the new
131 * window size to be sent to the server a little later. This is volatile
132 * because this is updated in a signal handler.
134 static volatile sig_atomic_t received_window_change_signal = 0;
135 static volatile sig_atomic_t received_signal = 0;
137 /* Flag indicating whether the user's terminal is in non-blocking mode. */
138 static int in_non_blocking_mode = 0;
140 /* Common data for the client loop code. */
141 static volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
142 static int escape_char; /* Escape character. */
143 static int escape_pending; /* Last character was the escape character */
144 static int last_was_cr; /* Last character was a newline. */
145 static int exit_status; /* Used to store the exit status of the command. */
146 static int stdin_eof; /* EOF has been encountered on standard error. */
147 static Buffer stdin_buffer; /* Buffer for stdin data. */
148 static Buffer stdout_buffer; /* Buffer for stdout data. */
149 static Buffer stderr_buffer; /* Buffer for stderr data. */
150 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
151 static u_int buffer_high;/* Soft max buffer size. */
152 static int connection_in; /* Connection to server (input). */
153 static int connection_out; /* Connection to server (output). */
154 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
155 static int session_closed = 0; /* In SSH2: login session closed. */
156 static int server_alive_timeouts = 0;
158 static void client_init_dispatch(void);
159 int session_ident = -1;
175 void ssh_process_session2_setup(int, int, int, Buffer *);
177 /* Restores stdin to blocking mode. */
180 leave_non_blocking(void)
182 if (in_non_blocking_mode) {
183 unset_nonblock(fileno(stdin));
184 in_non_blocking_mode = 0;
188 /* Puts stdin terminal in non-blocking mode. */
191 enter_non_blocking(void)
193 in_non_blocking_mode = 1;
194 set_nonblock(fileno(stdin));
198 * Signal handler for the window change signal (SIGWINCH). This just sets a
199 * flag indicating that the window has changed.
203 window_change_handler(int sig)
205 received_window_change_signal = 1;
206 signal(SIGWINCH, window_change_handler);
210 * Signal handler for signals that cause the program to terminate. These
211 * signals must be trapped to restore terminal modes.
215 signal_handler(int sig)
217 received_signal = sig;
222 * Returns current time in seconds from Jan 1, 1970 with the maximum
223 * available resolution.
227 get_current_time(void)
230 gettimeofday(&tv, NULL);
231 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
234 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
236 client_x11_get_proto(const char *display, const char *xauth_path,
237 u_int trusted, char **_proto, char **_data)
242 static char proto[512], data[512];
244 int got_data = 0, generated = 0, do_unlink = 0, i;
245 char *xauthdir, *xauthfile;
248 xauthdir = xauthfile = NULL;
251 proto[0] = data[0] = '\0';
253 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
254 debug("No xauth program.");
256 if (display == NULL) {
257 debug("x11_get_proto: DISPLAY not set");
261 * Handle FamilyLocal case where $DISPLAY does
262 * not match an authorization entry. For this we
263 * just try "xauth list unix:displaynum.screennum".
264 * XXX: "localhost" match to determine FamilyLocal
267 if (strncmp(display, "localhost:", 10) == 0) {
268 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
273 xauthdir = xmalloc(MAXPATHLEN);
274 xauthfile = xmalloc(MAXPATHLEN);
275 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
276 if (mkdtemp(xauthdir) != NULL) {
278 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
280 snprintf(cmd, sizeof(cmd),
281 "%s -f %s generate %s " SSH_X11_PROTO
282 " untrusted timeout 1200 2>" _PATH_DEVNULL,
283 xauth_path, xauthfile, display);
284 debug2("x11_get_proto: %s", cmd);
285 if (system(cmd) == 0)
289 snprintf(cmd, sizeof(cmd),
290 "%s %s%s list %s 2>" _PATH_DEVNULL,
292 generated ? "-f " : "" ,
293 generated ? xauthfile : "",
295 debug2("x11_get_proto: %s", cmd);
297 if (f && fgets(line, sizeof(line), f) &&
298 sscanf(line, "%*s %511s %511s", proto, data) == 2)
314 * If we didn't get authentication data, just make up some
315 * data. The forwarding code will check the validity of the
316 * response anyway, and substitute this data. The X11
317 * server, however, will ignore this fake data and use
318 * whatever authentication mechanisms it was using otherwise
319 * for the local connection.
324 logit("Warning: No xauth data; "
325 "using fake authentication data for X11 forwarding.");
326 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
327 for (i = 0; i < 16; i++) {
330 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
338 * This is called when the interactive is entered. This checks if there is
339 * an EOF coming on stdin. We must check this explicitly, as select() does
340 * not appear to wake up when redirecting from /dev/null.
344 client_check_initial_eof_on_stdin(void)
350 * If standard input is to be "redirected from /dev/null", we simply
351 * mark that we have seen an EOF and send an EOF message to the
352 * server. Otherwise, we try to read a single character; it appears
353 * that for some files, such /dev/null, select() never wakes up for
354 * read for this descriptor, which means that we never get EOF. This
355 * way we will get the EOF if stdin comes from /dev/null or similar.
357 if (stdin_null_flag) {
358 /* Fake EOF on stdin. */
359 debug("Sending eof.");
361 packet_start(SSH_CMSG_EOF);
364 enter_non_blocking();
366 /* Check for immediate EOF on stdin. */
367 len = read(fileno(stdin), buf, 1);
369 /* EOF. Record that we have seen it and send EOF to server. */
370 debug("Sending eof.");
372 packet_start(SSH_CMSG_EOF);
374 } else if (len > 0) {
376 * Got data. We must store the data in the buffer,
377 * and also process it as an escape character if
380 if ((u_char) buf[0] == escape_char)
383 buffer_append(&stdin_buffer, buf, 1);
385 leave_non_blocking();
391 * Make packets from buffered stdin data, and buffer them for sending to the
396 client_make_packets_from_stdin_data(void)
400 /* Send buffered stdin data to the server. */
401 while (buffer_len(&stdin_buffer) > 0 &&
402 packet_not_very_much_data_to_write()) {
403 len = buffer_len(&stdin_buffer);
404 /* Keep the packets at reasonable size. */
405 if (len > packet_get_maxsize())
406 len = packet_get_maxsize();
407 packet_start(SSH_CMSG_STDIN_DATA);
408 packet_put_string(buffer_ptr(&stdin_buffer), len);
410 buffer_consume(&stdin_buffer, len);
412 /* If we have a pending EOF, send it now. */
413 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
414 packet_start(SSH_CMSG_EOF);
421 * Checks if the client window has changed, and sends a packet about it to
422 * the server if so. The actual change is detected elsewhere (by a software
423 * interrupt on Unix); this just checks the flag and sends a message if
428 client_check_window_change(void)
432 if (! received_window_change_signal)
435 received_window_change_signal = 0;
437 debug2("client_check_window_change: changed");
440 channel_send_window_changes();
442 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
444 packet_start(SSH_CMSG_WINDOW_SIZE);
445 packet_put_int((u_int)ws.ws_row);
446 packet_put_int((u_int)ws.ws_col);
447 packet_put_int((u_int)ws.ws_xpixel);
448 packet_put_int((u_int)ws.ws_ypixel);
454 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
456 server_alive_timeouts = 0;
457 client_global_request_reply_fwd(type, seq, ctxt);
461 server_alive_check(void)
463 if (++server_alive_timeouts > options.server_alive_count_max)
464 packet_disconnect("Timeout, server not responding.");
465 packet_start(SSH2_MSG_GLOBAL_REQUEST);
466 packet_put_cstring("keepalive@openssh.com");
467 packet_put_char(1); /* boolean: want reply */
472 * Waits until the client can do something (some data becomes available on
473 * one of the file descriptors).
476 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
477 int *maxfdp, u_int *nallocp, int rekeying)
479 struct timeval tv, *tvp;
482 /* Add any selections by the channel mechanism. */
483 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
486 /* Read from the connection, unless our buffers are full. */
487 if (buffer_len(&stdout_buffer) < buffer_high &&
488 buffer_len(&stderr_buffer) < buffer_high &&
489 channel_not_very_much_buffered_data())
490 FD_SET(connection_in, *readsetp);
492 * Read from stdin, unless we have seen EOF or have very much
493 * buffered data to send to the server.
495 if (!stdin_eof && packet_not_very_much_data_to_write())
496 FD_SET(fileno(stdin), *readsetp);
498 /* Select stdout/stderr if have data in buffer. */
499 if (buffer_len(&stdout_buffer) > 0)
500 FD_SET(fileno(stdout), *writesetp);
501 if (buffer_len(&stderr_buffer) > 0)
502 FD_SET(fileno(stderr), *writesetp);
504 /* channel_prepare_select could have closed the last channel */
505 if (session_closed && !channel_still_open() &&
506 !packet_have_data_to_write()) {
507 /* clear mask since we did not call select() */
508 memset(*readsetp, 0, *nallocp);
509 memset(*writesetp, 0, *nallocp);
512 FD_SET(connection_in, *readsetp);
516 /* Select server connection if have data to write to the server. */
517 if (packet_have_data_to_write())
518 FD_SET(connection_out, *writesetp);
520 if (control_fd != -1)
521 FD_SET(control_fd, *readsetp);
524 * Wait for something to happen. This will suspend the process until
525 * some selected descriptor can be read, written, or has some other
529 if (options.server_alive_interval == 0 || !compat20)
532 tv.tv_sec = options.server_alive_interval;
536 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
541 * We have to clear the select masks, because we return.
542 * We have to return, because the mainloop checks for the flags
543 * set by the signal handlers.
545 memset(*readsetp, 0, *nallocp);
546 memset(*writesetp, 0, *nallocp);
550 /* Note: we might still have data in the buffers. */
551 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
552 buffer_append(&stderr_buffer, buf, strlen(buf));
555 server_alive_check();
559 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
561 /* Flush stdout and stderr buffers. */
562 if (buffer_len(bout) > 0)
563 atomicio(vwrite, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
564 if (buffer_len(berr) > 0)
565 atomicio(vwrite, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
570 * Free (and clear) the buffer to reduce the amount of data that gets
577 /* Send the suspend signal to the program itself. */
578 kill(getpid(), SIGTSTP);
580 /* Reset window sizes in case they have changed */
581 received_window_change_signal = 1;
583 /* OK, we have been continued by the user. Reinitialize buffers. */
592 client_process_net_input(fd_set *readset)
598 * Read input from the server, and add any such data to the buffer of
599 * the packet subsystem.
601 if (FD_ISSET(connection_in, readset)) {
602 /* Read as much as possible. */
603 len = read(connection_in, buf, sizeof(buf));
605 /* Received EOF. The remote host has closed the connection. */
606 snprintf(buf, sizeof buf, "Connection to %.300s closed by remote host.\r\n",
608 buffer_append(&stderr_buffer, buf, strlen(buf));
613 * There is a kernel bug on Solaris that causes select to
614 * sometimes wake up even though there is no data available.
616 if (len < 0 && (errno == EAGAIN || errno == EINTR))
620 /* An error has encountered. Perhaps there is a network problem. */
621 snprintf(buf, sizeof buf, "Read from remote host %.300s: %.100s\r\n",
622 host, strerror(errno));
623 buffer_append(&stderr_buffer, buf, strlen(buf));
627 packet_process_incoming(buf, len);
632 client_subsystem_reply(int type, u_int32_t seq, void *ctxt)
637 id = packet_get_int();
640 if ((c = channel_lookup(id)) == NULL) {
641 error("%s: no channel for id %d", __func__, id);
645 if (type == SSH2_MSG_CHANNEL_SUCCESS)
646 debug2("Request suceeded on channel %d", id);
647 else if (type == SSH2_MSG_CHANNEL_FAILURE) {
648 error("Request failed on channel %d", id);
654 client_extra_session2_setup(int id, void *arg)
656 struct confirm_ctx *cctx = arg;
662 fatal("%s: cctx == NULL", __func__);
663 if ((c = channel_lookup(id)) == NULL)
664 fatal("%s: no channel for id %d", __func__, id);
666 display = getenv("DISPLAY");
667 if (cctx->want_x_fwd && options.forward_x11 && display != NULL) {
669 /* Get reasonable local authentication information. */
670 client_x11_get_proto(display, options.xauth_location,
671 options.forward_x11_trusted, &proto, &data);
672 /* Request forwarding with authentication spoofing. */
673 debug("Requesting X11 forwarding with authentication spoofing.");
674 x11_request_forwarding_with_spoofing(id, display, proto, data);
675 /* XXX wait for reply */
678 if (cctx->want_agent_fwd && options.forward_agent) {
679 debug("Requesting authentication agent forwarding.");
680 channel_request_start(id, "auth-agent-req@openssh.com", 0);
684 client_session2_setup(id, cctx->want_tty, cctx->want_subsys,
685 cctx->term, &cctx->tio, c->rfd, &cctx->cmd, cctx->env,
686 client_subsystem_reply);
688 c->confirm_ctx = NULL;
689 buffer_free(&cctx->cmd);
691 if (cctx->env != NULL) {
692 for (i = 0; cctx->env[i] != NULL; i++)
700 client_process_control(fd_set *readset)
704 int client_fd, new_fd[3], ver, allowed;
706 struct sockaddr_storage addr;
707 struct confirm_ctx *cctx;
709 u_int i, len, env_len, command, flags;
714 * Accept connection on control socket
716 if (control_fd == -1 || !FD_ISSET(control_fd, readset))
719 memset(&addr, 0, sizeof(addr));
720 addrlen = sizeof(addr);
721 if ((client_fd = accept(control_fd,
722 (struct sockaddr*)&addr, &addrlen)) == -1) {
723 error("%s accept: %s", __func__, strerror(errno));
727 if (getpeereid(client_fd, &euid, &egid) < 0) {
728 error("%s getpeereid failed: %s", __func__, strerror(errno));
732 if ((euid != 0) && (getuid() != euid)) {
733 error("control mode uid mismatch: peer euid %u != uid %u",
734 (u_int) euid, (u_int) getuid());
739 unset_nonblock(client_fd);
743 if (ssh_msg_recv(client_fd, &m) == -1) {
744 error("%s: client msg_recv failed", __func__);
749 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
750 error("%s: wrong client version %d", __func__, ver);
757 command = buffer_get_int(&m);
758 flags = buffer_get_int(&m);
763 case SSHMUX_COMMAND_OPEN:
764 if (options.control_master == SSHCTL_MASTER_ASK ||
765 options.control_master == SSHCTL_MASTER_AUTO_ASK)
766 allowed = ask_permission("Allow shared connection "
770 case SSHMUX_COMMAND_TERMINATE:
771 if (options.control_master == SSHCTL_MASTER_ASK ||
772 options.control_master == SSHCTL_MASTER_AUTO_ASK)
773 allowed = ask_permission("Terminate shared connection "
778 case SSHMUX_COMMAND_ALIVE_CHECK:
779 /* Reply for SSHMUX_COMMAND_TERMINATE and ALIVE_CHECK */
781 buffer_put_int(&m, allowed);
782 buffer_put_int(&m, getpid());
783 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
784 error("%s: client msg_send failed", __func__);
793 error("Unsupported command %d", command);
799 /* Reply for SSHMUX_COMMAND_OPEN */
801 buffer_put_int(&m, allowed);
802 buffer_put_int(&m, getpid());
803 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
804 error("%s: client msg_send failed", __func__);
811 error("Refused control connection");
818 if (ssh_msg_recv(client_fd, &m) == -1) {
819 error("%s: client msg_recv failed", __func__);
824 if ((ver = buffer_get_char(&m)) != SSHMUX_VER) {
825 error("%s: wrong client version %d", __func__, ver);
831 cctx = xcalloc(1, sizeof(*cctx));
832 cctx->want_tty = (flags & SSHMUX_FLAG_TTY) != 0;
833 cctx->want_subsys = (flags & SSHMUX_FLAG_SUBSYS) != 0;
834 cctx->want_x_fwd = (flags & SSHMUX_FLAG_X11_FWD) != 0;
835 cctx->want_agent_fwd = (flags & SSHMUX_FLAG_AGENT_FWD) != 0;
836 cctx->term = buffer_get_string(&m, &len);
838 cmd = buffer_get_string(&m, &len);
839 buffer_init(&cctx->cmd);
840 buffer_append(&cctx->cmd, cmd, strlen(cmd));
842 env_len = buffer_get_int(&m);
843 env_len = MIN(env_len, 4096);
844 debug3("%s: receiving %d env vars", __func__, env_len);
846 cctx->env = xcalloc(env_len + 1, sizeof(*cctx->env));
847 for (i = 0; i < env_len; i++)
848 cctx->env[i] = buffer_get_string(&m, &len);
852 debug2("%s: accepted tty %d, subsys %d, cmd %s", __func__,
853 cctx->want_tty, cctx->want_subsys, cmd);
856 /* Gather fds from client */
857 new_fd[0] = mm_receive_fd(client_fd);
858 new_fd[1] = mm_receive_fd(client_fd);
859 new_fd[2] = mm_receive_fd(client_fd);
861 debug2("%s: got fds stdin %d, stdout %d, stderr %d", __func__,
862 new_fd[0], new_fd[1], new_fd[2]);
864 /* Try to pick up ttymodes from client before it goes raw */
865 if (cctx->want_tty && tcgetattr(new_fd[0], &cctx->tio) == -1)
866 error("%s: tcgetattr: %s", __func__, strerror(errno));
868 /* This roundtrip is just for synchronisation of ttymodes */
870 if (ssh_msg_send(client_fd, SSHMUX_VER, &m) == -1) {
871 error("%s: client msg_send failed", __func__);
879 for (i = 0; i < env_len; i++)
887 /* enable nonblocking unless tty */
888 if (!isatty(new_fd[0]))
889 set_nonblock(new_fd[0]);
890 if (!isatty(new_fd[1]))
891 set_nonblock(new_fd[1]);
892 if (!isatty(new_fd[2]))
893 set_nonblock(new_fd[2]);
895 set_nonblock(client_fd);
897 c = channel_new("session", SSH_CHANNEL_OPENING,
898 new_fd[0], new_fd[1], new_fd[2],
899 CHAN_SES_WINDOW_DEFAULT, CHAN_SES_PACKET_DEFAULT,
900 CHAN_EXTENDED_WRITE, "client-session", /*nonblock*/0);
903 c->ctl_fd = client_fd;
905 debug3("%s: channel_new: %d", __func__, c->self);
907 channel_send_open(c->self);
908 channel_register_confirm(c->self, client_extra_session2_setup, cctx);
912 process_cmdline(void)
914 void (*handler)(int);
915 char *s, *cmd, *cancel_host;
922 handler = signal(SIGINT, SIG_IGN);
923 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
926 while (*s && isspace(*s))
929 s++; /* Skip cmdline '-', if any */
933 if (*s == 'h' || *s == 'H' || *s == '?') {
935 logit(" -L[bind_address:]port:host:hostport "
936 "Request local forward");
937 logit(" -R[bind_address:]port:host:hostport "
938 "Request remote forward");
939 logit(" -KR[bind_address:]port "
940 "Cancel remote forward");
941 if (!options.permit_local_command)
944 "Execute local command");
948 if (*s == '!' && options.permit_local_command) {
958 if (*s != 'L' && *s != 'R') {
959 logit("Invalid command.");
964 if (local && delete) {
965 logit("Not supported.");
968 if ((!local || delete) && !compat20) {
969 logit("Not supported for SSH protocol version 1.");
974 while (*s && isspace(*s))
979 cancel_host = hpdelim(&s); /* may be NULL */
981 cancel_port = a2port(s);
982 cancel_host = cleanhostname(cancel_host);
984 cancel_port = a2port(cancel_host);
987 if (cancel_port == 0) {
988 logit("Bad forwarding close port");
991 channel_request_rforward_cancel(cancel_host, cancel_port);
993 if (!parse_forward(&fwd, s)) {
994 logit("Bad forwarding specification.");
998 if (channel_setup_local_fwd_listener(fwd.listen_host,
999 fwd.listen_port, fwd.connect_host,
1000 fwd.connect_port, options.gateway_ports) < 0) {
1001 logit("Port forwarding failed.");
1005 if (channel_request_remote_forwarding(fwd.listen_host,
1006 fwd.listen_port, fwd.connect_host,
1007 fwd.connect_port) < 0) {
1008 logit("Port forwarding failed.");
1013 logit("Forwarding port.");
1017 signal(SIGINT, handler);
1023 /* process the characters one by one */
1025 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
1037 for (i = 0; i < (u_int)len; i++) {
1038 /* Get one character at a time. */
1041 if (escape_pending) {
1042 /* We have previously seen an escape character. */
1043 /* Clear the flag now. */
1046 /* Process the escaped character. */
1049 /* Terminate the connection. */
1050 snprintf(string, sizeof string, "%c.\r\n", escape_char);
1051 buffer_append(berr, string, strlen(string));
1057 /* Suspend the program. */
1058 /* Print a message to that effect to the user. */
1059 snprintf(string, sizeof string, "%c^Z [suspend ssh]\r\n", escape_char);
1060 buffer_append(berr, string, strlen(string));
1062 /* Restore terminal modes and suspend. */
1063 client_suspend_self(bin, bout, berr);
1065 /* We have been continued. */
1070 snprintf(string, sizeof string,
1071 "%cB\r\n", escape_char);
1072 buffer_append(berr, string,
1074 channel_request_start(session_ident,
1076 packet_put_int(1000);
1083 if (datafellows & SSH_BUG_NOREKEY)
1084 logit("Server does not support re-keying");
1092 * Detach the program (continue to serve connections,
1093 * but put in background and no more new connections).
1095 /* Restore tty modes. */
1098 /* Stop listening for new connections. */
1099 channel_stop_listening();
1101 snprintf(string, sizeof string,
1102 "%c& [backgrounded]\n", escape_char);
1103 buffer_append(berr, string, strlen(string));
1105 /* Fork into background. */
1108 error("fork: %.100s", strerror(errno));
1111 if (pid != 0) { /* This is the parent. */
1112 /* The parent just exits. */
1115 /* The child continues serving connections. */
1117 buffer_append(bin, "\004", 1);
1118 /* fake EOF on stdin */
1120 } else if (!stdin_eof) {
1122 * Sending SSH_CMSG_EOF alone does not always appear
1123 * to be enough. So we try to send an EOF character
1126 packet_start(SSH_CMSG_STDIN_DATA);
1127 packet_put_string("\004", 1);
1131 if (buffer_len(bin) == 0) {
1132 packet_start(SSH_CMSG_EOF);
1139 snprintf(string, sizeof string,
1141 Supported escape sequences:\r\n\
1142 %c. - terminate connection\r\n\
1143 %cB - send a BREAK to the remote system\r\n\
1144 %cC - open a command line\r\n\
1145 %cR - Request rekey (SSH protocol 2 only)\r\n\
1146 %c^Z - suspend ssh\r\n\
1147 %c# - list forwarded connections\r\n\
1148 %c& - background ssh (when waiting for connections to terminate)\r\n\
1149 %c? - this message\r\n\
1150 %c%c - send the escape character by typing it twice\r\n\
1151 (Note that escapes are only recognized immediately after newline.)\r\n",
1152 escape_char, escape_char, escape_char, escape_char,
1153 escape_char, escape_char, escape_char, escape_char,
1154 escape_char, escape_char, escape_char);
1155 buffer_append(berr, string, strlen(string));
1159 snprintf(string, sizeof string, "%c#\r\n", escape_char);
1160 buffer_append(berr, string, strlen(string));
1161 s = channel_open_message();
1162 buffer_append(berr, s, strlen(s));
1171 if (ch != escape_char) {
1172 buffer_put_char(bin, escape_char);
1175 /* Escaped characters fall through here */
1180 * The previous character was not an escape char. Check if this
1183 if (last_was_cr && ch == escape_char) {
1184 /* It is. Set the flag and continue to next character. */
1191 * Normal character. Record whether it was a newline,
1192 * and append it to the buffer.
1194 last_was_cr = (ch == '\r' || ch == '\n');
1195 buffer_put_char(bin, ch);
1202 client_process_input(fd_set *readset)
1207 /* Read input from stdin. */
1208 if (FD_ISSET(fileno(stdin), readset)) {
1209 /* Read as much as possible. */
1210 len = read(fileno(stdin), buf, sizeof(buf));
1211 if (len < 0 && (errno == EAGAIN || errno == EINTR))
1212 return; /* we'll try again later */
1215 * Received EOF or error. They are treated
1216 * similarly, except that an error message is printed
1217 * if it was an error condition.
1220 snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
1221 buffer_append(&stderr_buffer, buf, strlen(buf));
1223 /* Mark that we have seen EOF. */
1226 * Send an EOF message to the server unless there is
1227 * data in the buffer. If there is data in the
1228 * buffer, no message will be sent now. Code
1229 * elsewhere will send the EOF when the buffer
1230 * becomes empty if stdin_eof is set.
1232 if (buffer_len(&stdin_buffer) == 0) {
1233 packet_start(SSH_CMSG_EOF);
1236 } else if (escape_char == SSH_ESCAPECHAR_NONE) {
1238 * Normal successful read, and no escape character.
1239 * Just append the data to buffer.
1241 buffer_append(&stdin_buffer, buf, len);
1244 * Normal, successful read. But we have an escape character
1245 * and have to process the characters one by one.
1247 if (process_escapes(&stdin_buffer, &stdout_buffer,
1248 &stderr_buffer, buf, len) == -1)
1255 client_process_output(fd_set *writeset)
1260 /* Write buffered output to stdout. */
1261 if (FD_ISSET(fileno(stdout), writeset)) {
1262 /* Write as much data as possible. */
1263 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1264 buffer_len(&stdout_buffer));
1266 if (errno == EINTR || errno == EAGAIN)
1270 * An error or EOF was encountered. Put an
1271 * error message to stderr buffer.
1273 snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
1274 buffer_append(&stderr_buffer, buf, strlen(buf));
1279 /* Consume printed data from the buffer. */
1280 buffer_consume(&stdout_buffer, len);
1281 stdout_bytes += len;
1283 /* Write buffered output to stderr. */
1284 if (FD_ISSET(fileno(stderr), writeset)) {
1285 /* Write as much data as possible. */
1286 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1287 buffer_len(&stderr_buffer));
1289 if (errno == EINTR || errno == EAGAIN)
1292 /* EOF or error, but can't even print error message. */
1297 /* Consume printed characters from the buffer. */
1298 buffer_consume(&stderr_buffer, len);
1299 stderr_bytes += len;
1304 * Get packets from the connection input buffer, and process them as long as
1305 * there are packets available.
1307 * Any unknown packets received during the actual
1308 * session cause the session to terminate. This is
1309 * intended to make debugging easier since no
1310 * confirmations are sent. Any compatible protocol
1311 * extensions must be negotiated during the
1312 * preparatory phase.
1316 client_process_buffered_input_packets(void)
1318 dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
1321 /* scan buf[] for '~' before sending data to the peer */
1324 simple_escape_filter(Channel *c, char *buf, int len)
1326 /* XXX we assume c->extended is writeable */
1327 return process_escapes(&c->input, &c->output, &c->extended, buf, len);
1331 client_channel_closed(int id, void *arg)
1333 channel_cancel_cleanup(id);
1339 * Implements the interactive session with the server. This is called after
1340 * the user has been authenticated, and a command has been started on the
1341 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1342 * used as an escape character for terminating or suspending the session.
1346 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1348 fd_set *readset = NULL, *writeset = NULL;
1349 double start_time, total_time;
1350 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1354 debug("Entering interactive session.");
1356 start_time = get_current_time();
1358 /* Initialize variables. */
1363 buffer_high = 64 * 1024;
1364 connection_in = packet_get_connection_in();
1365 connection_out = packet_get_connection_out();
1366 max_fd = MAX(connection_in, connection_out);
1367 if (control_fd != -1)
1368 max_fd = MAX(max_fd, control_fd);
1371 /* enable nonblocking unless tty */
1372 if (!isatty(fileno(stdin)))
1373 set_nonblock(fileno(stdin));
1374 if (!isatty(fileno(stdout)))
1375 set_nonblock(fileno(stdout));
1376 if (!isatty(fileno(stderr)))
1377 set_nonblock(fileno(stderr));
1378 max_fd = MAX(max_fd, fileno(stdin));
1379 max_fd = MAX(max_fd, fileno(stdout));
1380 max_fd = MAX(max_fd, fileno(stderr));
1386 escape_char = escape_char_arg;
1388 /* Initialize buffers. */
1389 buffer_init(&stdin_buffer);
1390 buffer_init(&stdout_buffer);
1391 buffer_init(&stderr_buffer);
1393 client_init_dispatch();
1396 * Set signal handlers, (e.g. to restore non-blocking mode)
1397 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1399 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1400 signal(SIGHUP, signal_handler);
1401 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1402 signal(SIGINT, signal_handler);
1403 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1404 signal(SIGQUIT, signal_handler);
1405 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1406 signal(SIGTERM, signal_handler);
1407 signal(SIGWINCH, window_change_handler);
1413 session_ident = ssh2_chan_id;
1414 if (escape_char != SSH_ESCAPECHAR_NONE)
1415 channel_register_filter(session_ident,
1416 simple_escape_filter, NULL);
1417 if (session_ident != -1)
1418 channel_register_cleanup(session_ident,
1419 client_channel_closed, 0);
1421 /* Check if we should immediately send eof on stdin. */
1422 client_check_initial_eof_on_stdin();
1425 /* Main loop of the client for the interactive session mode. */
1426 while (!quit_pending) {
1428 /* Process buffered packets sent by the server. */
1429 client_process_buffered_input_packets();
1431 if (compat20 && session_closed && !channel_still_open())
1434 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1437 debug("rekeying in progress");
1440 * Make packets of buffered stdin data, and buffer
1441 * them for sending to the server.
1444 client_make_packets_from_stdin_data();
1447 * Make packets from buffered channel data, and
1448 * enqueue them for sending to the server.
1450 if (packet_not_very_much_data_to_write())
1451 channel_output_poll();
1454 * Check if the window size has changed, and buffer a
1455 * message about it to the server if so.
1457 client_check_window_change();
1463 * Wait until we have something to do (something becomes
1464 * available on one of the descriptors).
1467 client_wait_until_can_do_something(&readset, &writeset,
1468 &max_fd2, &nalloc, rekeying);
1473 /* Do channel operations unless rekeying in progress. */
1475 channel_after_select(readset, writeset);
1476 if (need_rekeying || packet_need_rekeying()) {
1477 debug("need rekeying");
1479 kex_send_kexinit(xxx_kex);
1484 /* Buffer input from the connection. */
1485 client_process_net_input(readset);
1487 /* Accept control connections. */
1488 client_process_control(readset);
1494 /* Buffer data from stdin */
1495 client_process_input(readset);
1497 * Process output to stdout and stderr. Output to
1498 * the connection is processed elsewhere (above).
1500 client_process_output(writeset);
1503 /* Send as much buffered packet data as possible to the sender. */
1504 if (FD_ISSET(connection_out, writeset))
1505 packet_write_poll();
1512 /* Terminate the session. */
1514 /* Stop watching for window change. */
1515 signal(SIGWINCH, SIG_DFL);
1522 /* restore blocking io */
1523 if (!isatty(fileno(stdin)))
1524 unset_nonblock(fileno(stdin));
1525 if (!isatty(fileno(stdout)))
1526 unset_nonblock(fileno(stdout));
1527 if (!isatty(fileno(stderr)))
1528 unset_nonblock(fileno(stderr));
1531 * If there was no shell or command requested, there will be no remote
1532 * exit status to be returned. In that case, clear error code if the
1533 * connection was deliberately terminated at this end.
1535 if (no_shell_flag && received_signal == SIGTERM) {
1536 received_signal = 0;
1540 if (received_signal)
1541 fatal("Killed by signal %d.", (int) received_signal);
1544 * In interactive mode (with pseudo tty) display a message indicating
1545 * that the connection has been closed.
1547 if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1548 snprintf(buf, sizeof buf, "Connection to %.64s closed.\r\n", host);
1549 buffer_append(&stderr_buffer, buf, strlen(buf));
1552 /* Output any buffered data for stdout. */
1553 while (buffer_len(&stdout_buffer) > 0) {
1554 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1555 buffer_len(&stdout_buffer));
1557 error("Write failed flushing stdout buffer.");
1560 buffer_consume(&stdout_buffer, len);
1561 stdout_bytes += len;
1564 /* Output any buffered data for stderr. */
1565 while (buffer_len(&stderr_buffer) > 0) {
1566 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1567 buffer_len(&stderr_buffer));
1569 error("Write failed flushing stderr buffer.");
1572 buffer_consume(&stderr_buffer, len);
1573 stderr_bytes += len;
1576 /* Clear and free any buffers. */
1577 memset(buf, 0, sizeof(buf));
1578 buffer_free(&stdin_buffer);
1579 buffer_free(&stdout_buffer);
1580 buffer_free(&stderr_buffer);
1582 /* Report bytes transferred, and transfer rates. */
1583 total_time = get_current_time() - start_time;
1584 debug("Transferred: stdin %lu, stdout %lu, stderr %lu bytes in %.1f seconds",
1585 stdin_bytes, stdout_bytes, stderr_bytes, total_time);
1587 debug("Bytes per second: stdin %.1f, stdout %.1f, stderr %.1f",
1588 stdin_bytes / total_time, stdout_bytes / total_time,
1589 stderr_bytes / total_time);
1591 /* Return the exit status of the program. */
1592 debug("Exit status %d", exit_status);
1599 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1602 char *data = packet_get_string(&data_len);
1604 buffer_append(&stdout_buffer, data, data_len);
1605 memset(data, 0, data_len);
1609 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1612 char *data = packet_get_string(&data_len);
1614 buffer_append(&stderr_buffer, data, data_len);
1615 memset(data, 0, data_len);
1619 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1621 exit_status = packet_get_int();
1623 /* Acknowledge the exit. */
1624 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1627 * Must wait for packet to be sent since we are
1630 packet_write_wait();
1631 /* Flag that we want to exit. */
1635 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1638 int remote_id, sock;
1640 /* Read the remote channel number from the message. */
1641 remote_id = packet_get_int();
1645 * Get a connection to the local authentication agent (this may again
1648 sock = ssh_get_authentication_socket();
1651 * If we could not connect the agent, send an error message back to
1652 * the server. This should never happen unless the agent dies,
1653 * because authentication forwarding is only enabled if we have an
1657 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1658 -1, 0, 0, 0, "authentication agent connection", 1);
1659 c->remote_id = remote_id;
1663 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1664 packet_put_int(remote_id);
1666 /* Send a confirmation to the remote host. */
1667 debug("Forwarding authentication connection.");
1668 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1669 packet_put_int(remote_id);
1670 packet_put_int(c->self);
1676 client_request_forwarded_tcpip(const char *request_type, int rchan)
1679 char *listen_address, *originator_address;
1680 int listen_port, originator_port;
1683 /* Get rest of the packet */
1684 listen_address = packet_get_string(NULL);
1685 listen_port = packet_get_int();
1686 originator_address = packet_get_string(NULL);
1687 originator_port = packet_get_int();
1690 debug("client_request_forwarded_tcpip: listen %s port %d, originator %s port %d",
1691 listen_address, listen_port, originator_address, originator_port);
1693 sock = channel_connect_by_listen_address(listen_port);
1695 xfree(originator_address);
1696 xfree(listen_address);
1699 c = channel_new("forwarded-tcpip",
1700 SSH_CHANNEL_CONNECTING, sock, sock, -1,
1701 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1702 originator_address, 1);
1703 xfree(originator_address);
1704 xfree(listen_address);
1709 client_request_x11(const char *request_type, int rchan)
1713 int originator_port;
1716 if (!options.forward_x11) {
1717 error("Warning: ssh server tried X11 forwarding.");
1718 error("Warning: this is probably a break-in attempt by a malicious server.");
1721 originator = packet_get_string(NULL);
1722 if (datafellows & SSH_BUG_X11FWD) {
1723 debug2("buggy server: x11 request w/o originator_port");
1724 originator_port = 0;
1726 originator_port = packet_get_int();
1729 /* XXX check permission */
1730 debug("client_request_x11: request from %s %d", originator,
1733 sock = x11_connect_display();
1736 c = channel_new("x11",
1737 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1738 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1744 client_request_agent(const char *request_type, int rchan)
1749 if (!options.forward_agent) {
1750 error("Warning: ssh server tried agent forwarding.");
1751 error("Warning: this is probably a break-in attempt by a malicious server.");
1754 sock = ssh_get_authentication_socket();
1757 c = channel_new("authentication agent connection",
1758 SSH_CHANNEL_OPEN, sock, sock, -1,
1759 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1760 "authentication agent connection", 1);
1765 /* XXXX move to generic input handler */
1767 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1772 u_int rmaxpack, rwindow, len;
1774 ctype = packet_get_string(&len);
1775 rchan = packet_get_int();
1776 rwindow = packet_get_int();
1777 rmaxpack = packet_get_int();
1779 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1780 ctype, rchan, rwindow, rmaxpack);
1782 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1783 c = client_request_forwarded_tcpip(ctype, rchan);
1784 } else if (strcmp(ctype, "x11") == 0) {
1785 c = client_request_x11(ctype, rchan);
1786 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1787 c = client_request_agent(ctype, rchan);
1789 /* XXX duplicate : */
1791 debug("confirm %s", ctype);
1792 c->remote_id = rchan;
1793 c->remote_window = rwindow;
1794 c->remote_maxpacket = rmaxpack;
1795 if (c->type != SSH_CHANNEL_CONNECTING) {
1796 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1797 packet_put_int(c->remote_id);
1798 packet_put_int(c->self);
1799 packet_put_int(c->local_window);
1800 packet_put_int(c->local_maxpacket);
1804 debug("failure %s", ctype);
1805 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1806 packet_put_int(rchan);
1807 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1808 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1809 packet_put_cstring("open failed");
1810 packet_put_cstring("");
1817 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1820 int exitval, id, reply, success = 0;
1823 id = packet_get_int();
1824 rtype = packet_get_string(NULL);
1825 reply = packet_get_char();
1827 debug("client_input_channel_req: channel %d rtype %s reply %d",
1831 error("client_input_channel_req: request for channel -1");
1832 } else if ((c = channel_lookup(id)) == NULL) {
1833 error("client_input_channel_req: channel %d: unknown channel", id);
1834 } else if (strcmp(rtype, "exit-status") == 0) {
1835 exitval = packet_get_int();
1836 if (id == session_ident) {
1838 exit_status = exitval;
1839 } else if (c->ctl_fd == -1) {
1840 error("client_input_channel_req: unexpected channel %d",
1843 atomicio(vwrite, c->ctl_fd, &exitval, sizeof(exitval));
1849 packet_start(success ?
1850 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1857 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1863 rtype = packet_get_string(NULL);
1864 want_reply = packet_get_char();
1865 debug("client_input_global_request: rtype %s want_reply %d",
1868 packet_start(success ?
1869 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1871 packet_write_wait();
1877 client_session2_setup(int id, int want_tty, int want_subsystem,
1878 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env,
1879 dispatch_fn *subsys_repl)
1884 debug2("%s: id %d", __func__, id);
1886 if ((c = channel_lookup(id)) == NULL)
1887 fatal("client_session2_setup: channel %d: unknown channel", id);
1893 /* Store window size in the packet. */
1894 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
1895 memset(&ws, 0, sizeof(ws));
1897 channel_request_start(id, "pty-req", 0);
1898 packet_put_cstring(term != NULL ? term : "");
1899 packet_put_int((u_int)ws.ws_col);
1900 packet_put_int((u_int)ws.ws_row);
1901 packet_put_int((u_int)ws.ws_xpixel);
1902 packet_put_int((u_int)ws.ws_ypixel);
1903 tio = get_saved_tio();
1904 tty_make_modes(-1, tiop != NULL ? tiop : &tio);
1906 /* XXX wait for reply */
1910 /* Transfer any environment variables from client to server */
1911 if (options.num_send_env != 0 && env != NULL) {
1915 debug("Sending environment.");
1916 for (i = 0; env[i] != NULL; i++) {
1918 name = xstrdup(env[i]);
1919 if ((val = strchr(name, '=')) == NULL) {
1926 for (j = 0; j < options.num_send_env; j++) {
1927 if (match_pattern(name, options.send_env[j])) {
1933 debug3("Ignored env %s", name);
1938 debug("Sending env %s = %s", name, val);
1939 channel_request_start(id, "env", 0);
1940 packet_put_cstring(name);
1941 packet_put_cstring(val);
1947 len = buffer_len(cmd);
1951 if (want_subsystem) {
1952 debug("Sending subsystem: %.*s", len, (u_char*)buffer_ptr(cmd));
1953 channel_request_start(id, "subsystem", subsys_repl != NULL);
1954 if (subsys_repl != NULL) {
1955 /* register callback for reply */
1956 /* XXX we assume that client_loop has already been called */
1957 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, subsys_repl);
1958 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, subsys_repl);
1961 debug("Sending command: %.*s", len, (u_char*)buffer_ptr(cmd));
1962 channel_request_start(id, "exec", 0);
1964 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
1967 channel_request_start(id, "shell", 0);
1973 client_init_dispatch_20(void)
1975 dispatch_init(&dispatch_protocol_error);
1977 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1978 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
1979 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
1980 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
1981 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
1982 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1983 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1984 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
1985 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
1986 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
1989 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1991 /* global request reply messages */
1992 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
1993 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
1996 client_init_dispatch_13(void)
1998 dispatch_init(NULL);
1999 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2000 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2001 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2002 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2003 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2004 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2005 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2006 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2007 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2009 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2010 &client_input_agent_open : &deny_input_open);
2011 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2012 &x11_input_open : &deny_input_open);
2015 client_init_dispatch_15(void)
2017 client_init_dispatch_13();
2018 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2019 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2022 client_init_dispatch(void)
2025 client_init_dispatch_20();
2027 client_init_dispatch_13();
2029 client_init_dispatch_15();
2032 /* client specific fatal cleanup */
2037 leave_non_blocking();
2038 if (options.control_path != NULL && control_fd != -1)
2039 unlink(options.control_path);