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