xref: /freebsd/crypto/openssh/clientloop.c (revision 4436b51dff5736e74da464946049ea6899a88938)
1 /* $OpenBSD: clientloop.c,v 1.258 2014/02/02 03:44:31 djm Exp $ */
2 /* $FreeBSD$ */
3 /*
4  * Author: Tatu Ylonen <ylo@cs.hut.fi>
5  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6  *                    All rights reserved
7  * The main loop for the interactive session (client side).
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  *
38  *
39  * SSH2 support added by Markus Friedl.
40  * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  *
51  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
52  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
53  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
54  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
55  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
60  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61  */
62 
63 #include "includes.h"
64 __RCSID("$FreeBSD$");
65 
66 #include <sys/types.h>
67 #include <sys/ioctl.h>
68 #include <sys/param.h>
69 #ifdef HAVE_SYS_STAT_H
70 # include <sys/stat.h>
71 #endif
72 #ifdef HAVE_SYS_TIME_H
73 # include <sys/time.h>
74 #endif
75 #include <sys/socket.h>
76 
77 #include <ctype.h>
78 #include <errno.h>
79 #ifdef HAVE_PATHS_H
80 #include <paths.h>
81 #endif
82 #include <signal.h>
83 #include <stdarg.h>
84 #include <stdio.h>
85 #include <stdlib.h>
86 #include <string.h>
87 #include <termios.h>
88 #include <pwd.h>
89 #include <unistd.h>
90 
91 #include "openbsd-compat/sys-queue.h"
92 #include "xmalloc.h"
93 #include "ssh.h"
94 #include "ssh1.h"
95 #include "ssh2.h"
96 #include "packet.h"
97 #include "buffer.h"
98 #include "compat.h"
99 #include "channels.h"
100 #include "dispatch.h"
101 #include "key.h"
102 #include "cipher.h"
103 #include "kex.h"
104 #include "log.h"
105 #include "readconf.h"
106 #include "clientloop.h"
107 #include "sshconnect.h"
108 #include "authfd.h"
109 #include "atomicio.h"
110 #include "sshpty.h"
111 #include "misc.h"
112 #include "match.h"
113 #include "msg.h"
114 #include "roaming.h"
115 
116 /* import options */
117 extern Options options;
118 
119 /* Flag indicating that stdin should be redirected from /dev/null. */
120 extern int stdin_null_flag;
121 
122 /* Flag indicating that no shell has been requested */
123 extern int no_shell_flag;
124 
125 /* Control socket */
126 extern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
127 
128 /*
129  * Name of the host we are connecting to.  This is the name given on the
130  * command line, or the HostName specified for the user-supplied name in a
131  * configuration file.
132  */
133 extern char *host;
134 
135 /*
136  * Flag to indicate that we have received a window change signal which has
137  * not yet been processed.  This will cause a message indicating the new
138  * window size to be sent to the server a little later.  This is volatile
139  * because this is updated in a signal handler.
140  */
141 static volatile sig_atomic_t received_window_change_signal = 0;
142 static volatile sig_atomic_t received_signal = 0;
143 
144 /* Flag indicating whether the user's terminal is in non-blocking mode. */
145 static int in_non_blocking_mode = 0;
146 
147 /* Time when backgrounded control master using ControlPersist should exit */
148 static time_t control_persist_exit_time = 0;
149 
150 /* Common data for the client loop code. */
151 volatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
152 static int escape_char1;	/* Escape character. (proto1 only) */
153 static int escape_pending1;	/* Last character was an escape (proto1 only) */
154 static int last_was_cr;		/* Last character was a newline. */
155 static int exit_status;		/* Used to store the command exit status. */
156 static int stdin_eof;		/* EOF has been encountered on stderr. */
157 static Buffer stdin_buffer;	/* Buffer for stdin data. */
158 static Buffer stdout_buffer;	/* Buffer for stdout data. */
159 static Buffer stderr_buffer;	/* Buffer for stderr data. */
160 static u_int buffer_high;	/* Soft max buffer size. */
161 static int connection_in;	/* Connection to server (input). */
162 static int connection_out;	/* Connection to server (output). */
163 static int need_rekeying;	/* Set to non-zero if rekeying is requested. */
164 static int session_closed;	/* In SSH2: login session closed. */
165 static int x11_refuse_time;	/* If >0, refuse x11 opens after this time. */
166 
167 static void client_init_dispatch(void);
168 int	session_ident = -1;
169 
170 int	session_resumed = 0;
171 
172 /* Track escape per proto2 channel */
173 struct escape_filter_ctx {
174 	int escape_pending;
175 	int escape_char;
176 };
177 
178 /* Context for channel confirmation replies */
179 struct channel_reply_ctx {
180 	const char *request_type;
181 	int id;
182 	enum confirm_action action;
183 };
184 
185 /* Global request success/failure callbacks */
186 struct global_confirm {
187 	TAILQ_ENTRY(global_confirm) entry;
188 	global_confirm_cb *cb;
189 	void *ctx;
190 	int ref_count;
191 };
192 TAILQ_HEAD(global_confirms, global_confirm);
193 static struct global_confirms global_confirms =
194     TAILQ_HEAD_INITIALIZER(global_confirms);
195 
196 /*XXX*/
197 extern Kex *xxx_kex;
198 
199 void ssh_process_session2_setup(int, int, int, Buffer *);
200 
201 /* Restores stdin to blocking mode. */
202 
203 static void
204 leave_non_blocking(void)
205 {
206 	if (in_non_blocking_mode) {
207 		unset_nonblock(fileno(stdin));
208 		in_non_blocking_mode = 0;
209 	}
210 }
211 
212 /* Puts stdin terminal in non-blocking mode. */
213 
214 static void
215 enter_non_blocking(void)
216 {
217 	in_non_blocking_mode = 1;
218 	set_nonblock(fileno(stdin));
219 }
220 
221 /*
222  * Signal handler for the window change signal (SIGWINCH).  This just sets a
223  * flag indicating that the window has changed.
224  */
225 /*ARGSUSED */
226 static void
227 window_change_handler(int sig)
228 {
229 	received_window_change_signal = 1;
230 	signal(SIGWINCH, window_change_handler);
231 }
232 
233 /*
234  * Signal handler for signals that cause the program to terminate.  These
235  * signals must be trapped to restore terminal modes.
236  */
237 /*ARGSUSED */
238 static void
239 signal_handler(int sig)
240 {
241 	received_signal = sig;
242 	quit_pending = 1;
243 }
244 
245 /*
246  * Returns current time in seconds from Jan 1, 1970 with the maximum
247  * available resolution.
248  */
249 
250 static double
251 get_current_time(void)
252 {
253 	struct timeval tv;
254 	gettimeofday(&tv, NULL);
255 	return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
256 }
257 
258 /*
259  * Sets control_persist_exit_time to the absolute time when the
260  * backgrounded control master should exit due to expiry of the
261  * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
262  * control master process, or if there is no ControlPersist timeout.
263  */
264 static void
265 set_control_persist_exit_time(void)
266 {
267 	if (muxserver_sock == -1 || !options.control_persist
268 	    || options.control_persist_timeout == 0) {
269 		/* not using a ControlPersist timeout */
270 		control_persist_exit_time = 0;
271 	} else if (channel_still_open()) {
272 		/* some client connections are still open */
273 		if (control_persist_exit_time > 0)
274 			debug2("%s: cancel scheduled exit", __func__);
275 		control_persist_exit_time = 0;
276 	} else if (control_persist_exit_time <= 0) {
277 		/* a client connection has recently closed */
278 		control_persist_exit_time = monotime() +
279 			(time_t)options.control_persist_timeout;
280 		debug2("%s: schedule exit in %d seconds", __func__,
281 		    options.control_persist_timeout);
282 	}
283 	/* else we are already counting down to the timeout */
284 }
285 
286 #define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
287 static int
288 client_x11_display_valid(const char *display)
289 {
290 	size_t i, dlen;
291 
292 	dlen = strlen(display);
293 	for (i = 0; i < dlen; i++) {
294 		if (!isalnum((u_char)display[i]) &&
295 		    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
296 			debug("Invalid character '%c' in DISPLAY", display[i]);
297 			return 0;
298 		}
299 	}
300 	return 1;
301 }
302 
303 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
304 void
305 client_x11_get_proto(const char *display, const char *xauth_path,
306     u_int trusted, u_int timeout, char **_proto, char **_data)
307 {
308 	char cmd[1024];
309 	char line[512];
310 	char xdisplay[512];
311 	static char proto[512], data[512];
312 	FILE *f;
313 	int got_data = 0, generated = 0, do_unlink = 0, i;
314 	char *xauthdir, *xauthfile;
315 	struct stat st;
316 	u_int now;
317 
318 	xauthdir = xauthfile = NULL;
319 	*_proto = proto;
320 	*_data = data;
321 	proto[0] = data[0] = '\0';
322 
323 	if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
324 		debug("No xauth program.");
325 	} else if (!client_x11_display_valid(display)) {
326 		logit("DISPLAY '%s' invalid, falling back to fake xauth data",
327 		    display);
328 	} else {
329 		if (display == NULL) {
330 			debug("x11_get_proto: DISPLAY not set");
331 			return;
332 		}
333 		/*
334 		 * Handle FamilyLocal case where $DISPLAY does
335 		 * not match an authorization entry.  For this we
336 		 * just try "xauth list unix:displaynum.screennum".
337 		 * XXX: "localhost" match to determine FamilyLocal
338 		 *      is not perfect.
339 		 */
340 		if (strncmp(display, "localhost:", 10) == 0) {
341 			snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
342 			    display + 10);
343 			display = xdisplay;
344 		}
345 		if (trusted == 0) {
346 			xauthdir = xmalloc(MAXPATHLEN);
347 			xauthfile = xmalloc(MAXPATHLEN);
348 			mktemp_proto(xauthdir, MAXPATHLEN);
349 			if (mkdtemp(xauthdir) != NULL) {
350 				do_unlink = 1;
351 				snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
352 				    xauthdir);
353 				snprintf(cmd, sizeof(cmd),
354 				    "%s -f %s generate %s " SSH_X11_PROTO
355 				    " untrusted timeout %u 2>" _PATH_DEVNULL,
356 				    xauth_path, xauthfile, display, timeout);
357 				debug2("x11_get_proto: %s", cmd);
358 				if (system(cmd) == 0)
359 					generated = 1;
360 				if (x11_refuse_time == 0) {
361 					now = monotime() + 1;
362 					if (UINT_MAX - timeout < now)
363 						x11_refuse_time = UINT_MAX;
364 					else
365 						x11_refuse_time = now + timeout;
366 				}
367 			}
368 		}
369 
370 		/*
371 		 * When in untrusted mode, we read the cookie only if it was
372 		 * successfully generated as an untrusted one in the step
373 		 * above.
374 		 */
375 		if (trusted || generated) {
376 			snprintf(cmd, sizeof(cmd),
377 			    "%s %s%s list %s 2>" _PATH_DEVNULL,
378 			    xauth_path,
379 			    generated ? "-f " : "" ,
380 			    generated ? xauthfile : "",
381 			    display);
382 			debug2("x11_get_proto: %s", cmd);
383 			f = popen(cmd, "r");
384 			if (f && fgets(line, sizeof(line), f) &&
385 			    sscanf(line, "%*s %511s %511s", proto, data) == 2)
386 				got_data = 1;
387 			if (f)
388 				pclose(f);
389 		} else
390 			error("Warning: untrusted X11 forwarding setup failed: "
391 			    "xauth key data not generated");
392 	}
393 
394 	if (do_unlink) {
395 		unlink(xauthfile);
396 		rmdir(xauthdir);
397 	}
398 	free(xauthdir);
399 	free(xauthfile);
400 
401 	/*
402 	 * If we didn't get authentication data, just make up some
403 	 * data.  The forwarding code will check the validity of the
404 	 * response anyway, and substitute this data.  The X11
405 	 * server, however, will ignore this fake data and use
406 	 * whatever authentication mechanisms it was using otherwise
407 	 * for the local connection.
408 	 */
409 	if (!got_data) {
410 		u_int32_t rnd = 0;
411 
412 		logit("Warning: No xauth data; "
413 		    "using fake authentication data for X11 forwarding.");
414 		strlcpy(proto, SSH_X11_PROTO, sizeof proto);
415 		for (i = 0; i < 16; i++) {
416 			if (i % 4 == 0)
417 				rnd = arc4random();
418 			snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
419 			    rnd & 0xff);
420 			rnd >>= 8;
421 		}
422 	}
423 }
424 
425 /*
426  * This is called when the interactive is entered.  This checks if there is
427  * an EOF coming on stdin.  We must check this explicitly, as select() does
428  * not appear to wake up when redirecting from /dev/null.
429  */
430 
431 static void
432 client_check_initial_eof_on_stdin(void)
433 {
434 	int len;
435 	char buf[1];
436 
437 	/*
438 	 * If standard input is to be "redirected from /dev/null", we simply
439 	 * mark that we have seen an EOF and send an EOF message to the
440 	 * server. Otherwise, we try to read a single character; it appears
441 	 * that for some files, such /dev/null, select() never wakes up for
442 	 * read for this descriptor, which means that we never get EOF.  This
443 	 * way we will get the EOF if stdin comes from /dev/null or similar.
444 	 */
445 	if (stdin_null_flag) {
446 		/* Fake EOF on stdin. */
447 		debug("Sending eof.");
448 		stdin_eof = 1;
449 		packet_start(SSH_CMSG_EOF);
450 		packet_send();
451 	} else {
452 		enter_non_blocking();
453 
454 		/* Check for immediate EOF on stdin. */
455 		len = read(fileno(stdin), buf, 1);
456 		if (len == 0) {
457 			/*
458 			 * EOF.  Record that we have seen it and send
459 			 * EOF to server.
460 			 */
461 			debug("Sending eof.");
462 			stdin_eof = 1;
463 			packet_start(SSH_CMSG_EOF);
464 			packet_send();
465 		} else if (len > 0) {
466 			/*
467 			 * Got data.  We must store the data in the buffer,
468 			 * and also process it as an escape character if
469 			 * appropriate.
470 			 */
471 			if ((u_char) buf[0] == escape_char1)
472 				escape_pending1 = 1;
473 			else
474 				buffer_append(&stdin_buffer, buf, 1);
475 		}
476 		leave_non_blocking();
477 	}
478 }
479 
480 
481 /*
482  * Make packets from buffered stdin data, and buffer them for sending to the
483  * connection.
484  */
485 
486 static void
487 client_make_packets_from_stdin_data(void)
488 {
489 	u_int len;
490 
491 	/* Send buffered stdin data to the server. */
492 	while (buffer_len(&stdin_buffer) > 0 &&
493 	    packet_not_very_much_data_to_write()) {
494 		len = buffer_len(&stdin_buffer);
495 		/* Keep the packets at reasonable size. */
496 		if (len > packet_get_maxsize())
497 			len = packet_get_maxsize();
498 		packet_start(SSH_CMSG_STDIN_DATA);
499 		packet_put_string(buffer_ptr(&stdin_buffer), len);
500 		packet_send();
501 		buffer_consume(&stdin_buffer, len);
502 		/* If we have a pending EOF, send it now. */
503 		if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
504 			packet_start(SSH_CMSG_EOF);
505 			packet_send();
506 		}
507 	}
508 }
509 
510 /*
511  * Checks if the client window has changed, and sends a packet about it to
512  * the server if so.  The actual change is detected elsewhere (by a software
513  * interrupt on Unix); this just checks the flag and sends a message if
514  * appropriate.
515  */
516 
517 static void
518 client_check_window_change(void)
519 {
520 	struct winsize ws;
521 
522 	if (! received_window_change_signal)
523 		return;
524 	/** XXX race */
525 	received_window_change_signal = 0;
526 
527 	debug2("client_check_window_change: changed");
528 
529 	if (compat20) {
530 		channel_send_window_changes();
531 	} else {
532 		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
533 			return;
534 		packet_start(SSH_CMSG_WINDOW_SIZE);
535 		packet_put_int((u_int)ws.ws_row);
536 		packet_put_int((u_int)ws.ws_col);
537 		packet_put_int((u_int)ws.ws_xpixel);
538 		packet_put_int((u_int)ws.ws_ypixel);
539 		packet_send();
540 	}
541 }
542 
543 static void
544 client_global_request_reply(int type, u_int32_t seq, void *ctxt)
545 {
546 	struct global_confirm *gc;
547 
548 	if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
549 		return;
550 	if (gc->cb != NULL)
551 		gc->cb(type, seq, gc->ctx);
552 	if (--gc->ref_count <= 0) {
553 		TAILQ_REMOVE(&global_confirms, gc, entry);
554 		explicit_bzero(gc, sizeof(*gc));
555 		free(gc);
556 	}
557 
558 	packet_set_alive_timeouts(0);
559 }
560 
561 static void
562 server_alive_check(void)
563 {
564 	if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
565 		logit("Timeout, server %s not responding.", host);
566 		cleanup_exit(255);
567 	}
568 	packet_start(SSH2_MSG_GLOBAL_REQUEST);
569 	packet_put_cstring("keepalive@openssh.com");
570 	packet_put_char(1);     /* boolean: want reply */
571 	packet_send();
572 	/* Insert an empty placeholder to maintain ordering */
573 	client_register_global_confirm(NULL, NULL);
574 }
575 
576 /*
577  * Waits until the client can do something (some data becomes available on
578  * one of the file descriptors).
579  */
580 static void
581 client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
582     int *maxfdp, u_int *nallocp, int rekeying)
583 {
584 	struct timeval tv, *tvp;
585 	int timeout_secs;
586 	time_t minwait_secs = 0, server_alive_time = 0, now = monotime();
587 	int ret;
588 
589 	/* Add any selections by the channel mechanism. */
590 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
591 	    &minwait_secs, rekeying);
592 
593 	if (!compat20) {
594 		/* Read from the connection, unless our buffers are full. */
595 		if (buffer_len(&stdout_buffer) < buffer_high &&
596 		    buffer_len(&stderr_buffer) < buffer_high &&
597 		    channel_not_very_much_buffered_data())
598 			FD_SET(connection_in, *readsetp);
599 		/*
600 		 * Read from stdin, unless we have seen EOF or have very much
601 		 * buffered data to send to the server.
602 		 */
603 		if (!stdin_eof && packet_not_very_much_data_to_write())
604 			FD_SET(fileno(stdin), *readsetp);
605 
606 		/* Select stdout/stderr if have data in buffer. */
607 		if (buffer_len(&stdout_buffer) > 0)
608 			FD_SET(fileno(stdout), *writesetp);
609 		if (buffer_len(&stderr_buffer) > 0)
610 			FD_SET(fileno(stderr), *writesetp);
611 	} else {
612 		/* channel_prepare_select could have closed the last channel */
613 		if (session_closed && !channel_still_open() &&
614 		    !packet_have_data_to_write()) {
615 			/* clear mask since we did not call select() */
616 			memset(*readsetp, 0, *nallocp);
617 			memset(*writesetp, 0, *nallocp);
618 			return;
619 		} else {
620 			FD_SET(connection_in, *readsetp);
621 		}
622 	}
623 
624 	/* Select server connection if have data to write to the server. */
625 	if (packet_have_data_to_write())
626 		FD_SET(connection_out, *writesetp);
627 
628 	/*
629 	 * Wait for something to happen.  This will suspend the process until
630 	 * some selected descriptor can be read, written, or has some other
631 	 * event pending, or a timeout expires.
632 	 */
633 
634 	timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
635 	if (options.server_alive_interval > 0 && compat20) {
636 		timeout_secs = options.server_alive_interval;
637 		server_alive_time = now + options.server_alive_interval;
638 	}
639 	if (options.rekey_interval > 0 && compat20 && !rekeying)
640 		timeout_secs = MIN(timeout_secs, packet_get_rekey_timeout());
641 	set_control_persist_exit_time();
642 	if (control_persist_exit_time > 0) {
643 		timeout_secs = MIN(timeout_secs,
644 			control_persist_exit_time - now);
645 		if (timeout_secs < 0)
646 			timeout_secs = 0;
647 	}
648 	if (minwait_secs != 0)
649 		timeout_secs = MIN(timeout_secs, (int)minwait_secs);
650 	if (timeout_secs == INT_MAX)
651 		tvp = NULL;
652 	else {
653 		tv.tv_sec = timeout_secs;
654 		tv.tv_usec = 0;
655 		tvp = &tv;
656 	}
657 
658 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
659 	if (ret < 0) {
660 		char buf[100];
661 
662 		/*
663 		 * We have to clear the select masks, because we return.
664 		 * We have to return, because the mainloop checks for the flags
665 		 * set by the signal handlers.
666 		 */
667 		memset(*readsetp, 0, *nallocp);
668 		memset(*writesetp, 0, *nallocp);
669 
670 		if (errno == EINTR)
671 			return;
672 		/* Note: we might still have data in the buffers. */
673 		snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
674 		buffer_append(&stderr_buffer, buf, strlen(buf));
675 		quit_pending = 1;
676 	} else if (ret == 0) {
677 		/*
678 		 * Timeout.  Could have been either keepalive or rekeying.
679 		 * Keepalive we check here, rekeying is checked in clientloop.
680 		 */
681 		if (server_alive_time != 0 && server_alive_time <= monotime())
682 			server_alive_check();
683 	}
684 
685 }
686 
687 static void
688 client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
689 {
690 	/* Flush stdout and stderr buffers. */
691 	if (buffer_len(bout) > 0)
692 		atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
693 		    buffer_len(bout));
694 	if (buffer_len(berr) > 0)
695 		atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
696 		    buffer_len(berr));
697 
698 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
699 
700 	/*
701 	 * Free (and clear) the buffer to reduce the amount of data that gets
702 	 * written to swap.
703 	 */
704 	buffer_free(bin);
705 	buffer_free(bout);
706 	buffer_free(berr);
707 
708 	/* Send the suspend signal to the program itself. */
709 	kill(getpid(), SIGTSTP);
710 
711 	/* Reset window sizes in case they have changed */
712 	received_window_change_signal = 1;
713 
714 	/* OK, we have been continued by the user. Reinitialize buffers. */
715 	buffer_init(bin);
716 	buffer_init(bout);
717 	buffer_init(berr);
718 
719 	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
720 }
721 
722 static void
723 client_process_net_input(fd_set *readset)
724 {
725 	int len, cont = 0;
726 	char buf[SSH_IOBUFSZ];
727 
728 	/*
729 	 * Read input from the server, and add any such data to the buffer of
730 	 * the packet subsystem.
731 	 */
732 	if (FD_ISSET(connection_in, readset)) {
733 		/* Read as much as possible. */
734 		len = roaming_read(connection_in, buf, sizeof(buf), &cont);
735 		if (len == 0 && cont == 0) {
736 			/*
737 			 * Received EOF.  The remote host has closed the
738 			 * connection.
739 			 */
740 			snprintf(buf, sizeof buf,
741 			    "Connection to %.300s closed by remote host.\r\n",
742 			    host);
743 			buffer_append(&stderr_buffer, buf, strlen(buf));
744 			quit_pending = 1;
745 			return;
746 		}
747 		/*
748 		 * There is a kernel bug on Solaris that causes select to
749 		 * sometimes wake up even though there is no data available.
750 		 */
751 		if (len < 0 &&
752 		    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
753 			len = 0;
754 
755 		if (len < 0) {
756 			/*
757 			 * An error has encountered.  Perhaps there is a
758 			 * network problem.
759 			 */
760 			snprintf(buf, sizeof buf,
761 			    "Read from remote host %.300s: %.100s\r\n",
762 			    host, strerror(errno));
763 			buffer_append(&stderr_buffer, buf, strlen(buf));
764 			quit_pending = 1;
765 			return;
766 		}
767 		packet_process_incoming(buf, len);
768 	}
769 }
770 
771 static void
772 client_status_confirm(int type, Channel *c, void *ctx)
773 {
774 	struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
775 	char errmsg[256];
776 	int tochan;
777 
778 	/*
779 	 * If a TTY was explicitly requested, then a failure to allocate
780 	 * one is fatal.
781 	 */
782 	if (cr->action == CONFIRM_TTY &&
783 	    (options.request_tty == REQUEST_TTY_FORCE ||
784 	    options.request_tty == REQUEST_TTY_YES))
785 		cr->action = CONFIRM_CLOSE;
786 
787 	/* XXX supress on mux _client_ quietmode */
788 	tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
789 	    c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
790 
791 	if (type == SSH2_MSG_CHANNEL_SUCCESS) {
792 		debug2("%s request accepted on channel %d",
793 		    cr->request_type, c->self);
794 	} else if (type == SSH2_MSG_CHANNEL_FAILURE) {
795 		if (tochan) {
796 			snprintf(errmsg, sizeof(errmsg),
797 			    "%s request failed\r\n", cr->request_type);
798 		} else {
799 			snprintf(errmsg, sizeof(errmsg),
800 			    "%s request failed on channel %d",
801 			    cr->request_type, c->self);
802 		}
803 		/* If error occurred on primary session channel, then exit */
804 		if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
805 			fatal("%s", errmsg);
806 		/*
807 		 * If error occurred on mux client, append to
808 		 * their stderr.
809 		 */
810 		if (tochan) {
811 			buffer_append(&c->extended, errmsg,
812 			    strlen(errmsg));
813 		} else
814 			error("%s", errmsg);
815 		if (cr->action == CONFIRM_TTY) {
816 			/*
817 			 * If a TTY allocation error occurred, then arrange
818 			 * for the correct TTY to leave raw mode.
819 			 */
820 			if (c->self == session_ident)
821 				leave_raw_mode(0);
822 			else
823 				mux_tty_alloc_failed(c);
824 		} else if (cr->action == CONFIRM_CLOSE) {
825 			chan_read_failed(c);
826 			chan_write_failed(c);
827 		}
828 	}
829 	free(cr);
830 }
831 
832 static void
833 client_abandon_status_confirm(Channel *c, void *ctx)
834 {
835 	free(ctx);
836 }
837 
838 void
839 client_expect_confirm(int id, const char *request,
840     enum confirm_action action)
841 {
842 	struct channel_reply_ctx *cr = xcalloc(1, sizeof(*cr));
843 
844 	cr->request_type = request;
845 	cr->action = action;
846 
847 	channel_register_status_confirm(id, client_status_confirm,
848 	    client_abandon_status_confirm, cr);
849 }
850 
851 void
852 client_register_global_confirm(global_confirm_cb *cb, void *ctx)
853 {
854 	struct global_confirm *gc, *last_gc;
855 
856 	/* Coalesce identical callbacks */
857 	last_gc = TAILQ_LAST(&global_confirms, global_confirms);
858 	if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
859 		if (++last_gc->ref_count >= INT_MAX)
860 			fatal("%s: last_gc->ref_count = %d",
861 			    __func__, last_gc->ref_count);
862 		return;
863 	}
864 
865 	gc = xcalloc(1, sizeof(*gc));
866 	gc->cb = cb;
867 	gc->ctx = ctx;
868 	gc->ref_count = 1;
869 	TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
870 }
871 
872 static void
873 process_cmdline(void)
874 {
875 	void (*handler)(int);
876 	char *s, *cmd, *cancel_host;
877 	int delete = 0, local = 0, remote = 0, dynamic = 0;
878 	int cancel_port, ok;
879 	Forward fwd;
880 
881 	memset(&fwd, 0, sizeof(fwd));
882 	fwd.listen_host = fwd.connect_host = NULL;
883 
884 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
885 	handler = signal(SIGINT, SIG_IGN);
886 	cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
887 	if (s == NULL)
888 		goto out;
889 	while (isspace((u_char)*s))
890 		s++;
891 	if (*s == '-')
892 		s++;	/* Skip cmdline '-', if any */
893 	if (*s == '\0')
894 		goto out;
895 
896 	if (*s == 'h' || *s == 'H' || *s == '?') {
897 		logit("Commands:");
898 		logit("      -L[bind_address:]port:host:hostport    "
899 		    "Request local forward");
900 		logit("      -R[bind_address:]port:host:hostport    "
901 		    "Request remote forward");
902 		logit("      -D[bind_address:]port                  "
903 		    "Request dynamic forward");
904 		logit("      -KL[bind_address:]port                 "
905 		    "Cancel local forward");
906 		logit("      -KR[bind_address:]port                 "
907 		    "Cancel remote forward");
908 		logit("      -KD[bind_address:]port                 "
909 		    "Cancel dynamic forward");
910 		if (!options.permit_local_command)
911 			goto out;
912 		logit("      !args                                  "
913 		    "Execute local command");
914 		goto out;
915 	}
916 
917 	if (*s == '!' && options.permit_local_command) {
918 		s++;
919 		ssh_local_cmd(s);
920 		goto out;
921 	}
922 
923 	if (*s == 'K') {
924 		delete = 1;
925 		s++;
926 	}
927 	if (*s == 'L')
928 		local = 1;
929 	else if (*s == 'R')
930 		remote = 1;
931 	else if (*s == 'D')
932 		dynamic = 1;
933 	else {
934 		logit("Invalid command.");
935 		goto out;
936 	}
937 
938 	if (delete && !compat20) {
939 		logit("Not supported for SSH protocol version 1.");
940 		goto out;
941 	}
942 
943 	while (isspace((u_char)*++s))
944 		;
945 
946 	/* XXX update list of forwards in options */
947 	if (delete) {
948 		cancel_port = 0;
949 		cancel_host = hpdelim(&s);	/* may be NULL */
950 		if (s != NULL) {
951 			cancel_port = a2port(s);
952 			cancel_host = cleanhostname(cancel_host);
953 		} else {
954 			cancel_port = a2port(cancel_host);
955 			cancel_host = NULL;
956 		}
957 		if (cancel_port <= 0) {
958 			logit("Bad forwarding close port");
959 			goto out;
960 		}
961 		if (remote)
962 			ok = channel_request_rforward_cancel(cancel_host,
963 			    cancel_port) == 0;
964 		else if (dynamic)
965                 	ok = channel_cancel_lport_listener(cancel_host,
966 			    cancel_port, 0, options.gateway_ports) > 0;
967 		else
968                 	ok = channel_cancel_lport_listener(cancel_host,
969 			    cancel_port, CHANNEL_CANCEL_PORT_STATIC,
970 			    options.gateway_ports) > 0;
971 		if (!ok) {
972 			logit("Unkown port forwarding.");
973 			goto out;
974 		}
975 		logit("Canceled forwarding.");
976 	} else {
977 		if (!parse_forward(&fwd, s, dynamic, remote)) {
978 			logit("Bad forwarding specification.");
979 			goto out;
980 		}
981 		if (local || dynamic) {
982 			if (!channel_setup_local_fwd_listener(fwd.listen_host,
983 			    fwd.listen_port, fwd.connect_host,
984 			    fwd.connect_port, options.gateway_ports)) {
985 				logit("Port forwarding failed.");
986 				goto out;
987 			}
988 		} else {
989 			if (channel_request_remote_forwarding(fwd.listen_host,
990 			    fwd.listen_port, fwd.connect_host,
991 			    fwd.connect_port) < 0) {
992 				logit("Port forwarding failed.");
993 				goto out;
994 			}
995 		}
996 		logit("Forwarding port.");
997 	}
998 
999 out:
1000 	signal(SIGINT, handler);
1001 	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1002 	free(cmd);
1003 	free(fwd.listen_host);
1004 	free(fwd.connect_host);
1005 }
1006 
1007 /* reasons to suppress output of an escape command in help output */
1008 #define SUPPRESS_NEVER		0	/* never suppress, always show */
1009 #define SUPPRESS_PROTO1		1	/* don't show in protocol 1 sessions */
1010 #define SUPPRESS_MUXCLIENT	2	/* don't show in mux client sessions */
1011 #define SUPPRESS_MUXMASTER	4	/* don't show in mux master sessions */
1012 #define SUPPRESS_SYSLOG		8	/* don't show when logging to syslog */
1013 struct escape_help_text {
1014 	const char *cmd;
1015 	const char *text;
1016 	unsigned int flags;
1017 };
1018 static struct escape_help_text esc_txt[] = {
1019     {".",  "terminate session", SUPPRESS_MUXMASTER},
1020     {".",  "terminate connection (and any multiplexed sessions)",
1021 	SUPPRESS_MUXCLIENT},
1022     {"B",  "send a BREAK to the remote system", SUPPRESS_PROTO1},
1023     {"C",  "open a command line", SUPPRESS_MUXCLIENT},
1024     {"R",  "request rekey", SUPPRESS_PROTO1},
1025     {"V/v",  "decrease/increase verbosity (LogLevel)", SUPPRESS_MUXCLIENT},
1026     {"^Z", "suspend ssh", SUPPRESS_MUXCLIENT},
1027     {"#",  "list forwarded connections", SUPPRESS_NEVER},
1028     {"&",  "background ssh (when waiting for connections to terminate)",
1029 	SUPPRESS_MUXCLIENT},
1030     {"?", "this message", SUPPRESS_NEVER},
1031 };
1032 
1033 static void
1034 print_escape_help(Buffer *b, int escape_char, int protocol2, int mux_client,
1035     int using_stderr)
1036 {
1037 	unsigned int i, suppress_flags;
1038 	char string[1024];
1039 
1040 	snprintf(string, sizeof string, "%c?\r\n"
1041 	    "Supported escape sequences:\r\n", escape_char);
1042 	buffer_append(b, string, strlen(string));
1043 
1044 	suppress_flags = (protocol2 ? 0 : SUPPRESS_PROTO1) |
1045 	    (mux_client ? SUPPRESS_MUXCLIENT : 0) |
1046 	    (mux_client ? 0 : SUPPRESS_MUXMASTER) |
1047 	    (using_stderr ? 0 : SUPPRESS_SYSLOG);
1048 
1049 	for (i = 0; i < sizeof(esc_txt)/sizeof(esc_txt[0]); i++) {
1050 		if (esc_txt[i].flags & suppress_flags)
1051 			continue;
1052 		snprintf(string, sizeof string, " %c%-3s - %s\r\n",
1053 		    escape_char, esc_txt[i].cmd, esc_txt[i].text);
1054 		buffer_append(b, string, strlen(string));
1055 	}
1056 
1057 	snprintf(string, sizeof string,
1058 	    " %c%c   - send the escape character by typing it twice\r\n"
1059 	    "(Note that escapes are only recognized immediately after "
1060 	    "newline.)\r\n", escape_char, escape_char);
1061 	buffer_append(b, string, strlen(string));
1062 }
1063 
1064 /*
1065  * Process the characters one by one, call with c==NULL for proto1 case.
1066  */
1067 static int
1068 process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1069     char *buf, int len)
1070 {
1071 	char string[1024];
1072 	pid_t pid;
1073 	int bytes = 0;
1074 	u_int i;
1075 	u_char ch;
1076 	char *s;
1077 	int *escape_pendingp, escape_char;
1078 	struct escape_filter_ctx *efc;
1079 
1080 	if (c == NULL) {
1081 		escape_pendingp = &escape_pending1;
1082 		escape_char = escape_char1;
1083 	} else {
1084 		if (c->filter_ctx == NULL)
1085 			return 0;
1086 		efc = (struct escape_filter_ctx *)c->filter_ctx;
1087 		escape_pendingp = &efc->escape_pending;
1088 		escape_char = efc->escape_char;
1089 	}
1090 
1091 	if (len <= 0)
1092 		return (0);
1093 
1094 	for (i = 0; i < (u_int)len; i++) {
1095 		/* Get one character at a time. */
1096 		ch = buf[i];
1097 
1098 		if (*escape_pendingp) {
1099 			/* We have previously seen an escape character. */
1100 			/* Clear the flag now. */
1101 			*escape_pendingp = 0;
1102 
1103 			/* Process the escaped character. */
1104 			switch (ch) {
1105 			case '.':
1106 				/* Terminate the connection. */
1107 				snprintf(string, sizeof string, "%c.\r\n",
1108 				    escape_char);
1109 				buffer_append(berr, string, strlen(string));
1110 
1111 				if (c && c->ctl_chan != -1) {
1112 					chan_read_failed(c);
1113 					chan_write_failed(c);
1114 					if (c->detach_user)
1115 						c->detach_user(c->self, NULL);
1116 					c->type = SSH_CHANNEL_ABANDONED;
1117 					buffer_clear(&c->input);
1118 					chan_ibuf_empty(c);
1119 					return 0;
1120 				} else
1121 					quit_pending = 1;
1122 				return -1;
1123 
1124 			case 'Z' - 64:
1125 				/* XXX support this for mux clients */
1126 				if (c && c->ctl_chan != -1) {
1127 					char b[16];
1128  noescape:
1129 					if (ch == 'Z' - 64)
1130 						snprintf(b, sizeof b, "^Z");
1131 					else
1132 						snprintf(b, sizeof b, "%c", ch);
1133 					snprintf(string, sizeof string,
1134 					    "%c%s escape not available to "
1135 					    "multiplexed sessions\r\n",
1136 					    escape_char, b);
1137 					buffer_append(berr, string,
1138 					    strlen(string));
1139 					continue;
1140 				}
1141 				/* Suspend the program. Inform the user */
1142 				snprintf(string, sizeof string,
1143 				    "%c^Z [suspend ssh]\r\n", escape_char);
1144 				buffer_append(berr, string, strlen(string));
1145 
1146 				/* Restore terminal modes and suspend. */
1147 				client_suspend_self(bin, bout, berr);
1148 
1149 				/* We have been continued. */
1150 				continue;
1151 
1152 			case 'B':
1153 				if (compat20) {
1154 					snprintf(string, sizeof string,
1155 					    "%cB\r\n", escape_char);
1156 					buffer_append(berr, string,
1157 					    strlen(string));
1158 					channel_request_start(c->self,
1159 					    "break", 0);
1160 					packet_put_int(1000);
1161 					packet_send();
1162 				}
1163 				continue;
1164 
1165 			case 'R':
1166 				if (compat20) {
1167 					if (datafellows & SSH_BUG_NOREKEY)
1168 						logit("Server does not "
1169 						    "support re-keying");
1170 					else
1171 						need_rekeying = 1;
1172 				}
1173 				continue;
1174 
1175 			case 'V':
1176 				/* FALLTHROUGH */
1177 			case 'v':
1178 				if (c && c->ctl_chan != -1)
1179 					goto noescape;
1180 				if (!log_is_on_stderr()) {
1181 					snprintf(string, sizeof string,
1182 					    "%c%c [Logging to syslog]\r\n",
1183 					     escape_char, ch);
1184 					buffer_append(berr, string,
1185 					    strlen(string));
1186 					continue;
1187 				}
1188 				if (ch == 'V' && options.log_level >
1189 				    SYSLOG_LEVEL_QUIET)
1190 					log_change_level(--options.log_level);
1191 				if (ch == 'v' && options.log_level <
1192 				    SYSLOG_LEVEL_DEBUG3)
1193 					log_change_level(++options.log_level);
1194 				snprintf(string, sizeof string,
1195 				    "%c%c [LogLevel %s]\r\n", escape_char, ch,
1196 				    log_level_name(options.log_level));
1197 				buffer_append(berr, string, strlen(string));
1198 				continue;
1199 
1200 			case '&':
1201 				if (c && c->ctl_chan != -1)
1202 					goto noescape;
1203 				/*
1204 				 * Detach the program (continue to serve
1205 				 * connections, but put in background and no
1206 				 * more new connections).
1207 				 */
1208 				/* Restore tty modes. */
1209 				leave_raw_mode(
1210 				    options.request_tty == REQUEST_TTY_FORCE);
1211 
1212 				/* Stop listening for new connections. */
1213 				channel_stop_listening();
1214 
1215 				snprintf(string, sizeof string,
1216 				    "%c& [backgrounded]\n", escape_char);
1217 				buffer_append(berr, string, strlen(string));
1218 
1219 				/* Fork into background. */
1220 				pid = fork();
1221 				if (pid < 0) {
1222 					error("fork: %.100s", strerror(errno));
1223 					continue;
1224 				}
1225 				if (pid != 0) {	/* This is the parent. */
1226 					/* The parent just exits. */
1227 					exit(0);
1228 				}
1229 				/* The child continues serving connections. */
1230 				if (compat20) {
1231 					buffer_append(bin, "\004", 1);
1232 					/* fake EOF on stdin */
1233 					return -1;
1234 				} else if (!stdin_eof) {
1235 					/*
1236 					 * Sending SSH_CMSG_EOF alone does not
1237 					 * always appear to be enough.  So we
1238 					 * try to send an EOF character first.
1239 					 */
1240 					packet_start(SSH_CMSG_STDIN_DATA);
1241 					packet_put_string("\004", 1);
1242 					packet_send();
1243 					/* Close stdin. */
1244 					stdin_eof = 1;
1245 					if (buffer_len(bin) == 0) {
1246 						packet_start(SSH_CMSG_EOF);
1247 						packet_send();
1248 					}
1249 				}
1250 				continue;
1251 
1252 			case '?':
1253 				print_escape_help(berr, escape_char, compat20,
1254 				    (c && c->ctl_chan != -1),
1255 				    log_is_on_stderr());
1256 				continue;
1257 
1258 			case '#':
1259 				snprintf(string, sizeof string, "%c#\r\n",
1260 				    escape_char);
1261 				buffer_append(berr, string, strlen(string));
1262 				s = channel_open_message();
1263 				buffer_append(berr, s, strlen(s));
1264 				free(s);
1265 				continue;
1266 
1267 			case 'C':
1268 				if (c && c->ctl_chan != -1)
1269 					goto noescape;
1270 				process_cmdline();
1271 				continue;
1272 
1273 			default:
1274 				if (ch != escape_char) {
1275 					buffer_put_char(bin, escape_char);
1276 					bytes++;
1277 				}
1278 				/* Escaped characters fall through here */
1279 				break;
1280 			}
1281 		} else {
1282 			/*
1283 			 * The previous character was not an escape char.
1284 			 * Check if this is an escape.
1285 			 */
1286 			if (last_was_cr && ch == escape_char) {
1287 				/*
1288 				 * It is. Set the flag and continue to
1289 				 * next character.
1290 				 */
1291 				*escape_pendingp = 1;
1292 				continue;
1293 			}
1294 		}
1295 
1296 		/*
1297 		 * Normal character.  Record whether it was a newline,
1298 		 * and append it to the buffer.
1299 		 */
1300 		last_was_cr = (ch == '\r' || ch == '\n');
1301 		buffer_put_char(bin, ch);
1302 		bytes++;
1303 	}
1304 	return bytes;
1305 }
1306 
1307 static void
1308 client_process_input(fd_set *readset)
1309 {
1310 	int len;
1311 	char buf[SSH_IOBUFSZ];
1312 
1313 	/* Read input from stdin. */
1314 	if (FD_ISSET(fileno(stdin), readset)) {
1315 		/* Read as much as possible. */
1316 		len = read(fileno(stdin), buf, sizeof(buf));
1317 		if (len < 0 &&
1318 		    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1319 			return;		/* we'll try again later */
1320 		if (len <= 0) {
1321 			/*
1322 			 * Received EOF or error.  They are treated
1323 			 * similarly, except that an error message is printed
1324 			 * if it was an error condition.
1325 			 */
1326 			if (len < 0) {
1327 				snprintf(buf, sizeof buf, "read: %.100s\r\n",
1328 				    strerror(errno));
1329 				buffer_append(&stderr_buffer, buf, strlen(buf));
1330 			}
1331 			/* Mark that we have seen EOF. */
1332 			stdin_eof = 1;
1333 			/*
1334 			 * Send an EOF message to the server unless there is
1335 			 * data in the buffer.  If there is data in the
1336 			 * buffer, no message will be sent now.  Code
1337 			 * elsewhere will send the EOF when the buffer
1338 			 * becomes empty if stdin_eof is set.
1339 			 */
1340 			if (buffer_len(&stdin_buffer) == 0) {
1341 				packet_start(SSH_CMSG_EOF);
1342 				packet_send();
1343 			}
1344 		} else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1345 			/*
1346 			 * Normal successful read, and no escape character.
1347 			 * Just append the data to buffer.
1348 			 */
1349 			buffer_append(&stdin_buffer, buf, len);
1350 		} else {
1351 			/*
1352 			 * Normal, successful read.  But we have an escape
1353 			 * character and have to process the characters one
1354 			 * by one.
1355 			 */
1356 			if (process_escapes(NULL, &stdin_buffer,
1357 			    &stdout_buffer, &stderr_buffer, buf, len) == -1)
1358 				return;
1359 		}
1360 	}
1361 }
1362 
1363 static void
1364 client_process_output(fd_set *writeset)
1365 {
1366 	int len;
1367 	char buf[100];
1368 
1369 	/* Write buffered output to stdout. */
1370 	if (FD_ISSET(fileno(stdout), writeset)) {
1371 		/* Write as much data as possible. */
1372 		len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1373 		    buffer_len(&stdout_buffer));
1374 		if (len <= 0) {
1375 			if (errno == EINTR || errno == EAGAIN ||
1376 			    errno == EWOULDBLOCK)
1377 				len = 0;
1378 			else {
1379 				/*
1380 				 * An error or EOF was encountered.  Put an
1381 				 * error message to stderr buffer.
1382 				 */
1383 				snprintf(buf, sizeof buf,
1384 				    "write stdout: %.50s\r\n", strerror(errno));
1385 				buffer_append(&stderr_buffer, buf, strlen(buf));
1386 				quit_pending = 1;
1387 				return;
1388 			}
1389 		}
1390 		/* Consume printed data from the buffer. */
1391 		buffer_consume(&stdout_buffer, len);
1392 	}
1393 	/* Write buffered output to stderr. */
1394 	if (FD_ISSET(fileno(stderr), writeset)) {
1395 		/* Write as much data as possible. */
1396 		len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1397 		    buffer_len(&stderr_buffer));
1398 		if (len <= 0) {
1399 			if (errno == EINTR || errno == EAGAIN ||
1400 			    errno == EWOULDBLOCK)
1401 				len = 0;
1402 			else {
1403 				/*
1404 				 * EOF or error, but can't even print
1405 				 * error message.
1406 				 */
1407 				quit_pending = 1;
1408 				return;
1409 			}
1410 		}
1411 		/* Consume printed characters from the buffer. */
1412 		buffer_consume(&stderr_buffer, len);
1413 	}
1414 }
1415 
1416 /*
1417  * Get packets from the connection input buffer, and process them as long as
1418  * there are packets available.
1419  *
1420  * Any unknown packets received during the actual
1421  * session cause the session to terminate.  This is
1422  * intended to make debugging easier since no
1423  * confirmations are sent.  Any compatible protocol
1424  * extensions must be negotiated during the
1425  * preparatory phase.
1426  */
1427 
1428 static void
1429 client_process_buffered_input_packets(void)
1430 {
1431 	dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1432 	    compat20 ? xxx_kex : NULL);
1433 }
1434 
1435 /* scan buf[] for '~' before sending data to the peer */
1436 
1437 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1438 void *
1439 client_new_escape_filter_ctx(int escape_char)
1440 {
1441 	struct escape_filter_ctx *ret;
1442 
1443 	ret = xcalloc(1, sizeof(*ret));
1444 	ret->escape_pending = 0;
1445 	ret->escape_char = escape_char;
1446 	return (void *)ret;
1447 }
1448 
1449 /* Free the escape filter context on channel free */
1450 void
1451 client_filter_cleanup(int cid, void *ctx)
1452 {
1453 	free(ctx);
1454 }
1455 
1456 int
1457 client_simple_escape_filter(Channel *c, char *buf, int len)
1458 {
1459 	if (c->extended_usage != CHAN_EXTENDED_WRITE)
1460 		return 0;
1461 
1462 	return process_escapes(c, &c->input, &c->output, &c->extended,
1463 	    buf, len);
1464 }
1465 
1466 static void
1467 client_channel_closed(int id, void *arg)
1468 {
1469 	channel_cancel_cleanup(id);
1470 	session_closed = 1;
1471 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1472 }
1473 
1474 /*
1475  * Implements the interactive session with the server.  This is called after
1476  * the user has been authenticated, and a command has been started on the
1477  * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1478  * used as an escape character for terminating or suspending the session.
1479  */
1480 
1481 int
1482 client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1483 {
1484 	fd_set *readset = NULL, *writeset = NULL;
1485 	double start_time, total_time;
1486 	int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1487 	u_int64_t ibytes, obytes;
1488 	u_int nalloc = 0;
1489 	char buf[100];
1490 
1491 	debug("Entering interactive session.");
1492 
1493 	start_time = get_current_time();
1494 
1495 	/* Initialize variables. */
1496 	escape_pending1 = 0;
1497 	last_was_cr = 1;
1498 	exit_status = -1;
1499 	stdin_eof = 0;
1500 	buffer_high = 64 * 1024;
1501 	connection_in = packet_get_connection_in();
1502 	connection_out = packet_get_connection_out();
1503 	max_fd = MAX(connection_in, connection_out);
1504 
1505 	if (!compat20) {
1506 		/* enable nonblocking unless tty */
1507 		if (!isatty(fileno(stdin)))
1508 			set_nonblock(fileno(stdin));
1509 		if (!isatty(fileno(stdout)))
1510 			set_nonblock(fileno(stdout));
1511 		if (!isatty(fileno(stderr)))
1512 			set_nonblock(fileno(stderr));
1513 		max_fd = MAX(max_fd, fileno(stdin));
1514 		max_fd = MAX(max_fd, fileno(stdout));
1515 		max_fd = MAX(max_fd, fileno(stderr));
1516 	}
1517 	quit_pending = 0;
1518 	escape_char1 = escape_char_arg;
1519 
1520 	/* Initialize buffers. */
1521 	buffer_init(&stdin_buffer);
1522 	buffer_init(&stdout_buffer);
1523 	buffer_init(&stderr_buffer);
1524 
1525 	client_init_dispatch();
1526 
1527 	/*
1528 	 * Set signal handlers, (e.g. to restore non-blocking mode)
1529 	 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1530 	 */
1531 	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1532 		signal(SIGHUP, signal_handler);
1533 	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1534 		signal(SIGINT, signal_handler);
1535 	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1536 		signal(SIGQUIT, signal_handler);
1537 	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1538 		signal(SIGTERM, signal_handler);
1539 	signal(SIGWINCH, window_change_handler);
1540 
1541 	if (have_pty)
1542 		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1543 
1544 	if (compat20) {
1545 		session_ident = ssh2_chan_id;
1546 		if (session_ident != -1) {
1547 			if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1548 				channel_register_filter(session_ident,
1549 				    client_simple_escape_filter, NULL,
1550 				    client_filter_cleanup,
1551 				    client_new_escape_filter_ctx(
1552 				    escape_char_arg));
1553 			}
1554 			channel_register_cleanup(session_ident,
1555 			    client_channel_closed, 0);
1556 		}
1557 	} else {
1558 		/* Check if we should immediately send eof on stdin. */
1559 		client_check_initial_eof_on_stdin();
1560 	}
1561 
1562 	/* Main loop of the client for the interactive session mode. */
1563 	while (!quit_pending) {
1564 
1565 		/* Process buffered packets sent by the server. */
1566 		client_process_buffered_input_packets();
1567 
1568 		if (compat20 && session_closed && !channel_still_open())
1569 			break;
1570 
1571 		rekeying = (xxx_kex != NULL && !xxx_kex->done);
1572 
1573 		if (rekeying) {
1574 			debug("rekeying in progress");
1575 		} else {
1576 			/*
1577 			 * Make packets of buffered stdin data, and buffer
1578 			 * them for sending to the server.
1579 			 */
1580 			if (!compat20)
1581 				client_make_packets_from_stdin_data();
1582 
1583 			/*
1584 			 * Make packets from buffered channel data, and
1585 			 * enqueue them for sending to the server.
1586 			 */
1587 			if (packet_not_very_much_data_to_write())
1588 				channel_output_poll();
1589 
1590 			/*
1591 			 * Check if the window size has changed, and buffer a
1592 			 * message about it to the server if so.
1593 			 */
1594 			client_check_window_change();
1595 
1596 			if (quit_pending)
1597 				break;
1598 		}
1599 		/*
1600 		 * Wait until we have something to do (something becomes
1601 		 * available on one of the descriptors).
1602 		 */
1603 		max_fd2 = max_fd;
1604 		client_wait_until_can_do_something(&readset, &writeset,
1605 		    &max_fd2, &nalloc, rekeying);
1606 
1607 		if (quit_pending)
1608 			break;
1609 
1610 		/* Do channel operations unless rekeying in progress. */
1611 		if (!rekeying) {
1612 			channel_after_select(readset, writeset);
1613 			if (need_rekeying || packet_need_rekeying()) {
1614 				debug("need rekeying");
1615 				xxx_kex->done = 0;
1616 				kex_send_kexinit(xxx_kex);
1617 				need_rekeying = 0;
1618 			}
1619 		}
1620 
1621 		/* Buffer input from the connection.  */
1622 		client_process_net_input(readset);
1623 
1624 		if (quit_pending)
1625 			break;
1626 
1627 		if (!compat20) {
1628 			/* Buffer data from stdin */
1629 			client_process_input(readset);
1630 			/*
1631 			 * Process output to stdout and stderr.  Output to
1632 			 * the connection is processed elsewhere (above).
1633 			 */
1634 			client_process_output(writeset);
1635 		}
1636 
1637 		if (session_resumed) {
1638 			connection_in = packet_get_connection_in();
1639 			connection_out = packet_get_connection_out();
1640 			max_fd = MAX(max_fd, connection_out);
1641 			max_fd = MAX(max_fd, connection_in);
1642 			session_resumed = 0;
1643 		}
1644 
1645 		/*
1646 		 * Send as much buffered packet data as possible to the
1647 		 * sender.
1648 		 */
1649 		if (FD_ISSET(connection_out, writeset))
1650 			packet_write_poll();
1651 
1652 		/*
1653 		 * If we are a backgrounded control master, and the
1654 		 * timeout has expired without any active client
1655 		 * connections, then quit.
1656 		 */
1657 		if (control_persist_exit_time > 0) {
1658 			if (monotime() >= control_persist_exit_time) {
1659 				debug("ControlPersist timeout expired");
1660 				break;
1661 			}
1662 		}
1663 	}
1664 	free(readset);
1665 	free(writeset);
1666 
1667 	/* Terminate the session. */
1668 
1669 	/* Stop watching for window change. */
1670 	signal(SIGWINCH, SIG_DFL);
1671 
1672 	if (compat20) {
1673 		packet_start(SSH2_MSG_DISCONNECT);
1674 		packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1675 		packet_put_cstring("disconnected by user");
1676 		packet_put_cstring(""); /* language tag */
1677 		packet_send();
1678 		packet_write_wait();
1679 	}
1680 
1681 	channel_free_all();
1682 
1683 	if (have_pty)
1684 		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1685 
1686 	/* restore blocking io */
1687 	if (!isatty(fileno(stdin)))
1688 		unset_nonblock(fileno(stdin));
1689 	if (!isatty(fileno(stdout)))
1690 		unset_nonblock(fileno(stdout));
1691 	if (!isatty(fileno(stderr)))
1692 		unset_nonblock(fileno(stderr));
1693 
1694 	/*
1695 	 * If there was no shell or command requested, there will be no remote
1696 	 * exit status to be returned.  In that case, clear error code if the
1697 	 * connection was deliberately terminated at this end.
1698 	 */
1699 	if (no_shell_flag && received_signal == SIGTERM) {
1700 		received_signal = 0;
1701 		exit_status = 0;
1702 	}
1703 
1704 	if (received_signal)
1705 		fatal("Killed by signal %d.", (int) received_signal);
1706 
1707 	/*
1708 	 * In interactive mode (with pseudo tty) display a message indicating
1709 	 * that the connection has been closed.
1710 	 */
1711 	if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1712 		snprintf(buf, sizeof buf,
1713 		    "Connection to %.64s closed.\r\n", host);
1714 		buffer_append(&stderr_buffer, buf, strlen(buf));
1715 	}
1716 
1717 	/* Output any buffered data for stdout. */
1718 	if (buffer_len(&stdout_buffer) > 0) {
1719 		len = atomicio(vwrite, fileno(stdout),
1720 		    buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1721 		if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1722 			error("Write failed flushing stdout buffer.");
1723 		else
1724 			buffer_consume(&stdout_buffer, len);
1725 	}
1726 
1727 	/* Output any buffered data for stderr. */
1728 	if (buffer_len(&stderr_buffer) > 0) {
1729 		len = atomicio(vwrite, fileno(stderr),
1730 		    buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1731 		if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1732 			error("Write failed flushing stderr buffer.");
1733 		else
1734 			buffer_consume(&stderr_buffer, len);
1735 	}
1736 
1737 	/* Clear and free any buffers. */
1738 	memset(buf, 0, sizeof(buf));
1739 	buffer_free(&stdin_buffer);
1740 	buffer_free(&stdout_buffer);
1741 	buffer_free(&stderr_buffer);
1742 
1743 	/* Report bytes transferred, and transfer rates. */
1744 	total_time = get_current_time() - start_time;
1745 	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1746 	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1747 	verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1748 	    (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1749 	if (total_time > 0)
1750 		verbose("Bytes per second: sent %.1f, received %.1f",
1751 		    obytes / total_time, ibytes / total_time);
1752 	/* Return the exit status of the program. */
1753 	debug("Exit status %d", exit_status);
1754 	return exit_status;
1755 }
1756 
1757 /*********/
1758 
1759 static void
1760 client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1761 {
1762 	u_int data_len;
1763 	char *data = packet_get_string(&data_len);
1764 	packet_check_eom();
1765 	buffer_append(&stdout_buffer, data, data_len);
1766 	explicit_bzero(data, data_len);
1767 	free(data);
1768 }
1769 static void
1770 client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1771 {
1772 	u_int data_len;
1773 	char *data = packet_get_string(&data_len);
1774 	packet_check_eom();
1775 	buffer_append(&stderr_buffer, data, data_len);
1776 	explicit_bzero(data, data_len);
1777 	free(data);
1778 }
1779 static void
1780 client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1781 {
1782 	exit_status = packet_get_int();
1783 	packet_check_eom();
1784 	/* Acknowledge the exit. */
1785 	packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1786 	packet_send();
1787 	/*
1788 	 * Must wait for packet to be sent since we are
1789 	 * exiting the loop.
1790 	 */
1791 	packet_write_wait();
1792 	/* Flag that we want to exit. */
1793 	quit_pending = 1;
1794 }
1795 static void
1796 client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1797 {
1798 	Channel *c = NULL;
1799 	int remote_id, sock;
1800 
1801 	/* Read the remote channel number from the message. */
1802 	remote_id = packet_get_int();
1803 	packet_check_eom();
1804 
1805 	/*
1806 	 * Get a connection to the local authentication agent (this may again
1807 	 * get forwarded).
1808 	 */
1809 	sock = ssh_get_authentication_socket();
1810 
1811 	/*
1812 	 * If we could not connect the agent, send an error message back to
1813 	 * the server. This should never happen unless the agent dies,
1814 	 * because authentication forwarding is only enabled if we have an
1815 	 * agent.
1816 	 */
1817 	if (sock >= 0) {
1818 		c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1819 		    -1, 0, 0, 0, "authentication agent connection", 1);
1820 		c->remote_id = remote_id;
1821 		c->force_drain = 1;
1822 	}
1823 	if (c == NULL) {
1824 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1825 		packet_put_int(remote_id);
1826 	} else {
1827 		/* Send a confirmation to the remote host. */
1828 		debug("Forwarding authentication connection.");
1829 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1830 		packet_put_int(remote_id);
1831 		packet_put_int(c->self);
1832 	}
1833 	packet_send();
1834 }
1835 
1836 static Channel *
1837 client_request_forwarded_tcpip(const char *request_type, int rchan)
1838 {
1839 	Channel *c = NULL;
1840 	char *listen_address, *originator_address;
1841 	u_short listen_port, originator_port;
1842 
1843 	/* Get rest of the packet */
1844 	listen_address = packet_get_string(NULL);
1845 	listen_port = packet_get_int();
1846 	originator_address = packet_get_string(NULL);
1847 	originator_port = packet_get_int();
1848 	packet_check_eom();
1849 
1850 	debug("client_request_forwarded_tcpip: listen %s port %d, "
1851 	    "originator %s port %d", listen_address, listen_port,
1852 	    originator_address, originator_port);
1853 
1854 	c = channel_connect_by_listen_address(listen_port,
1855 	    "forwarded-tcpip", originator_address);
1856 
1857 	free(originator_address);
1858 	free(listen_address);
1859 	return c;
1860 }
1861 
1862 static Channel *
1863 client_request_x11(const char *request_type, int rchan)
1864 {
1865 	Channel *c = NULL;
1866 	char *originator;
1867 	u_short originator_port;
1868 	int sock;
1869 
1870 	if (!options.forward_x11) {
1871 		error("Warning: ssh server tried X11 forwarding.");
1872 		error("Warning: this is probably a break-in attempt by a "
1873 		    "malicious server.");
1874 		return NULL;
1875 	}
1876 	if (x11_refuse_time != 0 && monotime() >= x11_refuse_time) {
1877 		verbose("Rejected X11 connection after ForwardX11Timeout "
1878 		    "expired");
1879 		return NULL;
1880 	}
1881 	originator = packet_get_string(NULL);
1882 	if (datafellows & SSH_BUG_X11FWD) {
1883 		debug2("buggy server: x11 request w/o originator_port");
1884 		originator_port = 0;
1885 	} else {
1886 		originator_port = packet_get_int();
1887 	}
1888 	packet_check_eom();
1889 	/* XXX check permission */
1890 	debug("client_request_x11: request from %s %d", originator,
1891 	    originator_port);
1892 	free(originator);
1893 	sock = x11_connect_display();
1894 	if (sock < 0)
1895 		return NULL;
1896 	if (options.hpn_disabled)
1897 		c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1898 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1899 		    0, "x11", 1);
1900 	else
1901 		c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1902 		    options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
1903 		    0, "x11", 1);
1904 	c->force_drain = 1;
1905 	return c;
1906 }
1907 
1908 static Channel *
1909 client_request_agent(const char *request_type, int rchan)
1910 {
1911 	Channel *c = NULL;
1912 	int sock;
1913 
1914 	if (!options.forward_agent) {
1915 		error("Warning: ssh server tried agent forwarding.");
1916 		error("Warning: this is probably a break-in attempt by a "
1917 		    "malicious server.");
1918 		return NULL;
1919 	}
1920 	sock = ssh_get_authentication_socket();
1921 	if (sock < 0)
1922 		return NULL;
1923 	if (options.hpn_disabled)
1924 		c = channel_new("authentication agent connection",
1925 		    SSH_CHANNEL_OPEN, sock, sock, -1,
1926 		    CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0,
1927 		    "authentication agent connection", 1);
1928 	else
1929 		c = channel_new("authentication agent connection",
1930 		    SSH_CHANNEL_OPEN, sock, sock, -1,
1931 		    options.hpn_buffer_size, options.hpn_buffer_size, 0,
1932 		    "authentication agent connection", 1);
1933 	c->force_drain = 1;
1934 	return c;
1935 }
1936 
1937 int
1938 client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1939 {
1940 	Channel *c;
1941 	int fd;
1942 
1943 	if (tun_mode == SSH_TUNMODE_NO)
1944 		return 0;
1945 
1946 	if (!compat20) {
1947 		error("Tunnel forwarding is not supported for protocol 1");
1948 		return -1;
1949 	}
1950 
1951 	debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1952 
1953 	/* Open local tunnel device */
1954 	if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1955 		error("Tunnel device open failed.");
1956 		return -1;
1957 	}
1958 
1959 	if (options.hpn_disabled)
1960 		c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1961 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1962 		    0, "tun", 1);
1963 	else
1964 		c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1965 		    options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1966 		    0, "tun", 1);
1967 	c->datagram = 1;
1968 
1969 #if defined(SSH_TUN_FILTER)
1970 	if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1971 		channel_register_filter(c->self, sys_tun_infilter,
1972 		    sys_tun_outfilter, NULL, NULL);
1973 #endif
1974 
1975 	packet_start(SSH2_MSG_CHANNEL_OPEN);
1976 	packet_put_cstring("tun@openssh.com");
1977 	packet_put_int(c->self);
1978 	packet_put_int(c->local_window_max);
1979 	packet_put_int(c->local_maxpacket);
1980 	packet_put_int(tun_mode);
1981 	packet_put_int(remote_tun);
1982 	packet_send();
1983 
1984 	return 0;
1985 }
1986 
1987 /* XXXX move to generic input handler */
1988 static void
1989 client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1990 {
1991 	Channel *c = NULL;
1992 	char *ctype;
1993 	int rchan;
1994 	u_int rmaxpack, rwindow, len;
1995 
1996 	ctype = packet_get_string(&len);
1997 	rchan = packet_get_int();
1998 	rwindow = packet_get_int();
1999 	rmaxpack = packet_get_int();
2000 
2001 	debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
2002 	    ctype, rchan, rwindow, rmaxpack);
2003 
2004 	if (strcmp(ctype, "forwarded-tcpip") == 0) {
2005 		c = client_request_forwarded_tcpip(ctype, rchan);
2006 	} else if (strcmp(ctype, "x11") == 0) {
2007 		c = client_request_x11(ctype, rchan);
2008 	} else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
2009 		c = client_request_agent(ctype, rchan);
2010 	}
2011 /* XXX duplicate : */
2012 	if (c != NULL) {
2013 		debug("confirm %s", ctype);
2014 		c->remote_id = rchan;
2015 		c->remote_window = rwindow;
2016 		c->remote_maxpacket = rmaxpack;
2017 		if (c->type != SSH_CHANNEL_CONNECTING) {
2018 			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
2019 			packet_put_int(c->remote_id);
2020 			packet_put_int(c->self);
2021 			packet_put_int(c->local_window);
2022 			packet_put_int(c->local_maxpacket);
2023 			packet_send();
2024 		}
2025 	} else {
2026 		debug("failure %s", ctype);
2027 		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
2028 		packet_put_int(rchan);
2029 		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
2030 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2031 			packet_put_cstring("open failed");
2032 			packet_put_cstring("");
2033 		}
2034 		packet_send();
2035 	}
2036 	free(ctype);
2037 }
2038 static void
2039 client_input_channel_req(int type, u_int32_t seq, void *ctxt)
2040 {
2041 	Channel *c = NULL;
2042 	int exitval, id, reply, success = 0;
2043 	char *rtype;
2044 
2045 	id = packet_get_int();
2046 	rtype = packet_get_string(NULL);
2047 	reply = packet_get_char();
2048 
2049 	debug("client_input_channel_req: channel %d rtype %s reply %d",
2050 	    id, rtype, reply);
2051 
2052 	if (id == -1) {
2053 		error("client_input_channel_req: request for channel -1");
2054 	} else if ((c = channel_lookup(id)) == NULL) {
2055 		error("client_input_channel_req: channel %d: "
2056 		    "unknown channel", id);
2057 	} else if (strcmp(rtype, "eow@openssh.com") == 0) {
2058 		packet_check_eom();
2059 		chan_rcvd_eow(c);
2060 	} else if (strcmp(rtype, "exit-status") == 0) {
2061 		exitval = packet_get_int();
2062 		if (c->ctl_chan != -1) {
2063 			mux_exit_message(c, exitval);
2064 			success = 1;
2065 		} else if (id == session_ident) {
2066 			/* Record exit value of local session */
2067 			success = 1;
2068 			exit_status = exitval;
2069 		} else {
2070 			/* Probably for a mux channel that has already closed */
2071 			debug("%s: no sink for exit-status on channel %d",
2072 			    __func__, id);
2073 		}
2074 		packet_check_eom();
2075 	}
2076 	if (reply && c != NULL) {
2077 		packet_start(success ?
2078 		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2079 		packet_put_int(c->remote_id);
2080 		packet_send();
2081 	}
2082 	free(rtype);
2083 }
2084 static void
2085 client_input_global_request(int type, u_int32_t seq, void *ctxt)
2086 {
2087 	char *rtype;
2088 	int want_reply;
2089 	int success = 0;
2090 
2091 	rtype = packet_get_string(NULL);
2092 	want_reply = packet_get_char();
2093 	debug("client_input_global_request: rtype %s want_reply %d",
2094 	    rtype, want_reply);
2095 	if (want_reply) {
2096 		packet_start(success ?
2097 		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2098 		packet_send();
2099 		packet_write_wait();
2100 	}
2101 	free(rtype);
2102 }
2103 
2104 void
2105 client_session2_setup(int id, int want_tty, int want_subsystem,
2106     const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2107 {
2108 	int len;
2109 	Channel *c = NULL;
2110 
2111 	debug2("%s: id %d", __func__, id);
2112 
2113 	if ((c = channel_lookup(id)) == NULL)
2114 		fatal("client_session2_setup: channel %d: unknown channel", id);
2115 
2116 	packet_set_interactive(want_tty,
2117 	    options.ip_qos_interactive, options.ip_qos_bulk);
2118 
2119 	if (want_tty) {
2120 		struct winsize ws;
2121 
2122 		/* Store window size in the packet. */
2123 		if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2124 			memset(&ws, 0, sizeof(ws));
2125 
2126 		channel_request_start(id, "pty-req", 1);
2127 		client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2128 		packet_put_cstring(term != NULL ? term : "");
2129 		packet_put_int((u_int)ws.ws_col);
2130 		packet_put_int((u_int)ws.ws_row);
2131 		packet_put_int((u_int)ws.ws_xpixel);
2132 		packet_put_int((u_int)ws.ws_ypixel);
2133 		if (tiop == NULL)
2134 			tiop = get_saved_tio();
2135 		tty_make_modes(-1, tiop);
2136 		packet_send();
2137 		/* XXX wait for reply */
2138 		c->client_tty = 1;
2139 	}
2140 
2141 	/* Transfer any environment variables from client to server */
2142 	if (options.num_send_env != 0 && env != NULL) {
2143 		int i, j, matched;
2144 		char *name, *val;
2145 
2146 		debug("Sending environment.");
2147 		for (i = 0; env[i] != NULL; i++) {
2148 			/* Split */
2149 			name = xstrdup(env[i]);
2150 			if ((val = strchr(name, '=')) == NULL) {
2151 				free(name);
2152 				continue;
2153 			}
2154 			*val++ = '\0';
2155 
2156 			matched = 0;
2157 			for (j = 0; j < options.num_send_env; j++) {
2158 				if (match_pattern(name, options.send_env[j])) {
2159 					matched = 1;
2160 					break;
2161 				}
2162 			}
2163 			if (!matched) {
2164 				debug3("Ignored env %s", name);
2165 				free(name);
2166 				continue;
2167 			}
2168 
2169 			debug("Sending env %s = %s", name, val);
2170 			channel_request_start(id, "env", 0);
2171 			packet_put_cstring(name);
2172 			packet_put_cstring(val);
2173 			packet_send();
2174 			free(name);
2175 		}
2176 	}
2177 
2178 	len = buffer_len(cmd);
2179 	if (len > 0) {
2180 		if (len > 900)
2181 			len = 900;
2182 		if (want_subsystem) {
2183 			debug("Sending subsystem: %.*s",
2184 			    len, (u_char*)buffer_ptr(cmd));
2185 			channel_request_start(id, "subsystem", 1);
2186 			client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2187 		} else {
2188 			debug("Sending command: %.*s",
2189 			    len, (u_char*)buffer_ptr(cmd));
2190 			channel_request_start(id, "exec", 1);
2191 			client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2192 		}
2193 		packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2194 		packet_send();
2195 	} else {
2196 		channel_request_start(id, "shell", 1);
2197 		client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2198 		packet_send();
2199 	}
2200 }
2201 
2202 static void
2203 client_init_dispatch_20(void)
2204 {
2205 	dispatch_init(&dispatch_protocol_error);
2206 
2207 	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2208 	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2209 	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2210 	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2211 	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2212 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2213 	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2214 	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2215 	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2216 	dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2217 	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2218 	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2219 
2220 	/* rekeying */
2221 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2222 
2223 	/* global request reply messages */
2224 	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2225 	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2226 }
2227 
2228 static void
2229 client_init_dispatch_13(void)
2230 {
2231 	dispatch_init(NULL);
2232 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2233 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2234 	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2235 	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2236 	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2237 	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2238 	dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2239 	dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2240 	dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2241 
2242 	dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2243 	    &client_input_agent_open : &deny_input_open);
2244 	dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2245 	    &x11_input_open : &deny_input_open);
2246 }
2247 
2248 static void
2249 client_init_dispatch_15(void)
2250 {
2251 	client_init_dispatch_13();
2252 	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2253 	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2254 }
2255 
2256 static void
2257 client_init_dispatch(void)
2258 {
2259 	if (compat20)
2260 		client_init_dispatch_20();
2261 	else if (compat13)
2262 		client_init_dispatch_13();
2263 	else
2264 		client_init_dispatch_15();
2265 }
2266 
2267 void
2268 client_stop_mux(void)
2269 {
2270 	if (options.control_path != NULL && muxserver_sock != -1)
2271 		unlink(options.control_path);
2272 	/*
2273 	 * If we are in persist mode, or don't have a shell, signal that we
2274 	 * should close when all active channels are closed.
2275 	 */
2276 	if (options.control_persist || no_shell_flag) {
2277 		session_closed = 1;
2278 		setproctitle("[stopped mux]");
2279 	}
2280 }
2281 
2282 /* client specific fatal cleanup */
2283 void
2284 cleanup_exit(int i)
2285 {
2286 	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2287 	leave_non_blocking();
2288 	if (options.control_path != NULL && muxserver_sock != -1)
2289 		unlink(options.control_path);
2290 	ssh_kill_proxy_command();
2291 	_exit(i);
2292 }
2293