Home | History | Annotate | Download | only in ssh
      1 /*
      2  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      3  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      4  *                    All rights reserved
      5  * The main loop for the interactive session (client side).
      6  *
      7  * As far as I am concerned, the code I have written for this software
      8  * can be used freely for any purpose.  Any derived versions of this
      9  * software must be clearly marked as such, and if the derived work is
     10  * incompatible with the protocol description in the RFC file, it must be
     11  * called by a name other than "ssh" or "Secure Shell".
     12  *
     13  *
     14  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
     15  *
     16  * Redistribution and use in source and binary forms, with or without
     17  * modification, are permitted provided that the following conditions
     18  * are met:
     19  * 1. Redistributions of source code must retain the above copyright
     20  *    notice, this list of conditions and the following disclaimer.
     21  * 2. Redistributions in binary form must reproduce the above copyright
     22  *    notice, this list of conditions and the following disclaimer in the
     23  *    documentation and/or other materials provided with the distribution.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     28  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     29  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     30  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     31  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     34  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     35  *
     36  *
     37  * SSH2 support added by Markus Friedl.
     38  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  *
     49  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     50  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     51  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     52  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     53  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     54  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     55  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     56  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     58  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     59  */
     60 
     61 /*
     62  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
     63  * Use is subject to license terms.
     64  */
     65 
     66 #include "includes.h"
     67 RCSID("$OpenBSD: clientloop.c,v 1.104 2002/08/22 19:38:42 stevesk Exp $");
     68 
     69 #include "ssh.h"
     70 #include "ssh1.h"
     71 #include "ssh2.h"
     72 #include "xmalloc.h"
     73 #include "packet.h"
     74 #include "buffer.h"
     75 #include "compat.h"
     76 #include "channels.h"
     77 #include "dispatch.h"
     78 #include "buffer.h"
     79 #include "bufaux.h"
     80 #include "key.h"
     81 #include "kex.h"
     82 #include "log.h"
     83 #include "readconf.h"
     84 #include "clientloop.h"
     85 #include "authfd.h"
     86 #include "atomicio.h"
     87 #include "sshtty.h"
     88 #include "misc.h"
     89 #include "readpass.h"
     90 
     91 /* import options */
     92 extern Options options;
     93 
     94 /* Flag indicating that stdin should be redirected from /dev/null. */
     95 extern int stdin_null_flag;
     96 
     97 /*
     98  * Name of the host we are connecting to.  This is the name given on the
     99  * command line, or the HostName specified for the user-supplied name in a
    100  * configuration file.
    101  */
    102 extern char *host;
    103 
    104 /*
    105  * Flag to indicate that we have received a window change signal which has
    106  * not yet been processed.  This will cause a message indicating the new
    107  * window size to be sent to the server a little later.  This is volatile
    108  * because this is updated in a signal handler.
    109  */
    110 static volatile sig_atomic_t received_window_change_signal = 0;
    111 static volatile sig_atomic_t received_signal = 0;
    112 
    113 /* Flag indicating whether the user's terminal is in non-blocking mode. */
    114 static int in_non_blocking_mode = 0;
    115 
    116 /* Common data for the client loop code. */
    117 static int quit_pending;	/* Set to non-zero to quit the client loop. */
    118 static int escape_char;		/* Escape character. */
    119 static int escape_pending;	/* Last character was the escape character */
    120 static int last_was_cr;		/* Last character was a newline. */
    121 static int exit_status;		/* Used to store the exit status of the command. */
    122 static int stdin_eof;		/* EOF has been encountered on standard error. */
    123 static Buffer stdin_buffer;	/* Buffer for stdin data. */
    124 static Buffer stdout_buffer;	/* Buffer for stdout data. */
    125 static Buffer stderr_buffer;	/* Buffer for stderr data. */
    126 static u_long stdin_bytes, stdout_bytes, stderr_bytes;
    127 static u_int buffer_high;	/* Soft max buffer size. */
    128 static int connection_in;	/* Connection to server (input). */
    129 static int connection_out;	/* Connection to server (output). */
    130 static int need_rekeying;	/* Set to non-zero if rekeying is requested. */
    131 static int session_closed = 0;	/* In SSH2: login session closed. */
    132 static int server_alive_timeouts = 0; /* Number of outstanding alive packets. */
    133 
    134 static void client_init_dispatch(void);
    135 int	session_ident = -1;
    136 
    137 /*XXX*/
    138 extern Kex *xxx_kex;
    139 
    140 extern int will_daemonize;
    141 
    142 /* Restores stdin to blocking mode. */
    143 
    144 static void
    145 leave_non_blocking(void)
    146 {
    147 	if (in_non_blocking_mode) {
    148 		(void) fcntl(fileno(stdin), F_SETFL, 0);
    149 		in_non_blocking_mode = 0;
    150 		fatal_remove_cleanup((void (*) (void *)) leave_non_blocking, NULL);
    151 	}
    152 }
    153 
    154 /* Puts stdin terminal in non-blocking mode. */
    155 
    156 static void
    157 enter_non_blocking(void)
    158 {
    159 	in_non_blocking_mode = 1;
    160 	(void) fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
    161 	fatal_add_cleanup((void (*) (void *)) leave_non_blocking, NULL);
    162 }
    163 
    164 /*
    165  * Signal handler for the window change signal (SIGWINCH).  This just sets a
    166  * flag indicating that the window has changed.
    167  */
    168 
    169 static void
    170 window_change_handler(int sig)
    171 {
    172 	received_window_change_signal = 1;
    173 	signal(SIGWINCH, window_change_handler);
    174 }
    175 
    176 /*
    177  * Signal handler for signals that cause the program to terminate.  These
    178  * signals must be trapped to restore terminal modes.
    179  */
    180 
    181 static void
    182 signal_handler(int sig)
    183 {
    184 	received_signal = sig;
    185 	quit_pending = 1;
    186 }
    187 
    188 /*
    189  * Returns current time in seconds from Jan 1, 1970 with the maximum
    190  * available resolution.
    191  */
    192 
    193 static double
    194 get_current_time(void)
    195 {
    196 	struct timeval tv;
    197 	gettimeofday(&tv, NULL);
    198 	return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
    199 }
    200 
    201 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
    202 void
    203 client_x11_get_proto(const char *display, const char *xauth_path,
    204     u_int trusted, char **_proto, char **_data)
    205 {
    206 	char cmd[1024];
    207 	char line[512];
    208 	char xdisplay[512];
    209 	static char proto[512], data[512];
    210 	FILE *f;
    211 	int got_data = 0, generated = 0, do_unlink = 0, i;
    212 	char *xauthdir, *xauthfile;
    213 	struct stat st;
    214 
    215 	xauthdir = xauthfile = NULL;
    216 	*_proto = proto;
    217 	*_data = data;
    218 	proto[0] = data[0] = '\0';
    219 
    220 	if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
    221 		debug("No xauth program.");
    222 	} else {
    223 		if (display == NULL) {
    224 			debug("x11_get_proto: DISPLAY not set");
    225 			return;
    226 		}
    227 		/*
    228 		 * Handle FamilyLocal case where $DISPLAY does
    229 		 * not match an authorization entry.  For this we
    230 		 * just try "xauth list unix:displaynum.screennum".
    231 		 * XXX: "localhost" match to determine FamilyLocal
    232 		 *      is not perfect.
    233 		 */
    234 		if (strncmp(display, "localhost:", 10) == 0) {
    235 			snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
    236 			    display + 10);
    237 			display = xdisplay;
    238 		}
    239 		if (trusted == 0) {
    240 			xauthdir = xmalloc(MAXPATHLEN);
    241 			xauthfile = xmalloc(MAXPATHLEN);
    242 			strlcpy(xauthdir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
    243 			if (mkdtemp(xauthdir) != NULL) {
    244 				do_unlink = 1;
    245 				snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
    246 				    xauthdir);
    247 				snprintf(cmd, sizeof(cmd),
    248 				    "%s -f %s generate %s " SSH_X11_PROTO
    249 				    " untrusted timeout 1200 2>" _PATH_DEVNULL,
    250 				    xauth_path, xauthfile, display);
    251 				debug2("x11_get_proto: %s", cmd);
    252 				if (system(cmd) == 0)
    253 					generated = 1;
    254 			}
    255 		}
    256 
    257 		/*
    258 		 * When in untrusted mode, we read the cookie only if it was
    259 		 * successfully generated as an untrusted one in the step
    260 		 * above.
    261 		 */
    262 		if (trusted || generated) {
    263 			snprintf(cmd, sizeof(cmd),
    264 			    "%s %s%s list %s 2>" _PATH_DEVNULL,
    265 			    xauth_path,
    266 			    generated ? "-f " : "" ,
    267 			    generated ? xauthfile : "",
    268 			    display);
    269 			debug2("x11_get_proto: %s", cmd);
    270 			f = popen(cmd, "r");
    271 			if (f && fgets(line, sizeof(line), f) &&
    272 			    sscanf(line, "%*s %511s %511s", proto, data) == 2)
    273 				got_data = 1;
    274 			if (f)
    275 				pclose(f);
    276 		}
    277 		else
    278 			error("Warning: untrusted X11 forwarding setup failed: "
    279 			    "xauth key data not generated");
    280 	}
    281 
    282 	if (do_unlink) {
    283 		unlink(xauthfile);
    284 		rmdir(xauthdir);
    285 	}
    286 	if (xauthdir)
    287 		xfree(xauthdir);
    288 	if (xauthfile)
    289 		xfree(xauthfile);
    290 
    291 	/*
    292 	 * If we didn't get authentication data, just make up some
    293 	 * data.  The forwarding code will check the validity of the
    294 	 * response anyway, and substitute this data.  The X11
    295 	 * server, however, will ignore this fake data and use
    296 	 * whatever authentication mechanisms it was using otherwise
    297 	 * for the local connection.
    298 	 */
    299 	if (!got_data) {
    300 		u_int32_t rnd = 0;
    301 
    302 		log("Warning: No xauth data; "
    303 		    "using fake authentication data for X11 forwarding.");
    304 		strlcpy(proto, SSH_X11_PROTO, sizeof proto);
    305 		for (i = 0; i < 16; i++) {
    306 			if (i % 4 == 0)
    307 				rnd = arc4random();
    308 			snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
    309 			    rnd & 0xff);
    310 			rnd >>= 8;
    311 		}
    312 	}
    313 }
    314 
    315 /*
    316  * This is called when the interactive is entered.  This checks if there is
    317  * an EOF coming on stdin.  We must check this explicitly, as select() does
    318  * not appear to wake up when redirecting from /dev/null.
    319  */
    320 
    321 static void
    322 client_check_initial_eof_on_stdin(void)
    323 {
    324 	int len;
    325 	char buf[1];
    326 
    327 	/*
    328 	 * If standard input is to be "redirected from /dev/null", we simply
    329 	 * mark that we have seen an EOF and send an EOF message to the
    330 	 * server. Otherwise, we try to read a single character; it appears
    331 	 * that for some files, such /dev/null, select() never wakes up for
    332 	 * read for this descriptor, which means that we never get EOF.  This
    333 	 * way we will get the EOF if stdin comes from /dev/null or similar.
    334 	 */
    335 	if (stdin_null_flag) {
    336 		/* Fake EOF on stdin. */
    337 		debug("Sending eof.");
    338 		stdin_eof = 1;
    339 		packet_start(SSH_CMSG_EOF);
    340 		packet_send();
    341 	} else {
    342 		enter_non_blocking();
    343 
    344 		/* Check for immediate EOF on stdin. */
    345 		len = read(fileno(stdin), buf, 1);
    346 		if (len == 0) {
    347 			/* EOF.  Record that we have seen it and send EOF to server. */
    348 			debug("Sending eof.");
    349 			stdin_eof = 1;
    350 			packet_start(SSH_CMSG_EOF);
    351 			packet_send();
    352 		} else if (len > 0) {
    353 			/*
    354 			 * Got data.  We must store the data in the buffer,
    355 			 * and also process it as an escape character if
    356 			 * appropriate.
    357 			 */
    358 			if ((u_char) buf[0] == escape_char)
    359 				escape_pending = 1;
    360 			else
    361 				buffer_append(&stdin_buffer, buf, 1);
    362 		}
    363 		leave_non_blocking();
    364 	}
    365 }
    366 
    367 
    368 /*
    369  * Make packets from buffered stdin data, and buffer them for sending to the
    370  * connection.
    371  */
    372 
    373 static void
    374 client_make_packets_from_stdin_data(void)
    375 {
    376 	u_int len;
    377 
    378 	/* Send buffered stdin data to the server. */
    379 	while (buffer_len(&stdin_buffer) > 0 &&
    380 	    packet_not_very_much_data_to_write()) {
    381 		len = buffer_len(&stdin_buffer);
    382 		/* Keep the packets at reasonable size. */
    383 		if (len > packet_get_maxsize())
    384 			len = packet_get_maxsize();
    385 		packet_start(SSH_CMSG_STDIN_DATA);
    386 		packet_put_string(buffer_ptr(&stdin_buffer), len);
    387 		packet_send();
    388 		buffer_consume(&stdin_buffer, len);
    389 		stdin_bytes += len;
    390 		/* If we have a pending EOF, send it now. */
    391 		if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
    392 			packet_start(SSH_CMSG_EOF);
    393 			packet_send();
    394 		}
    395 	}
    396 }
    397 
    398 /*
    399  * Checks if the client window has changed, and sends a packet about it to
    400  * the server if so.  The actual change is detected elsewhere (by a software
    401  * interrupt on Unix); this just checks the flag and sends a message if
    402  * appropriate.
    403  */
    404 
    405 static void
    406 client_check_window_change(void)
    407 {
    408 	struct winsize ws;
    409 
    410 	if (! received_window_change_signal)
    411 		return;
    412 	/** XXX race */
    413 	received_window_change_signal = 0;
    414 
    415 	if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
    416 		return;
    417 
    418 	debug2("client_check_window_change: changed");
    419 
    420 	if (compat20) {
    421 		channel_request_start(session_ident, "window-change", 0);
    422 		packet_put_int(ws.ws_col);
    423 		packet_put_int(ws.ws_row);
    424 		packet_put_int(ws.ws_xpixel);
    425 		packet_put_int(ws.ws_ypixel);
    426 		packet_send();
    427 	} else {
    428 		packet_start(SSH_CMSG_WINDOW_SIZE);
    429 		packet_put_int(ws.ws_row);
    430 		packet_put_int(ws.ws_col);
    431 		packet_put_int(ws.ws_xpixel);
    432 		packet_put_int(ws.ws_ypixel);
    433 		packet_send();
    434 	}
    435 }
    436 
    437 static void
    438 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
    439 {
    440 	server_alive_timeouts = 0;
    441 	client_global_request_reply_fwd(type, seq, ctxt);
    442 }
    443 
    444 static void
    445 server_alive_check(void)
    446 {
    447 	if (++server_alive_timeouts > options.server_alive_count_max) {
    448 		log("Timeout, server not responding.");
    449 		fatal_cleanup();
    450 	}
    451 	packet_start(SSH2_MSG_GLOBAL_REQUEST);
    452 	packet_put_cstring("keepalive (at) openssh.com");
    453 	packet_put_char(1);     /* boolean: want reply */
    454 	packet_send();
    455 }
    456 
    457 /*
    458  * Waits until the client can do something (some data becomes available on
    459  * one of the file descriptors).
    460  */
    461 
    462 static void
    463 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
    464     int *maxfdp, int *nallocp, int rekeying)
    465 {
    466 	struct timeval tv, *tvp;
    467 	int ret;
    468 
    469 	/* Add any selections by the channel mechanism. */
    470 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, rekeying);
    471 
    472 	if (!compat20) {
    473 		/* Read from the connection, unless our buffers are full. */
    474 		if (buffer_len(&stdout_buffer) < buffer_high &&
    475 		    buffer_len(&stderr_buffer) < buffer_high &&
    476 		    channel_not_very_much_buffered_data())
    477 			FD_SET(connection_in, *readsetp);
    478 		/*
    479 		 * Read from stdin, unless we have seen EOF or have very much
    480 		 * buffered data to send to the server.
    481 		 */
    482 		if (!stdin_eof && packet_not_very_much_data_to_write())
    483 			FD_SET(fileno(stdin), *readsetp);
    484 
    485 		/* Select stdout/stderr if have data in buffer. */
    486 		if (buffer_len(&stdout_buffer) > 0)
    487 			FD_SET(fileno(stdout), *writesetp);
    488 		if (buffer_len(&stderr_buffer) > 0)
    489 			FD_SET(fileno(stderr), *writesetp);
    490 	} else {
    491 		/* channel_prepare_select could have closed the last channel */
    492 		if (session_closed && !channel_still_open() &&
    493 		    !packet_have_data_to_write()) {
    494 			/* clear mask since we did not call select() */
    495 			memset(*readsetp, 0, *nallocp);
    496 			memset(*writesetp, 0, *nallocp);
    497 			return;
    498 		} else {
    499 			FD_SET(connection_in, *readsetp);
    500 		}
    501 	}
    502 
    503 	/* Select server connection if have data to write to the server. */
    504 	if (packet_have_data_to_write())
    505 		FD_SET(connection_out, *writesetp);
    506 
    507 	/*
    508 	 * Wait for something to happen.  This will suspend the process until
    509 	 * some selected descriptor can be read, written, or has some other
    510 	 * event pending.
    511 	 */
    512 
    513 	if (options.server_alive_interval == 0 || !compat20)
    514 		tvp = NULL;
    515 	else {
    516 		tv.tv_sec = options.server_alive_interval;
    517 		tv.tv_usec = 0;
    518 		tvp = &tv;
    519 	}
    520 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
    521 	if (ret < 0) {
    522 		char buf[100];
    523 
    524 		/*
    525 		 * We have to clear the select masks, because we return.
    526 		 * We have to return, because the mainloop checks for the flags
    527 		 * set by the signal handlers.
    528 		 */
    529 		memset(*readsetp, 0, *nallocp);
    530 		memset(*writesetp, 0, *nallocp);
    531 
    532 		if (errno == EINTR)
    533 			return;
    534 		/* Note: we might still have data in the buffers. */
    535 		snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
    536 		buffer_append(&stderr_buffer, buf, strlen(buf));
    537 		quit_pending = 1;
    538 	} else if (ret == 0)
    539 		server_alive_check();
    540 }
    541 
    542 static void
    543 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
    544 {
    545 	struct winsize oldws, newws;
    546 
    547 	/* Flush stdout and stderr buffers. */
    548 	if (buffer_len(bout) > 0)
    549 		atomicio(write, fileno(stdout), buffer_ptr(bout), buffer_len(bout));
    550 	if (buffer_len(berr) > 0)
    551 		atomicio(write, fileno(stderr), buffer_ptr(berr), buffer_len(berr));
    552 
    553 	leave_raw_mode();
    554 
    555 	/*
    556 	 * Free (and clear) the buffer to reduce the amount of data that gets
    557 	 * written to swap.
    558 	 */
    559 	buffer_free(bin);
    560 	buffer_free(bout);
    561 	buffer_free(berr);
    562 
    563 	/* Save old window size. */
    564 	ioctl(fileno(stdin), TIOCGWINSZ, &oldws);
    565 
    566 	/* Send the suspend signal to the program itself. */
    567 	kill(getpid(), SIGTSTP);
    568 
    569 	/* Check if the window size has changed. */
    570 	if (ioctl(fileno(stdin), TIOCGWINSZ, &newws) >= 0 &&
    571 	    (oldws.ws_row != newws.ws_row ||
    572 	    oldws.ws_col != newws.ws_col ||
    573 	    oldws.ws_xpixel != newws.ws_xpixel ||
    574 	    oldws.ws_ypixel != newws.ws_ypixel))
    575 		received_window_change_signal = 1;
    576 
    577 	/* OK, we have been continued by the user. Reinitialize buffers. */
    578 	buffer_init(bin);
    579 	buffer_init(bout);
    580 	buffer_init(berr);
    581 
    582 	enter_raw_mode();
    583 }
    584 
    585 static void
    586 client_process_net_input(fd_set * readset)
    587 {
    588 	int len;
    589 	char buf[8192];
    590 
    591 	/*
    592 	 * Read input from the server, and add any such data to the buffer of
    593 	 * the packet subsystem.
    594 	 */
    595 	if (FD_ISSET(connection_in, readset)) {
    596 		/* Read as much as possible. */
    597 		len = read(connection_in, buf, sizeof(buf));
    598 		if (len == 0) {
    599 			/* Received EOF.  The remote host has closed the connection. */
    600 			snprintf(buf, sizeof buf,
    601 				 gettext("Connection to %.300s closed "
    602 					 "by remote host.\r\n"),
    603 				 host);
    604 			buffer_append(&stderr_buffer, buf, strlen(buf));
    605 			quit_pending = 1;
    606 			return;
    607 		}
    608 		/*
    609 		 * There is a kernel bug on Solaris that causes select to
    610 		 * sometimes wake up even though there is no data available.
    611 		 */
    612 		if (len < 0 && (errno == EAGAIN || errno == EINTR))
    613 			len = 0;
    614 
    615 		if (len < 0) {
    616 			/* An error has encountered.  Perhaps there is a network problem. */
    617 			snprintf(buf, sizeof buf,
    618 				 gettext("Read from remote host "
    619 					 "%.300s: %.100s\r\n"),
    620 				 host, strerror(errno));
    621 			buffer_append(&stderr_buffer, buf, strlen(buf));
    622 			quit_pending = 1;
    623 			return;
    624 		}
    625 		packet_process_incoming(buf, len);
    626 	}
    627 }
    628 
    629 static void
    630 process_cmdline(void)
    631 {
    632 	void (*handler)(int);
    633 	char *s, *cmd;
    634 	int delete = 0;
    635 	int local = 0;
    636 	Forward fwd;
    637 
    638 	memset(&fwd, 0, sizeof(fwd));
    639 
    640 	leave_raw_mode();
    641 	handler = signal(SIGINT, SIG_IGN);
    642 	cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
    643 	if (s == NULL)
    644 		goto out;
    645 	while (isspace(*s))
    646 		s++;
    647 	if (*s == '-')
    648 		s++;	/* Skip cmdline '-', if any */
    649 	if (*s == '\0')
    650 		goto out;
    651 
    652 	if (*s == 'h' || *s == 'H' || *s == '?') {
    653 		log("Commands:");
    654 		log("      -L[bind_address:]port:host:hostport    "
    655 		    "Request local forward");
    656 		log("      -R[bind_address:]port:host:hostport    "
    657 		    "Request remote forward");
    658 		log("      -KR[bind_address:]port                 "
    659 		    "Cancel remote forward");
    660 		goto out;
    661 	}
    662 
    663 	if (*s == 'K') {
    664 		delete = 1;
    665 		s++;
    666 	}
    667 	if (*s != 'L' && *s != 'R') {
    668 		log("Invalid command.");
    669 		goto out;
    670 	}
    671 	if (*s == 'L')
    672 		local = 1;
    673 	if (local && delete) {
    674 		log("Not supported.");
    675 		goto out;
    676 	}
    677 	if ((!local || delete) && !compat20) {
    678 		log("Not supported for SSH protocol version 1.");
    679 		goto out;
    680 	}
    681 
    682 	while (isspace(*++s))
    683 		;
    684 
    685 	if (delete) {
    686 		if (parse_forward(0, &fwd, s) == 0) {
    687 			log("Bad forwarding close port");
    688 			goto out;
    689 		}
    690 		channel_request_rforward_cancel(fwd.listen_host, fwd.listen_port);
    691 	} else {
    692 		if (parse_forward(1, &fwd, s) == 0) {
    693 			log("Bad forwarding specification.");
    694 			goto out;
    695 		}
    696 		if (local) {
    697 			if (channel_setup_local_fwd_listener(fwd.listen_host,
    698 			    fwd.listen_port, fwd.connect_host,
    699 			    fwd.connect_port, options.gateway_ports) < 0) {
    700 				log("Port forwarding failed.");
    701 				goto out;
    702 			}
    703 		} else {
    704 			if (channel_request_remote_forwarding(fwd.listen_host,
    705 			    fwd.listen_port, fwd.connect_host,
    706 			    fwd.connect_port) < 0) {
    707 				log("Port forwarding failed.");
    708 				goto out;
    709 			}
    710 		}
    711 
    712 		log("Forwarding port.");
    713 	}
    714 
    715 out:
    716 	signal(SIGINT, handler);
    717 	enter_raw_mode();
    718 	if (cmd != NULL)
    719 		xfree(cmd);
    720 	if (fwd.listen_host != NULL)
    721 		xfree(fwd.listen_host);
    722 	if (fwd.connect_host != NULL)
    723 		xfree(fwd.connect_host);
    724 }
    725 
    726 /*
    727  * If we are using the engine we must not fork until we do key reexchange. See
    728  * PKCS#11 spec for more information on fork safety and packet.c for information
    729  * about forking with the engine.
    730  */
    731 void
    732 client_daemonize(void)
    733 {
    734 	if (compat20 == 1 && options.use_openssl_engine == 1) {
    735 		will_daemonize = 1;
    736 		debug("must rekey before daemonizing");
    737 		kex_send_kexinit(xxx_kex);
    738 		need_rekeying = 0;
    739 	}
    740 	else {
    741 		if (daemon(1, 1) < 0) {
    742 			fatal("daemon() failed: %.200s",
    743 			    strerror(errno));
    744 		}
    745 	}
    746 }
    747 
    748 /* process the characters one by one */
    749 static int
    750 process_escapes(Buffer *bin, Buffer *bout, Buffer *berr, char *buf, int len)
    751 {
    752 	char string[1536];
    753 	int bytes = 0;
    754 	u_int i;
    755 	u_char ch;
    756 	char *s;
    757 
    758 	for (i = 0; i < len; i++) {
    759 		/* Get one character at a time. */
    760 		ch = buf[i];
    761 
    762 		if (escape_pending) {
    763 			/* We have previously seen an escape character. */
    764 			/* Clear the flag now. */
    765 			escape_pending = 0;
    766 
    767 			/* Process the escaped character. */
    768 			switch (ch) {
    769 			case '.':
    770 				/* Terminate the connection. */
    771 				snprintf(string, sizeof string, "%c.\r\n", escape_char);
    772 				buffer_append(berr, string, strlen(string));
    773 
    774 				quit_pending = 1;
    775 				return -1;
    776 
    777 			case 'Z' - 64:
    778 				/* Suspend the program. */
    779 				/* Print a message to that effect to the user. */
    780 				snprintf(string, sizeof string,
    781 					 gettext("%c^Z [suspend ssh]\r\n"),
    782 					 escape_char);
    783 				buffer_append(berr, string, strlen(string));
    784 
    785 				/* Restore terminal modes and suspend. */
    786 				client_suspend_self(bin, bout, berr);
    787 
    788 				/* We have been continued. */
    789 				continue;
    790 
    791 			case 'B':
    792 				if (compat20) {
    793 					snprintf(string, sizeof string,
    794 						gettext("%cB [sent break]\r\n"),
    795 						escape_char);
    796 					buffer_append(berr, string,
    797 						strlen(string));
    798 					channel_request_start(session_ident,
    799 						"break", 0);
    800 					packet_put_int(1000);
    801 					packet_send();
    802 				}
    803 				continue;
    804 
    805 			case 'R':
    806 				if (compat20) {
    807 					if (datafellows & SSH_BUG_NOREKEY)
    808 						log("Server does not support re-keying");
    809 					else
    810 						need_rekeying = 1;
    811 				}
    812 				continue;
    813 
    814 			case '&':
    815 				/*
    816 				 * Detach the program (continue to serve connections,
    817 				 * but put in background and no more new connections).
    818 				 */
    819 				/* Restore tty modes. */
    820 				leave_raw_mode();
    821 
    822 				/* Stop listening for new connections. */
    823 				channel_stop_listening();
    824 
    825 				snprintf(string, sizeof string,
    826 					 gettext("%c& [backgrounded]\n"),
    827 					 escape_char);
    828 				buffer_append(berr, string, strlen(string));
    829 
    830 				client_daemonize();
    831 
    832 				/* The child continues serving connections. */
    833 				if (compat20) {
    834 					buffer_append(bin, "\004", 1);
    835 					/* fake EOF on stdin */
    836 					return -1;
    837 				} else if (!stdin_eof) {
    838 					/*
    839 					 * Sending SSH_CMSG_EOF alone does not always appear
    840 					 * to be enough.  So we try to send an EOF character
    841 					 * first.
    842 					 */
    843 					packet_start(SSH_CMSG_STDIN_DATA);
    844 					packet_put_string("\004", 1);
    845 					packet_send();
    846 					/* Close stdin. */
    847 					stdin_eof = 1;
    848 					if (buffer_len(bin) == 0) {
    849 						packet_start(SSH_CMSG_EOF);
    850 						packet_send();
    851 					}
    852 				}
    853 				continue;
    854 
    855 			case '?':
    856 				snprintf(string, sizeof string, gettext(
    857 "%c?\r\n\
    858 Supported escape sequences:\r\n\
    859 %c.  - terminate connection\r\n\
    860 %cB  - send break\r\n\
    861 %cC  - open a command line\r\n\
    862 %cR  - Request rekey (SSH protocol 2 only)\r\n\
    863 %c^Z - suspend ssh\r\n\
    864 %c#  - list forwarded connections\r\n\
    865 %c&  - background ssh (when waiting for connections to terminate)\r\n\
    866 %c?  - this message\r\n\
    867 %c%c  - send the escape character by typing it twice\r\n\
    868 (Note that escapes are only recognized immediately after newline.)\r\n"),
    869 				    escape_char, escape_char, escape_char, escape_char,
    870 				    escape_char, escape_char, escape_char, escape_char,
    871 				    escape_char, escape_char);
    872 				buffer_append(berr, string, strlen(string));
    873 				continue;
    874 
    875 			case '#':
    876 				snprintf(string, sizeof string, "%c#\r\n", escape_char);
    877 				buffer_append(berr, string, strlen(string));
    878 				s = channel_open_message();
    879 				buffer_append(berr, s, strlen(s));
    880 				xfree(s);
    881 				continue;
    882 
    883 			case 'C':
    884 				process_cmdline();
    885 				continue;
    886 
    887 			default:
    888 				if (ch != escape_char) {
    889 					buffer_put_char(bin, escape_char);
    890 					bytes++;
    891 				}
    892 				/* Escaped characters fall through here */
    893 				break;
    894 			}
    895 		} else {
    896 			/*
    897 			 * The previous character was not an escape char. Check if this
    898 			 * is an escape.
    899 			 */
    900 			if (last_was_cr && ch == escape_char) {
    901 				/* It is. Set the flag and continue to next character. */
    902 				escape_pending = 1;
    903 				continue;
    904 			}
    905 		}
    906 
    907 		/*
    908 		 * Normal character.  Record whether it was a newline,
    909 		 * and append it to the buffer.
    910 		 */
    911 		last_was_cr = (ch == '\r' || ch == '\n');
    912 		buffer_put_char(bin, ch);
    913 		bytes++;
    914 	}
    915 	return bytes;
    916 }
    917 
    918 static void
    919 client_process_input(fd_set * readset)
    920 {
    921 	int len;
    922 	char buf[8192];
    923 
    924 	/* Read input from stdin. */
    925 	if (FD_ISSET(fileno(stdin), readset)) {
    926 		/* Read as much as possible. */
    927 		len = read(fileno(stdin), buf, sizeof(buf));
    928 		if (len < 0 && (errno == EAGAIN || errno == EINTR))
    929 			return;		/* we'll try again later */
    930 		if (len <= 0) {
    931 			/*
    932 			 * Received EOF or error.  They are treated
    933 			 * similarly, except that an error message is printed
    934 			 * if it was an error condition.
    935 			 */
    936 			if (len < 0) {
    937 				snprintf(buf, sizeof buf, "read: %.100s\r\n", strerror(errno));
    938 				buffer_append(&stderr_buffer, buf, strlen(buf));
    939 			}
    940 			/* Mark that we have seen EOF. */
    941 			stdin_eof = 1;
    942 			/*
    943 			 * Send an EOF message to the server unless there is
    944 			 * data in the buffer.  If there is data in the
    945 			 * buffer, no message will be sent now.  Code
    946 			 * elsewhere will send the EOF when the buffer
    947 			 * becomes empty if stdin_eof is set.
    948 			 */
    949 			if (buffer_len(&stdin_buffer) == 0) {
    950 				packet_start(SSH_CMSG_EOF);
    951 				packet_send();
    952 			}
    953 		} else if (escape_char == SSH_ESCAPECHAR_NONE) {
    954 			/*
    955 			 * Normal successful read, and no escape character.
    956 			 * Just append the data to buffer.
    957 			 */
    958 			buffer_append(&stdin_buffer, buf, len);
    959 		} else {
    960 			/*
    961 			 * Normal, successful read.  But we have an escape character
    962 			 * and have to process the characters one by one.
    963 			 */
    964 			if (process_escapes(&stdin_buffer, &stdout_buffer,
    965 			    &stderr_buffer, buf, len) == -1)
    966 				return;
    967 		}
    968 	}
    969 }
    970 
    971 static void
    972 client_process_output(fd_set * writeset)
    973 {
    974 	int len;
    975 	char buf[100];
    976 
    977 	/* Write buffered output to stdout. */
    978 	if (FD_ISSET(fileno(stdout), writeset)) {
    979 		/* Write as much data as possible. */
    980 		len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
    981 		    buffer_len(&stdout_buffer));
    982 		if (len <= 0) {
    983 			if (errno == EINTR || errno == EAGAIN)
    984 				len = 0;
    985 			else {
    986 				/*
    987 				 * An error or EOF was encountered.  Put an
    988 				 * error message to stderr buffer.
    989 				 */
    990 				snprintf(buf, sizeof buf, "write stdout: %.50s\r\n", strerror(errno));
    991 				buffer_append(&stderr_buffer, buf, strlen(buf));
    992 				quit_pending = 1;
    993 				return;
    994 			}
    995 		}
    996 		/* Consume printed data from the buffer. */
    997 		buffer_consume(&stdout_buffer, len);
    998 		stdout_bytes += len;
    999 	}
   1000 	/* Write buffered output to stderr. */
   1001 	if (FD_ISSET(fileno(stderr), writeset)) {
   1002 		/* Write as much data as possible. */
   1003 		len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
   1004 		    buffer_len(&stderr_buffer));
   1005 		if (len <= 0) {
   1006 			if (errno == EINTR || errno == EAGAIN)
   1007 				len = 0;
   1008 			else {
   1009 				/* EOF or error, but can't even print error message. */
   1010 				quit_pending = 1;
   1011 				return;
   1012 			}
   1013 		}
   1014 		/* Consume printed characters from the buffer. */
   1015 		buffer_consume(&stderr_buffer, len);
   1016 		stderr_bytes += len;
   1017 	}
   1018 }
   1019 
   1020 /*
   1021  * Get packets from the connection input buffer, and process them as long as
   1022  * there are packets available.
   1023  *
   1024  * Any unknown packets received during the actual
   1025  * session cause the session to terminate.  This is
   1026  * intended to make debugging easier since no
   1027  * confirmations are sent.  Any compatible protocol
   1028  * extensions must be negotiated during the
   1029  * preparatory phase.
   1030  */
   1031 
   1032 static void
   1033 client_process_buffered_input_packets(void)
   1034 {
   1035 	dispatch_run(DISPATCH_NONBLOCK, &quit_pending, compat20 ? xxx_kex : NULL);
   1036 }
   1037 
   1038 /* scan buf[] for '~' before sending data to the peer */
   1039 
   1040 static int
   1041 simple_escape_filter(Channel *c, char *buf, int len)
   1042 {
   1043 	/* XXX we assume c->extended is writeable */
   1044 	return process_escapes(&c->input, &c->output, &c->extended, buf, len);
   1045 }
   1046 
   1047 static void
   1048 client_channel_closed(int id, void *arg)
   1049 {
   1050 	if (id != session_ident)
   1051 		error("client_channel_closed: id %d != session_ident %d",
   1052 		    id, session_ident);
   1053 	channel_cancel_cleanup(id);
   1054 	session_closed = 1;
   1055 	if (in_raw_mode())
   1056 		leave_raw_mode();
   1057 }
   1058 
   1059 /*
   1060  * Implements the interactive session with the server.  This is called after
   1061  * the user has been authenticated, and a command has been started on the
   1062  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
   1063  * used as an escape character for terminating or suspending the session.
   1064  */
   1065 
   1066 int
   1067 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
   1068 {
   1069 	fd_set *readset = NULL, *writeset = NULL;
   1070 	double start_time, total_time;
   1071 	int max_fd = 0, max_fd2 = 0, len, rekeying = 0, nalloc = 0;
   1072 	char buf[100];
   1073 
   1074 	debug("Entering interactive session.");
   1075 
   1076 	start_time = get_current_time();
   1077 
   1078 	/* Initialize variables. */
   1079 	escape_pending = 0;
   1080 	last_was_cr = 1;
   1081 	exit_status = -1;
   1082 	stdin_eof = 0;
   1083 	buffer_high = 64 * 1024;
   1084 	connection_in = packet_get_connection_in();
   1085 	connection_out = packet_get_connection_out();
   1086 	max_fd = MAX(connection_in, connection_out);
   1087 
   1088 	if (!compat20) {
   1089 		/* enable nonblocking unless tty */
   1090 		if (!isatty(fileno(stdin)))
   1091 			set_nonblock(fileno(stdin));
   1092 		if (!isatty(fileno(stdout)))
   1093 			set_nonblock(fileno(stdout));
   1094 		if (!isatty(fileno(stderr)))
   1095 			set_nonblock(fileno(stderr));
   1096 		max_fd = MAX(max_fd, fileno(stdin));
   1097 		max_fd = MAX(max_fd, fileno(stdout));
   1098 		max_fd = MAX(max_fd, fileno(stderr));
   1099 	}
   1100 	stdin_bytes = 0;
   1101 	stdout_bytes = 0;
   1102 	stderr_bytes = 0;
   1103 	quit_pending = 0;
   1104 	escape_char = escape_char_arg;
   1105 
   1106 	/* Initialize buffers. */
   1107 	buffer_init(&stdin_buffer);
   1108 	buffer_init(&stdout_buffer);
   1109 	buffer_init(&stderr_buffer);
   1110 
   1111 	client_init_dispatch();
   1112 
   1113 	/*
   1114 	 * Set signal handlers to restore non-blocking mode, but
   1115 	 * don't overwrite SIG_IGN - matches behavious from rsh(1).
   1116 	 */
   1117 	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
   1118 		signal(SIGINT, signal_handler);
   1119 	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
   1120 		signal(SIGQUIT, signal_handler);
   1121 	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)