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