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