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