1 /* $OpenBSD: clientloop.c,v 1.213 2009/07/05 19:28:33 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 #include <sys/param.h>
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
70 #ifdef HAVE_SYS_TIME_H
71 # include <sys/time.h>
73 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
103 #include "readconf.h"
104 #include "clientloop.h"
105 #include "sshconnect.h"
107 #include "atomicio.h"
119 extern Options options;
121 /* Flag indicating that stdin should be redirected from /dev/null. */
122 extern int stdin_null_flag;
124 /* Flag indicating that no shell has been requested */
125 extern int no_shell_flag;
128 extern int muxserver_sock;
131 * Name of the host we are connecting to. This is the name given on the
132 * command line, or the HostName specified for the user-supplied name in a
133 * configuration file.
138 * Flag to indicate that we have received a window change signal which has
139 * not yet been processed. This will cause a message indicating the new
140 * window size to be sent to the server a little later. This is volatile
141 * because this is updated in a signal handler.
143 static volatile sig_atomic_t received_window_change_signal = 0;
144 static volatile sig_atomic_t received_signal = 0;
146 /* Flag indicating whether the user's terminal is in non-blocking mode. */
147 static int in_non_blocking_mode = 0;
149 /* Common data for the client loop code. */
150 static volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
151 static int escape_char1; /* Escape character. (proto1 only) */
152 static int escape_pending1; /* Last character was an escape (proto1 only) */
153 static int last_was_cr; /* Last character was a newline. */
154 static int exit_status; /* Used to store the command exit status. */
155 static int stdin_eof; /* EOF has been encountered on stderr. */
156 static Buffer stdin_buffer; /* Buffer for stdin data. */
157 static Buffer stdout_buffer; /* Buffer for stdout data. */
158 static Buffer stderr_buffer; /* Buffer for stderr data. */
159 static u_int buffer_high;/* Soft max buffer size. */
160 static int connection_in; /* Connection to server (input). */
161 static int connection_out; /* Connection to server (output). */
162 static int need_rekeying; /* Set to non-zero if rekeying is requested. */
163 static int session_closed = 0; /* In SSH2: login session closed. */
165 static void client_init_dispatch(void);
166 int session_ident = -1;
168 /* Track escape per proto2 channel */
169 struct escape_filter_ctx {
174 /* Context for channel confirmation replies */
175 struct channel_reply_ctx {
176 const char *request_type;
180 /* Global request success/failure callbacks */
181 struct global_confirm {
182 TAILQ_ENTRY(global_confirm) entry;
183 global_confirm_cb *cb;
187 TAILQ_HEAD(global_confirms, global_confirm);
188 static struct global_confirms global_confirms =
189 TAILQ_HEAD_INITIALIZER(global_confirms);
194 void ssh_process_session2_setup(int, int, int, Buffer *);
196 /* Restores stdin to blocking mode. */
199 leave_non_blocking(void)
201 if (in_non_blocking_mode) {
202 unset_nonblock(fileno(stdin));
203 in_non_blocking_mode = 0;
207 /* Puts stdin terminal in non-blocking mode. */
210 enter_non_blocking(void)
212 in_non_blocking_mode = 1;
213 set_nonblock(fileno(stdin));
217 * Signal handler for the window change signal (SIGWINCH). This just sets a
218 * flag indicating that the window has changed.
222 window_change_handler(int sig)
224 received_window_change_signal = 1;
225 signal(SIGWINCH, window_change_handler);
229 * Signal handler for signals that cause the program to terminate. These
230 * signals must be trapped to restore terminal modes.
234 signal_handler(int sig)
236 received_signal = sig;
241 * Returns current time in seconds from Jan 1, 1970 with the maximum
242 * available resolution.
246 get_current_time(void)
249 gettimeofday(&tv, NULL);
250 return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
253 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
255 client_x11_get_proto(const char *display, const char *xauth_path,
256 u_int trusted, char **_proto, char **_data)
261 static char proto[512], data[512];
263 int got_data = 0, generated = 0, do_unlink = 0, i;
264 char *xauthdir, *xauthfile;
267 xauthdir = xauthfile = NULL;
270 proto[0] = data[0] = '\0';
272 if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
273 debug("No xauth program.");
275 if (display == NULL) {
276 debug("x11_get_proto: DISPLAY not set");
280 * Handle FamilyLocal case where $DISPLAY does
281 * not match an authorization entry. For this we
282 * just try "xauth list unix:displaynum.screennum".
283 * XXX: "localhost" match to determine FamilyLocal
286 if (strncmp(display, "localhost:", 10) == 0) {
287 snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
292 xauthdir = xmalloc(MAXPATHLEN);
293 xauthfile = xmalloc(MAXPATHLEN);
294 strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
295 if (mkdtemp(xauthdir) != NULL) {
297 snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
299 snprintf(cmd, sizeof(cmd),
300 "%s -f %s generate %s " SSH_X11_PROTO
301 " untrusted timeout 1200 2>" _PATH_DEVNULL,
302 xauth_path, xauthfile, display);
303 debug2("x11_get_proto: %s", cmd);
304 if (system(cmd) == 0)
310 * When in untrusted mode, we read the cookie only if it was
311 * successfully generated as an untrusted one in the step
314 if (trusted || generated) {
315 snprintf(cmd, sizeof(cmd),
316 "%s %s%s list %s 2>" _PATH_DEVNULL,
318 generated ? "-f " : "" ,
319 generated ? xauthfile : "",
321 debug2("x11_get_proto: %s", cmd);
323 if (f && fgets(line, sizeof(line), f) &&
324 sscanf(line, "%*s %511s %511s", proto, data) == 2)
329 error("Warning: untrusted X11 forwarding setup failed: "
330 "xauth key data not generated");
343 * If we didn't get authentication data, just make up some
344 * data. The forwarding code will check the validity of the
345 * response anyway, and substitute this data. The X11
346 * server, however, will ignore this fake data and use
347 * whatever authentication mechanisms it was using otherwise
348 * for the local connection.
353 logit("Warning: No xauth data; "
354 "using fake authentication data for X11 forwarding.");
355 strlcpy(proto, SSH_X11_PROTO, sizeof proto);
356 for (i = 0; i < 16; i++) {
359 snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
367 * This is called when the interactive is entered. This checks if there is
368 * an EOF coming on stdin. We must check this explicitly, as select() does
369 * not appear to wake up when redirecting from /dev/null.
373 client_check_initial_eof_on_stdin(void)
379 * If standard input is to be "redirected from /dev/null", we simply
380 * mark that we have seen an EOF and send an EOF message to the
381 * server. Otherwise, we try to read a single character; it appears
382 * that for some files, such /dev/null, select() never wakes up for
383 * read for this descriptor, which means that we never get EOF. This
384 * way we will get the EOF if stdin comes from /dev/null or similar.
386 if (stdin_null_flag) {
387 /* Fake EOF on stdin. */
388 debug("Sending eof.");
390 packet_start(SSH_CMSG_EOF);
393 enter_non_blocking();
395 /* Check for immediate EOF on stdin. */
396 len = read(fileno(stdin), buf, 1);
399 * EOF. Record that we have seen it and send
402 debug("Sending eof.");
404 packet_start(SSH_CMSG_EOF);
406 } else if (len > 0) {
408 * Got data. We must store the data in the buffer,
409 * and also process it as an escape character if
412 if ((u_char) buf[0] == escape_char1)
415 buffer_append(&stdin_buffer, buf, 1);
417 leave_non_blocking();
423 * Make packets from buffered stdin data, and buffer them for sending to the
428 client_make_packets_from_stdin_data(void)
432 /* Send buffered stdin data to the server. */
433 while (buffer_len(&stdin_buffer) > 0 &&
434 packet_not_very_much_data_to_write()) {
435 len = buffer_len(&stdin_buffer);
436 /* Keep the packets at reasonable size. */
437 if (len > packet_get_maxsize())
438 len = packet_get_maxsize();
439 packet_start(SSH_CMSG_STDIN_DATA);
440 packet_put_string(buffer_ptr(&stdin_buffer), len);
442 buffer_consume(&stdin_buffer, len);
443 /* If we have a pending EOF, send it now. */
444 if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
445 packet_start(SSH_CMSG_EOF);
452 * Checks if the client window has changed, and sends a packet about it to
453 * the server if so. The actual change is detected elsewhere (by a software
454 * interrupt on Unix); this just checks the flag and sends a message if
459 client_check_window_change(void)
463 if (! received_window_change_signal)
466 received_window_change_signal = 0;
468 debug2("client_check_window_change: changed");
471 channel_send_window_changes();
473 if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
475 packet_start(SSH_CMSG_WINDOW_SIZE);
476 packet_put_int((u_int)ws.ws_row);
477 packet_put_int((u_int)ws.ws_col);
478 packet_put_int((u_int)ws.ws_xpixel);
479 packet_put_int((u_int)ws.ws_ypixel);
485 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
487 struct global_confirm *gc;
489 if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
492 gc->cb(type, seq, gc->ctx);
493 if (--gc->ref_count <= 0) {
494 TAILQ_REMOVE(&global_confirms, gc, entry);
495 bzero(gc, sizeof(*gc));
499 packet_set_alive_timeouts(0);
503 server_alive_check(void)
506 if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
507 logit("Timeout, server not responding.");
510 packet_start(SSH2_MSG_GLOBAL_REQUEST);
511 packet_put_cstring("keepalive@openssh.com");
512 packet_put_char(1); /* boolean: want reply */
514 /* Insert an empty placeholder to maintain ordering */
515 client_register_global_confirm(NULL, NULL);
517 packet_send_ignore(0);
523 * Waits until the client can do something (some data becomes available on
524 * one of the file descriptors).
527 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
528 int *maxfdp, u_int *nallocp, int rekeying)
530 struct timeval tv, *tvp;
533 /* Add any selections by the channel mechanism. */
534 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
537 /* Read from the connection, unless our buffers are full. */
538 if (buffer_len(&stdout_buffer) < buffer_high &&
539 buffer_len(&stderr_buffer) < buffer_high &&
540 channel_not_very_much_buffered_data())
541 FD_SET(connection_in, *readsetp);
543 * Read from stdin, unless we have seen EOF or have very much
544 * buffered data to send to the server.
546 if (!stdin_eof && packet_not_very_much_data_to_write())
547 FD_SET(fileno(stdin), *readsetp);
549 /* Select stdout/stderr if have data in buffer. */
550 if (buffer_len(&stdout_buffer) > 0)
551 FD_SET(fileno(stdout), *writesetp);
552 if (buffer_len(&stderr_buffer) > 0)
553 FD_SET(fileno(stderr), *writesetp);
555 /* channel_prepare_select could have closed the last channel */
556 if (session_closed && !channel_still_open() &&
557 !packet_have_data_to_write()) {
558 /* clear mask since we did not call select() */
559 memset(*readsetp, 0, *nallocp);
560 memset(*writesetp, 0, *nallocp);
563 FD_SET(connection_in, *readsetp);
567 /* Select server connection if have data to write to the server. */
568 if (packet_have_data_to_write())
569 FD_SET(connection_out, *writesetp);
571 if (muxserver_sock != -1)
572 FD_SET(muxserver_sock, *readsetp);
575 * Wait for something to happen. This will suspend the process until
576 * some selected descriptor can be read, written, or has some other
580 if (options.server_alive_interval == 0)
583 tv.tv_sec = options.server_alive_interval;
587 ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
592 * We have to clear the select masks, because we return.
593 * We have to return, because the mainloop checks for the flags
594 * set by the signal handlers.
596 memset(*readsetp, 0, *nallocp);
597 memset(*writesetp, 0, *nallocp);
601 /* Note: we might still have data in the buffers. */
602 snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
603 buffer_append(&stderr_buffer, buf, strlen(buf));
606 server_alive_check();
610 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
612 /* Flush stdout and stderr buffers. */
613 if (buffer_len(bout) > 0)
614 atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
616 if (buffer_len(berr) > 0)
617 atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
623 * Free (and clear) the buffer to reduce the amount of data that gets
630 /* Send the suspend signal to the program itself. */
631 kill(getpid(), SIGTSTP);
633 /* Reset window sizes in case they have changed */
634 received_window_change_signal = 1;
636 /* OK, we have been continued by the user. Reinitialize buffers. */
645 client_process_net_input(fd_set *readset)
648 char buf[SSH_IOBUFSZ];
651 * Read input from the server, and add any such data to the buffer of
652 * the packet subsystem.
654 if (FD_ISSET(connection_in, readset)) {
655 /* Read as much as possible. */
656 len = roaming_read(connection_in, buf, sizeof(buf), &cont);
657 if (len == 0 && cont == 0) {
659 * Received EOF. The remote host has closed the
662 snprintf(buf, sizeof buf,
663 "Connection to %.300s closed by remote host.\r\n",
665 buffer_append(&stderr_buffer, buf, strlen(buf));
670 * There is a kernel bug on Solaris that causes select to
671 * sometimes wake up even though there is no data available.
674 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
679 * An error has encountered. Perhaps there is a
682 snprintf(buf, sizeof buf,
683 "Read from remote host %.300s: %.100s\r\n",
684 host, strerror(errno));
685 buffer_append(&stderr_buffer, buf, strlen(buf));
689 packet_process_incoming(buf, len);
694 client_status_confirm(int type, Channel *c, void *ctx)
696 struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
700 /* XXX supress on mux _client_ quietmode */
701 tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
702 c->ctl_fd != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
704 if (type == SSH2_MSG_CHANNEL_SUCCESS) {
705 debug2("%s request accepted on channel %d",
706 cr->request_type, c->self);
707 } else if (type == SSH2_MSG_CHANNEL_FAILURE) {
709 snprintf(errmsg, sizeof(errmsg),
710 "%s request failed\r\n", cr->request_type);
712 snprintf(errmsg, sizeof(errmsg),
713 "%s request failed on channel %d",
714 cr->request_type, c->self);
716 /* If error occurred on primary session channel, then exit */
717 if (cr->do_close && c->self == session_ident)
719 /* If error occurred on mux client, append to their stderr */
721 buffer_append(&c->extended, errmsg, strlen(errmsg));
726 chan_write_failed(c);
733 client_abandon_status_confirm(Channel *c, void *ctx)
739 client_expect_confirm(int id, const char *request, int do_close)
741 struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
743 cr->request_type = request;
744 cr->do_close = do_close;
746 channel_register_status_confirm(id, client_status_confirm,
747 client_abandon_status_confirm, cr);
751 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
753 struct global_confirm *gc, *last_gc;
755 /* Coalesce identical callbacks */
756 last_gc = TAILQ_LAST(&global_confirms, global_confirms);
757 if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
758 if (++last_gc->ref_count >= INT_MAX)
759 fatal("%s: last_gc->ref_count = %d",
760 __func__, last_gc->ref_count);
764 gc = xmalloc(sizeof(*gc));
768 TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
772 process_cmdline(void)
774 void (*handler)(int);
775 char *s, *cmd, *cancel_host;
777 int local = 0, remote = 0, dynamic = 0;
781 bzero(&fwd, sizeof(fwd));
782 fwd.listen_host = fwd.connect_host = NULL;
785 handler = signal(SIGINT, SIG_IGN);
786 cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
792 s++; /* Skip cmdline '-', if any */
796 if (*s == 'h' || *s == 'H' || *s == '?') {
798 logit(" -L[bind_address:]port:host:hostport "
799 "Request local forward");
800 logit(" -R[bind_address:]port:host:hostport "
801 "Request remote forward");
802 logit(" -D[bind_address:]port "
803 "Request dynamic forward");
804 logit(" -KR[bind_address:]port "
805 "Cancel remote forward");
806 if (!options.permit_local_command)
809 "Execute local command");
813 if (*s == '!' && options.permit_local_command) {
830 logit("Invalid command.");
834 if ((local || dynamic) && delete) {
835 logit("Not supported.");
838 if (remote && delete && !compat20) {
839 logit("Not supported for SSH protocol version 1.");
843 while (isspace(*++s))
848 cancel_host = hpdelim(&s); /* may be NULL */
850 cancel_port = a2port(s);
851 cancel_host = cleanhostname(cancel_host);
853 cancel_port = a2port(cancel_host);
856 if (cancel_port <= 0) {
857 logit("Bad forwarding close port");
860 channel_request_rforward_cancel(cancel_host, cancel_port);
862 if (!parse_forward(&fwd, s, dynamic, remote)) {
863 logit("Bad forwarding specification.");
866 if (local || dynamic) {
867 if (channel_setup_local_fwd_listener(fwd.listen_host,
868 fwd.listen_port, fwd.connect_host,
869 fwd.connect_port, options.gateway_ports) < 0) {
870 logit("Port forwarding failed.");
874 if (channel_request_remote_forwarding(fwd.listen_host,
875 fwd.listen_port, fwd.connect_host,
876 fwd.connect_port) < 0) {
877 logit("Port forwarding failed.");
882 logit("Forwarding port.");
886 signal(SIGINT, handler);
890 if (fwd.listen_host != NULL)
891 xfree(fwd.listen_host);
892 if (fwd.connect_host != NULL)
893 xfree(fwd.connect_host);
897 * Process the characters one by one, call with c==NULL for proto1 case.
900 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
909 int *escape_pendingp, escape_char;
910 struct escape_filter_ctx *efc;
913 escape_pendingp = &escape_pending1;
914 escape_char = escape_char1;
916 if (c->filter_ctx == NULL)
918 efc = (struct escape_filter_ctx *)c->filter_ctx;
919 escape_pendingp = &efc->escape_pending;
920 escape_char = efc->escape_char;
926 for (i = 0; i < (u_int)len; i++) {
927 /* Get one character at a time. */
930 if (*escape_pendingp) {
931 /* We have previously seen an escape character. */
932 /* Clear the flag now. */
933 *escape_pendingp = 0;
935 /* Process the escaped character. */
938 /* Terminate the connection. */
939 snprintf(string, sizeof string, "%c.\r\n",
941 buffer_append(berr, string, strlen(string));
943 if (c && c->ctl_fd != -1) {
945 chan_write_failed(c);
952 /* XXX support this for mux clients */
953 if (c && c->ctl_fd != -1) {
955 snprintf(string, sizeof string,
956 "%c%c escape not available to "
957 "multiplexed sessions\r\n",
959 buffer_append(berr, string,
963 /* Suspend the program. Inform the user */
964 snprintf(string, sizeof string,
965 "%c^Z [suspend ssh]\r\n", escape_char);
966 buffer_append(berr, string, strlen(string));
968 /* Restore terminal modes and suspend. */
969 client_suspend_self(bin, bout, berr);
971 /* We have been continued. */
976 snprintf(string, sizeof string,
977 "%cB\r\n", escape_char);
978 buffer_append(berr, string,
980 channel_request_start(session_ident,
982 packet_put_int(1000);
989 if (datafellows & SSH_BUG_NOREKEY)
990 logit("Server does not "
991 "support re-keying");
998 if (c && c->ctl_fd != -1)
1001 * Detach the program (continue to serve
1002 * connections, but put in background and no
1003 * more new connections).
1005 /* Restore tty modes. */
1008 /* Stop listening for new connections. */
1009 channel_stop_listening();
1011 snprintf(string, sizeof string,
1012 "%c& [backgrounded]\n", escape_char);
1013 buffer_append(berr, string, strlen(string));
1015 /* Fork into background. */
1018 error("fork: %.100s", strerror(errno));
1021 if (pid != 0) { /* This is the parent. */
1022 /* The parent just exits. */
1025 /* The child continues serving connections. */
1027 buffer_append(bin, "\004", 1);
1028 /* fake EOF on stdin */
1030 } else if (!stdin_eof) {
1032 * Sending SSH_CMSG_EOF alone does not
1033 * always appear to be enough. So we
1034 * try to send an EOF character first.
1036 packet_start(SSH_CMSG_STDIN_DATA);
1037 packet_put_string("\004", 1);
1041 if (buffer_len(bin) == 0) {
1042 packet_start(SSH_CMSG_EOF);
1049 if (c && c->ctl_fd != -1) {
1050 snprintf(string, sizeof string,
1052 Supported escape sequences:\r\n\
1053 %c. - terminate session\r\n\
1054 %cB - send a BREAK to the remote system\r\n\
1055 %cR - Request rekey (SSH protocol 2 only)\r\n\
1056 %c# - list forwarded connections\r\n\
1057 %c? - this message\r\n\
1058 %c%c - send the escape character by typing it twice\r\n\
1059 (Note that escapes are only recognized immediately after newline.)\r\n",
1060 escape_char, escape_char,
1061 escape_char, escape_char,
1062 escape_char, escape_char,
1063 escape_char, escape_char);
1065 snprintf(string, sizeof string,
1067 Supported escape sequences:\r\n\
1068 %c. - terminate connection (and any multiplexed sessions)\r\n\
1069 %cB - send a BREAK to the remote system\r\n\
1070 %cC - open a command line\r\n\
1071 %cR - Request rekey (SSH protocol 2 only)\r\n\
1072 %c^Z - suspend ssh\r\n\
1073 %c# - list forwarded connections\r\n\
1074 %c& - background ssh (when waiting for connections to terminate)\r\n\
1075 %c? - this message\r\n\
1076 %c%c - send the escape character by typing it twice\r\n\
1077 (Note that escapes are only recognized immediately after newline.)\r\n",
1078 escape_char, escape_char,
1079 escape_char, escape_char,
1080 escape_char, escape_char,
1081 escape_char, escape_char,
1082 escape_char, escape_char,
1085 buffer_append(berr, string, strlen(string));
1089 snprintf(string, sizeof string, "%c#\r\n",
1091 buffer_append(berr, string, strlen(string));
1092 s = channel_open_message();
1093 buffer_append(berr, s, strlen(s));
1098 if (c && c->ctl_fd != -1)
1104 if (ch != escape_char) {
1105 buffer_put_char(bin, escape_char);
1108 /* Escaped characters fall through here */
1113 * The previous character was not an escape char.
1114 * Check if this is an escape.
1116 if (last_was_cr && ch == escape_char) {
1118 * It is. Set the flag and continue to
1121 *escape_pendingp = 1;
1127 * Normal character. Record whether it was a newline,
1128 * and append it to the buffer.
1130 last_was_cr = (ch == '\r' || ch == '\n');
1131 buffer_put_char(bin, ch);
1138 client_process_input(fd_set *readset)
1141 char buf[SSH_IOBUFSZ];
1143 /* Read input from stdin. */
1144 if (FD_ISSET(fileno(stdin), readset)) {
1145 /* Read as much as possible. */
1146 len = read(fileno(stdin), buf, sizeof(buf));
1148 (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1149 return; /* we'll try again later */
1152 * Received EOF or error. They are treated
1153 * similarly, except that an error message is printed
1154 * if it was an error condition.
1157 snprintf(buf, sizeof buf, "read: %.100s\r\n",
1159 buffer_append(&stderr_buffer, buf, strlen(buf));
1161 /* Mark that we have seen EOF. */
1164 * Send an EOF message to the server unless there is
1165 * data in the buffer. If there is data in the
1166 * buffer, no message will be sent now. Code
1167 * elsewhere will send the EOF when the buffer
1168 * becomes empty if stdin_eof is set.
1170 if (buffer_len(&stdin_buffer) == 0) {
1171 packet_start(SSH_CMSG_EOF);
1174 } else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1176 * Normal successful read, and no escape character.
1177 * Just append the data to buffer.
1179 buffer_append(&stdin_buffer, buf, len);
1182 * Normal, successful read. But we have an escape
1183 * character and have to process the characters one
1186 if (process_escapes(NULL, &stdin_buffer,
1187 &stdout_buffer, &stderr_buffer, buf, len) == -1)
1194 client_process_output(fd_set *writeset)
1199 /* Write buffered output to stdout. */
1200 if (FD_ISSET(fileno(stdout), writeset)) {
1201 /* Write as much data as possible. */
1202 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1203 buffer_len(&stdout_buffer));
1205 if (errno == EINTR || errno == EAGAIN ||
1206 errno == EWOULDBLOCK)
1210 * An error or EOF was encountered. Put an
1211 * error message to stderr buffer.
1213 snprintf(buf, sizeof buf,
1214 "write stdout: %.50s\r\n", strerror(errno));
1215 buffer_append(&stderr_buffer, buf, strlen(buf));
1220 /* Consume printed data from the buffer. */
1221 buffer_consume(&stdout_buffer, len);
1223 /* Write buffered output to stderr. */
1224 if (FD_ISSET(fileno(stderr), writeset)) {
1225 /* Write as much data as possible. */
1226 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1227 buffer_len(&stderr_buffer));
1229 if (errno == EINTR || errno == EAGAIN ||
1230 errno == EWOULDBLOCK)
1234 * EOF or error, but can't even print
1241 /* Consume printed characters from the buffer. */
1242 buffer_consume(&stderr_buffer, len);
1247 * Get packets from the connection input buffer, and process them as long as
1248 * there are packets available.
1250 * Any unknown packets received during the actual
1251 * session cause the session to terminate. This is
1252 * intended to make debugging easier since no
1253 * confirmations are sent. Any compatible protocol
1254 * extensions must be negotiated during the
1255 * preparatory phase.
1259 client_process_buffered_input_packets(void)
1261 dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1262 compat20 ? xxx_kex : NULL);
1265 /* scan buf[] for '~' before sending data to the peer */
1267 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1269 client_new_escape_filter_ctx(int escape_char)
1271 struct escape_filter_ctx *ret;
1273 ret = xmalloc(sizeof(*ret));
1274 ret->escape_pending = 0;
1275 ret->escape_char = escape_char;
1279 /* Free the escape filter context on channel free */
1281 client_filter_cleanup(int cid, void *ctx)
1287 client_simple_escape_filter(Channel *c, char *buf, int len)
1289 if (c->extended_usage != CHAN_EXTENDED_WRITE)
1292 return process_escapes(c, &c->input, &c->output, &c->extended,
1297 client_channel_closed(int id, void *arg)
1299 channel_cancel_cleanup(id);
1305 * Implements the interactive session with the server. This is called after
1306 * the user has been authenticated, and a command has been started on the
1307 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1308 * used as an escape character for terminating or suspending the session.
1312 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1314 fd_set *readset = NULL, *writeset = NULL;
1315 double start_time, total_time;
1316 int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1317 u_int64_t ibytes, obytes;
1321 debug("Entering interactive session.");
1323 start_time = get_current_time();
1325 /* Initialize variables. */
1326 escape_pending1 = 0;
1330 buffer_high = 64 * 1024;
1331 connection_in = packet_get_connection_in();
1332 connection_out = packet_get_connection_out();
1333 max_fd = MAX(connection_in, connection_out);
1334 if (muxserver_sock != -1)
1335 max_fd = MAX(max_fd, muxserver_sock);
1338 /* enable nonblocking unless tty */
1339 if (!isatty(fileno(stdin)))
1340 set_nonblock(fileno(stdin));
1341 if (!isatty(fileno(stdout)))
1342 set_nonblock(fileno(stdout));
1343 if (!isatty(fileno(stderr)))
1344 set_nonblock(fileno(stderr));
1345 max_fd = MAX(max_fd, fileno(stdin));
1346 max_fd = MAX(max_fd, fileno(stdout));
1347 max_fd = MAX(max_fd, fileno(stderr));
1350 escape_char1 = escape_char_arg;
1352 /* Initialize buffers. */
1353 buffer_init(&stdin_buffer);
1354 buffer_init(&stdout_buffer);
1355 buffer_init(&stderr_buffer);
1357 client_init_dispatch();
1360 * Set signal handlers, (e.g. to restore non-blocking mode)
1361 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1363 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1364 signal(SIGHUP, signal_handler);
1365 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1366 signal(SIGINT, signal_handler);
1367 if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1368 signal(SIGQUIT, signal_handler);
1369 if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1370 signal(SIGTERM, signal_handler);
1371 signal(SIGWINCH, window_change_handler);
1377 session_ident = ssh2_chan_id;
1378 if (escape_char_arg != SSH_ESCAPECHAR_NONE)
1379 channel_register_filter(session_ident,
1380 client_simple_escape_filter, NULL,
1381 client_filter_cleanup,
1382 client_new_escape_filter_ctx(escape_char_arg));
1383 if (session_ident != -1)
1384 channel_register_cleanup(session_ident,
1385 client_channel_closed, 0);
1387 /* Check if we should immediately send eof on stdin. */
1388 client_check_initial_eof_on_stdin();
1391 /* Main loop of the client for the interactive session mode. */
1392 while (!quit_pending) {
1394 /* Process buffered packets sent by the server. */
1395 client_process_buffered_input_packets();
1397 if (compat20 && session_closed && !channel_still_open())
1400 rekeying = (xxx_kex != NULL && !xxx_kex->done);
1403 debug("rekeying in progress");
1406 * Make packets of buffered stdin data, and buffer
1407 * them for sending to the server.
1410 client_make_packets_from_stdin_data();
1413 * Make packets from buffered channel data, and
1414 * enqueue them for sending to the server.
1416 if (packet_not_very_much_data_to_write())
1417 channel_output_poll();
1420 * Check if the window size has changed, and buffer a
1421 * message about it to the server if so.
1423 client_check_window_change();
1429 * Wait until we have something to do (something becomes
1430 * available on one of the descriptors).
1433 client_wait_until_can_do_something(&readset, &writeset,
1434 &max_fd2, &nalloc, rekeying);
1439 /* Do channel operations unless rekeying in progress. */
1441 channel_after_select(readset, writeset);
1444 if (options.gss_renewal_rekey &&
1445 ssh_gssapi_credentials_updated(GSS_C_NO_CONTEXT)) {
1446 debug("credentials updated - forcing rekey");
1451 if (need_rekeying || packet_need_rekeying()) {
1452 debug("need rekeying");
1454 kex_send_kexinit(xxx_kex);
1459 /* Buffer input from the connection. */
1460 client_process_net_input(readset);
1462 /* Accept control connections. */
1463 if (muxserver_sock != -1 &&FD_ISSET(muxserver_sock, readset)) {
1464 if (muxserver_accept_control())
1472 /* Buffer data from stdin */
1473 client_process_input(readset);
1475 * Process output to stdout and stderr. Output to
1476 * the connection is processed elsewhere (above).
1478 client_process_output(writeset);
1482 * Send as much buffered packet data as possible to the
1485 if (FD_ISSET(connection_out, writeset))
1486 packet_write_poll();
1493 /* Terminate the session. */
1495 /* Stop watching for window change. */
1496 signal(SIGWINCH, SIG_DFL);
1499 packet_start(SSH2_MSG_DISCONNECT);
1500 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1501 packet_put_cstring("disconnected by user");
1503 packet_write_wait();
1511 /* restore blocking io */
1512 if (!isatty(fileno(stdin)))
1513 unset_nonblock(fileno(stdin));
1514 if (!isatty(fileno(stdout)))
1515 unset_nonblock(fileno(stdout));
1516 if (!isatty(fileno(stderr)))
1517 unset_nonblock(fileno(stderr));
1520 * If there was no shell or command requested, there will be no remote
1521 * exit status to be returned. In that case, clear error code if the
1522 * connection was deliberately terminated at this end.
1524 if (no_shell_flag && received_signal == SIGTERM) {
1525 received_signal = 0;
1529 if (received_signal) {
1530 debug("Killed by signal %d.", (int) received_signal);
1531 cleanup_exit((int) received_signal + 128);
1535 * In interactive mode (with pseudo tty) display a message indicating
1536 * that the connection has been closed.
1538 if (have_pty && options.log_level > SYSLOG_LEVEL_QUIET) {
1539 snprintf(buf, sizeof buf,
1540 "Connection to %.64s closed.\r\n", host);
1541 buffer_append(&stderr_buffer, buf, strlen(buf));
1544 /* Output any buffered data for stdout. */
1545 while (buffer_len(&stdout_buffer) > 0) {
1546 len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1547 buffer_len(&stdout_buffer));
1549 error("Write failed flushing stdout buffer.");
1552 buffer_consume(&stdout_buffer, len);
1555 /* Output any buffered data for stderr. */
1556 while (buffer_len(&stderr_buffer) > 0) {
1557 len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1558 buffer_len(&stderr_buffer));
1560 error("Write failed flushing stderr buffer.");
1563 buffer_consume(&stderr_buffer, len);
1566 /* Clear and free any buffers. */
1567 memset(buf, 0, sizeof(buf));
1568 buffer_free(&stdin_buffer);
1569 buffer_free(&stdout_buffer);
1570 buffer_free(&stderr_buffer);
1572 /* Report bytes transferred, and transfer rates. */
1573 total_time = get_current_time() - start_time;
1574 packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1575 packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1576 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1577 obytes, ibytes, total_time);
1579 verbose("Bytes per second: sent %.1f, received %.1f",
1580 obytes / total_time, ibytes / total_time);
1581 /* Return the exit status of the program. */
1582 debug("Exit status %d", exit_status);
1589 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1592 char *data = packet_get_string(&data_len);
1594 buffer_append(&stdout_buffer, data, data_len);
1595 memset(data, 0, data_len);
1599 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1602 char *data = packet_get_string(&data_len);
1604 buffer_append(&stderr_buffer, data, data_len);
1605 memset(data, 0, data_len);
1609 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1611 exit_status = packet_get_int();
1613 /* Acknowledge the exit. */
1614 packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1617 * Must wait for packet to be sent since we are
1620 packet_write_wait();
1621 /* Flag that we want to exit. */
1625 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1628 int remote_id, sock;
1630 /* Read the remote channel number from the message. */
1631 remote_id = packet_get_int();
1635 * Get a connection to the local authentication agent (this may again
1638 sock = ssh_get_authentication_socket();
1641 * If we could not connect the agent, send an error message back to
1642 * the server. This should never happen unless the agent dies,
1643 * because authentication forwarding is only enabled if we have an
1647 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1648 -1, 0, 0, 0, "authentication agent connection", 1);
1649 c->remote_id = remote_id;
1653 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1654 packet_put_int(remote_id);
1656 /* Send a confirmation to the remote host. */
1657 debug("Forwarding authentication connection.");
1658 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1659 packet_put_int(remote_id);
1660 packet_put_int(c->self);
1666 client_request_forwarded_tcpip(const char *request_type, int rchan)
1669 char *listen_address, *originator_address;
1670 u_short listen_port, originator_port;
1672 /* Get rest of the packet */
1673 listen_address = packet_get_string(NULL);
1674 listen_port = packet_get_int();
1675 originator_address = packet_get_string(NULL);
1676 originator_port = packet_get_int();
1679 debug("client_request_forwarded_tcpip: listen %s port %d, "
1680 "originator %s port %d", listen_address, listen_port,
1681 originator_address, originator_port);
1683 c = channel_connect_by_listen_address(listen_port,
1684 "forwarded-tcpip", originator_address);
1686 xfree(originator_address);
1687 xfree(listen_address);
1692 client_request_x11(const char *request_type, int rchan)
1696 u_short originator_port;
1699 if (!options.forward_x11) {
1700 error("Warning: ssh server tried X11 forwarding.");
1701 error("Warning: this is probably a break-in attempt by a "
1702 "malicious server.");
1705 originator = packet_get_string(NULL);
1706 if (datafellows & SSH_BUG_X11FWD) {
1707 debug2("buggy server: x11 request w/o originator_port");
1708 originator_port = 0;
1710 originator_port = packet_get_int();
1713 /* XXX check permission */
1714 debug("client_request_x11: request from %s %d", originator,
1717 sock = x11_connect_display();
1720 c = channel_new("x11",
1721 SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1722 CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT, 0, "x11", 1);
1728 client_request_agent(const char *request_type, int rchan)
1733 if (!options.forward_agent) {
1734 error("Warning: ssh server tried agent forwarding.");
1735 error("Warning: this is probably a break-in attempt by a "
1736 "malicious server.");
1739 sock = ssh_get_authentication_socket();
1742 c = channel_new("authentication agent connection",
1743 SSH_CHANNEL_OPEN, sock, sock, -1,
1744 CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1745 "authentication agent connection", 1);
1751 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1756 if (tun_mode == SSH_TUNMODE_NO)
1760 error("Tunnel forwarding is not supported for protocol 1");
1764 debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1766 /* Open local tunnel device */
1767 if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1768 error("Tunnel device open failed.");
1772 c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1773 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, "tun", 1);
1776 #if defined(SSH_TUN_FILTER)
1777 if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1778 channel_register_filter(c->self, sys_tun_infilter,
1779 sys_tun_outfilter, NULL, NULL);
1782 packet_start(SSH2_MSG_CHANNEL_OPEN);
1783 packet_put_cstring("tun@openssh.com");
1784 packet_put_int(c->self);
1785 packet_put_int(c->local_window_max);
1786 packet_put_int(c->local_maxpacket);
1787 packet_put_int(tun_mode);
1788 packet_put_int(remote_tun);
1794 /* XXXX move to generic input handler */
1796 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1801 u_int rmaxpack, rwindow, len;
1803 ctype = packet_get_string(&len);
1804 rchan = packet_get_int();
1805 rwindow = packet_get_int();
1806 rmaxpack = packet_get_int();
1808 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1809 ctype, rchan, rwindow, rmaxpack);
1811 if (strcmp(ctype, "forwarded-tcpip") == 0) {
1812 c = client_request_forwarded_tcpip(ctype, rchan);
1813 } else if (strcmp(ctype, "x11") == 0) {
1814 c = client_request_x11(ctype, rchan);
1815 } else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1816 c = client_request_agent(ctype, rchan);
1818 /* XXX duplicate : */
1820 debug("confirm %s", ctype);
1821 c->remote_id = rchan;
1822 c->remote_window = rwindow;
1823 c->remote_maxpacket = rmaxpack;
1824 if (c->type != SSH_CHANNEL_CONNECTING) {
1825 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1826 packet_put_int(c->remote_id);
1827 packet_put_int(c->self);
1828 packet_put_int(c->local_window);
1829 packet_put_int(c->local_maxpacket);
1833 debug("failure %s", ctype);
1834 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1835 packet_put_int(rchan);
1836 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1837 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1838 packet_put_cstring("open failed");
1839 packet_put_cstring("");
1846 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1849 int exitval, id, reply, success = 0;
1852 id = packet_get_int();
1853 rtype = packet_get_string(NULL);
1854 reply = packet_get_char();
1856 debug("client_input_channel_req: channel %d rtype %s reply %d",
1860 error("client_input_channel_req: request for channel -1");
1861 } else if ((c = channel_lookup(id)) == NULL) {
1862 error("client_input_channel_req: channel %d: "
1863 "unknown channel", id);
1864 } else if (strcmp(rtype, "eow@openssh.com") == 0) {
1867 } else if (strcmp(rtype, "exit-status") == 0) {
1868 exitval = packet_get_int();
1869 if (id == session_ident) {
1871 exit_status = exitval;
1872 } else if (c->ctl_fd == -1) {
1873 error("client_input_channel_req: unexpected channel %d",
1876 atomicio(vwrite, c->ctl_fd, &exitval, sizeof(exitval));
1882 packet_start(success ?
1883 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1884 packet_put_int(c->remote_id);
1890 client_input_global_request(int type, u_int32_t seq, void *ctxt)
1896 rtype = packet_get_string(NULL);
1897 want_reply = packet_get_char();
1898 debug("client_input_global_request: rtype %s want_reply %d",
1901 packet_start(success ?
1902 SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
1904 packet_write_wait();
1910 client_session2_setup(int id, int want_tty, int want_subsystem,
1911 const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
1916 debug2("%s: id %d", __func__, id);
1918 if ((c = channel_lookup(id)) == NULL)
1919 fatal("client_session2_setup: channel %d: unknown channel", id);
1924 /* Store window size in the packet. */
1925 if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
1926 memset(&ws, 0, sizeof(ws));
1928 channel_request_start(id, "pty-req", 1);
1929 client_expect_confirm(id, "PTY allocation", 0);
1930 packet_put_cstring(term != NULL ? term : "");
1931 packet_put_int((u_int)ws.ws_col);
1932 packet_put_int((u_int)ws.ws_row);
1933 packet_put_int((u_int)ws.ws_xpixel);
1934 packet_put_int((u_int)ws.ws_ypixel);
1936 tiop = get_saved_tio();
1937 tty_make_modes(-1, tiop);
1939 /* XXX wait for reply */
1943 /* Transfer any environment variables from client to server */
1944 if (options.num_send_env != 0 && env != NULL) {
1948 debug("Sending environment.");
1949 for (i = 0; env[i] != NULL; i++) {
1951 name = xstrdup(env[i]);
1952 if ((val = strchr(name, '=')) == NULL) {
1959 for (j = 0; j < options.num_send_env; j++) {
1960 if (match_pattern(name, options.send_env[j])) {
1966 debug3("Ignored env %s", name);
1971 debug("Sending env %s = %s", name, val);
1972 channel_request_start(id, "env", 0);
1973 packet_put_cstring(name);
1974 packet_put_cstring(val);
1980 len = buffer_len(cmd);
1984 if (want_subsystem) {
1985 debug("Sending subsystem: %.*s",
1986 len, (u_char*)buffer_ptr(cmd));
1987 channel_request_start(id, "subsystem", 1);
1988 client_expect_confirm(id, "subsystem", 1);
1990 debug("Sending command: %.*s",
1991 len, (u_char*)buffer_ptr(cmd));
1992 channel_request_start(id, "exec", 1);
1993 client_expect_confirm(id, "exec", 1);
1995 packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
1998 channel_request_start(id, "shell", 1);
1999 client_expect_confirm(id, "shell", 1);
2005 client_init_dispatch_20(void)
2007 dispatch_init(&dispatch_protocol_error);
2009 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2010 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2011 dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2012 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2013 dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2014 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2015 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2016 dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2017 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2018 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2019 dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2020 dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2023 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2025 /* global request reply messages */
2026 dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2027 dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2031 client_init_dispatch_13(void)
2033 dispatch_init(NULL);
2034 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2035 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2036 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2037 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2038 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2039 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2040 dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2041 dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2042 dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2044 dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2045 &client_input_agent_open : &deny_input_open);
2046 dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2047 &x11_input_open : &deny_input_open);
2051 client_init_dispatch_15(void)
2053 client_init_dispatch_13();
2054 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2055 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2059 client_init_dispatch(void)
2062 client_init_dispatch_20();
2064 client_init_dispatch_13();
2066 client_init_dispatch_15();
2069 /* client specific fatal cleanup */
2074 leave_non_blocking();
2075 if (options.control_path != NULL && muxserver_sock != -1)
2076 unlink(options.control_path);