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