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