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