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