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