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