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