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