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