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