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