clientloop.c revision 240075
1195534Sscottl/* $OpenBSD: clientloop.c,v 1.240 2012/06/20 04:42:58 djm Exp $ */
2238805Smav/* $FreeBSD: head/crypto/openssh/clientloop.c 240075 2012-09-03 16:51:41Z des $ */
3195534Sscottl/*
4195534Sscottl * Author: Tatu Ylonen <ylo@cs.hut.fi>
5195534Sscottl * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6195534Sscottl *                    All rights reserved
7195534Sscottl * The main loop for the interactive session (client side).
8195534Sscottl *
9195534Sscottl * As far as I am concerned, the code I have written for this software
10195534Sscottl * can be used freely for any purpose.  Any derived versions of this
11195534Sscottl * software must be clearly marked as such, and if the derived work is
12195534Sscottl * incompatible with the protocol description in the RFC file, it must be
13195534Sscottl * called by a name other than "ssh" or "Secure Shell".
14195534Sscottl *
15195534Sscottl *
16195534Sscottl * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
17195534Sscottl *
18195534Sscottl * Redistribution and use in source and binary forms, with or without
19195534Sscottl * modification, are permitted provided that the following conditions
20195534Sscottl * are met:
21195534Sscottl * 1. Redistributions of source code must retain the above copyright
22195534Sscottl *    notice, this list of conditions and the following disclaimer.
23195534Sscottl * 2. Redistributions in binary form must reproduce the above copyright
24195534Sscottl *    notice, this list of conditions and the following disclaimer in the
25195534Sscottl *    documentation and/or other materials provided with the distribution.
26195534Sscottl *
27195534Sscottl * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28195534Sscottl * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29195534Sscottl * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30195534Sscottl * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31195534Sscottl * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32195534Sscottl * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33195534Sscottl * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34195534Sscottl * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35220576Smav * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36195534Sscottl * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37195534Sscottl *
38195534Sscottl *
39195534Sscottl * SSH2 support added by Markus Friedl.
40195534Sscottl * Copyright (c) 1999, 2000, 2001 Markus Friedl.  All rights reserved.
41195534Sscottl *
42195534Sscottl * Redistribution and use in source and binary forms, with or without
43195534Sscottl * modification, are permitted provided that the following conditions
44195534Sscottl * are met:
45195534Sscottl * 1. Redistributions of source code must retain the above copyright
46195534Sscottl *    notice, this list of conditions and the following disclaimer.
47195534Sscottl * 2. Redistributions in binary form must reproduce the above copyright
48271146Simp *    notice, this list of conditions and the following disclaimer in the
49271146Simp *    documentation and/or other materials provided with the distribution.
50195534Sscottl *
51199176Smav * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
52199176Smav * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
53203030Smav * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
54199176Smav * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
55199322Smav * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
56199176Smav * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
57271146Simp * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
58271146Simp * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
59271146Simp * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
60271146Simp * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
61271146Simp */
62271146Simp
63271146Simp#include "includes.h"
64271146Simp
65271146Simp#include <sys/types.h>
66244146Smav#include <sys/ioctl.h>
67244146Smav#include <sys/param.h>
68244146Smav#ifdef HAVE_SYS_STAT_H
69244146Smav# include <sys/stat.h>
70244146Smav#endif
71260830Smav#ifdef HAVE_SYS_TIME_H
72225140Smav# include <sys/time.h>
73203030Smav#endif
74203030Smav#include <sys/socket.h>
75203030Smav
76203030Smav#include <ctype.h>
77203030Smav#include <errno.h>
78203030Smav#ifdef HAVE_PATHS_H
79203030Smav#include <paths.h>
80203030Smav#endif
81203030Smav#include <signal.h>
82203030Smav#include <stdarg.h>
83203030Smav#include <stdio.h>
84203030Smav#include <stdlib.h>
85203030Smav#include <string.h>
86203030Smav#include <termios.h>
87203030Smav#include <pwd.h>
88203030Smav#include <unistd.h>
89203030Smav
90203030Smav#include "openbsd-compat/sys-queue.h"
91203030Smav#include "xmalloc.h"
92203030Smav#include "ssh.h"
93203030Smav#include "ssh1.h"
94203030Smav#include "ssh2.h"
95203030Smav#include "packet.h"
96203030Smav#include "buffer.h"
97203030Smav#include "compat.h"
98203030Smav#include "channels.h"
99203030Smav#include "dispatch.h"
100203030Smav#include "key.h"
101203030Smav#include "cipher.h"
102211922Smav#include "kex.h"
103211922Smav#include "log.h"
104211922Smav#include "readconf.h"
105211922Smav#include "clientloop.h"
106211922Smav#include "sshconnect.h"
107211922Smav#include "authfd.h"
108211922Smav#include "atomicio.h"
109211922Smav#include "sshpty.h"
110211922Smav#include "misc.h"
111211922Smav#include "match.h"
112218605Smav#include "msg.h"
113218605Smav#include "roaming.h"
114218605Smav
115229671Sjimharris/* import options */
116221789Sjfvextern Options options;
117221789Sjfv
118258162Smav/* Flag indicating that stdin should be redirected from /dev/null. */
119258162Smavextern int stdin_null_flag;
120258162Smav
121258162Smav/* Flag indicating that no shell has been requested */
122258162Smavextern int no_shell_flag;
123258162Smav
124258162Smav/* Control socket */
125258162Smavextern int muxserver_sock; /* XXX use mux_client_cleanup() instead */
126258162Smav
127258162Smav/*
128258162Smav * Name of the host we are connecting to.  This is the name given on the
129258162Smav * command line, or the HostName specified for the user-supplied name in a
130258162Smav * configuration file.
131258162Smav */
132258162Smavextern char *host;
133258162Smav
134258162Smav/*
135258162Smav * Flag to indicate that we have received a window change signal which has
136258162Smav * not yet been processed.  This will cause a message indicating the new
137258162Smav * window size to be sent to the server a little later.  This is volatile
138258162Smav * because this is updated in a signal handler.
139258162Smav */
140253475Sjfvstatic volatile sig_atomic_t received_window_change_signal = 0;
141258162Smavstatic volatile sig_atomic_t received_signal = 0;
142258162Smav
143244983Sjfv/* Flag indicating whether the user's terminal is in non-blocking mode. */
144244983Sjfvstatic int in_non_blocking_mode = 0;
145258162Smav
146258162Smav/* Time when backgrounded control master using ControlPersist should exit */
147258162Smavstatic time_t control_persist_exit_time = 0;
148258162Smav
149258162Smav/* Common data for the client loop code. */
150258162Smavvolatile sig_atomic_t quit_pending; /* Set non-zero to quit the loop. */
151258162Smavstatic int escape_char1;	/* Escape character. (proto1 only) */
152258162Smavstatic int escape_pending1;	/* Last character was an escape (proto1 only) */
153258162Smavstatic int last_was_cr;		/* Last character was a newline. */
154258162Smavstatic int exit_status;		/* Used to store the command exit status. */
155258162Smavstatic int stdin_eof;		/* EOF has been encountered on stderr. */
156258162Smavstatic Buffer stdin_buffer;	/* Buffer for stdin data. */
157258162Smavstatic Buffer stdout_buffer;	/* Buffer for stdout data. */
158258162Smavstatic Buffer stderr_buffer;	/* Buffer for stderr data. */
159258162Smavstatic u_int buffer_high;	/* Soft max buffer size. */
160258162Smavstatic int connection_in;	/* Connection to server (input). */
161258162Smavstatic int connection_out;	/* Connection to server (output). */
162258162Smavstatic int need_rekeying;	/* Set to non-zero if rekeying is requested. */
163258162Smavstatic int session_closed;	/* In SSH2: login session closed. */
164258162Smavstatic int x11_refuse_time;	/* If >0, refuse x11 opens after this time. */
165258162Smav
166221789Sjfvstatic void client_init_dispatch(void);
167239907Smavint	session_ident = -1;
168203030Smav
169239907Smavint	session_resumed = 0;
170203030Smav
171203030Smav/* Track escape per proto2 channel */
172203030Smavstruct escape_filter_ctx {
173203030Smav	int escape_pending;
174232380Smav	int escape_char;
175218596Smav};
176232380Smav
177218596Smav/* Context for channel confirmation replies */
178232380Smavstruct channel_reply_ctx {
179218596Smav	const char *request_type;
180232380Smav	int id;
181218596Smav	enum confirm_action action;
182271163Smav};
183271163Smav
184271163Smav/* Global request success/failure callbacks */
185271163Smavstruct global_confirm {
186271163Smav	TAILQ_ENTRY(global_confirm) entry;
187271163Smav	global_confirm_cb *cb;
188271163Smav	void *ctx;
189271163Smav	int ref_count;
190271163Smav};
191271163SmavTAILQ_HEAD(global_confirms, global_confirm);
192271163Smavstatic struct global_confirms global_confirms =
193271163Smav    TAILQ_HEAD_INITIALIZER(global_confirms);
194271163Smav
195271163Smav/*XXX*/
196271163Smavextern Kex *xxx_kex;
197271163Smav
198271163Smavvoid ssh_process_session2_setup(int, int, int, Buffer *);
199271163Smav
200271163Smav/* Restores stdin to blocking mode. */
201271163Smav
202271163Smavstatic void
203271163Smavleave_non_blocking(void)
204271163Smav{
205271163Smav	if (in_non_blocking_mode) {
206271163Smav		unset_nonblock(fileno(stdin));
207207499Smav		in_non_blocking_mode = 0;
208207499Smav	}
209207499Smav}
210207499Smav
211207499Smav/* Puts stdin terminal in non-blocking mode. */
212207499Smav
213207499Smavstatic void
214207499Smaventer_non_blocking(void)
215207499Smav{
216207499Smav	in_non_blocking_mode = 1;
217207499Smav	set_nonblock(fileno(stdin));
218207499Smav}
219207499Smav
220207499Smav/*
221207499Smav * Signal handler for the window change signal (SIGWINCH).  This just sets a
222207499Smav * flag indicating that the window has changed.
223207499Smav */
224207499Smav/*ARGSUSED */
225207499Smavstatic void
226207499Smavwindow_change_handler(int sig)
227207499Smav{
228207499Smav	received_window_change_signal = 1;
229207499Smav	signal(SIGWINCH, window_change_handler);
230207499Smav}
231207499Smav
232207499Smav/*
233207499Smav * Signal handler for signals that cause the program to terminate.  These
234207499Smav * signals must be trapped to restore terminal modes.
235207499Smav */
236207499Smav/*ARGSUSED */
237207499Smavstatic void
238207499Smavsignal_handler(int sig)
239207499Smav{
240207499Smav	received_signal = sig;
241207499Smav	quit_pending = 1;
242207499Smav}
243207499Smav
244207499Smav/*
245207499Smav * Returns current time in seconds from Jan 1, 1970 with the maximum
246207499Smav * available resolution.
247207499Smav */
248207499Smav
249207499Smavstatic double
250207499Smavget_current_time(void)
251207499Smav{
252207499Smav	struct timeval tv;
253207499Smav	gettimeofday(&tv, NULL);
254207499Smav	return (double) tv.tv_sec + (double) tv.tv_usec / 1000000.0;
255207499Smav}
256207499Smav
257207499Smav/*
258207499Smav * Sets control_persist_exit_time to the absolute time when the
259207499Smav * backgrounded control master should exit due to expiry of the
260207499Smav * ControlPersist timeout.  Sets it to 0 if we are not a backgrounded
261207499Smav * control master process, or if there is no ControlPersist timeout.
262207499Smav */
263207499Smavstatic void
264207499Smavset_control_persist_exit_time(void)
265224603Smav{
266207499Smav	if (muxserver_sock == -1 || !options.control_persist
267207499Smav	    || options.control_persist_timeout == 0) {
268207499Smav		/* not using a ControlPersist timeout */
269207499Smav		control_persist_exit_time = 0;
270207499Smav	} else if (channel_still_open()) {
271207499Smav		/* some client connections are still open */
272207499Smav		if (control_persist_exit_time > 0)
273207499Smav			debug2("%s: cancel scheduled exit", __func__);
274207499Smav		control_persist_exit_time = 0;
275207499Smav	} else if (control_persist_exit_time <= 0) {
276271403Smav		/* a client connection has recently closed */
277208907Smav		control_persist_exit_time = time(NULL) +
278208907Smav			(time_t)options.control_persist_timeout;
279203030Smav		debug2("%s: schedule exit in %d seconds", __func__,
280203030Smav		    options.control_persist_timeout);
281203030Smav	}
282203030Smav	/* else we are already counting down to the timeout */
283199176Smav}
284199176Smav
285271146Simp#define SSH_X11_VALID_DISPLAY_CHARS ":/.-_"
286271146Simpstatic int
287271146Simpclient_x11_display_valid(const char *display)
288220565Smav{
289271146Simp	size_t i, dlen;
290271146Simp
291271146Simp	dlen = strlen(display);
292271146Simp	for (i = 0; i < dlen; i++) {
293271146Simp		if (!isalnum(display[i]) &&
294228200Smav		    strchr(SSH_X11_VALID_DISPLAY_CHARS, display[i]) == NULL) {
295195534Sscottl			debug("Invalid character '%c' in DISPLAY", display[i]);
296195534Sscottl			return 0;
297195534Sscottl		}
298199176Smav	}
299199322Smav	return 1;
300199322Smav}
301203030Smav
302199322Smav#define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
303260163Szbbvoid
304260163Szbbclient_x11_get_proto(const char *display, const char *xauth_path,
305260163Szbb    u_int trusted, u_int timeout, char **_proto, char **_data)
306260163Szbb{
307260163Szbb	char cmd[1024];
308260163Szbb	char line[512];
309260163Szbb	char xdisplay[512];
310199322Smav	static char proto[512], data[512];
311199322Smav	FILE *f;
312199322Smav	int got_data = 0, generated = 0, do_unlink = 0, i;
313199322Smav	char *xauthdir, *xauthfile;
314199322Smav	struct stat st;
315199322Smav	u_int now;
316199322Smav
317199322Smav	xauthdir = xauthfile = NULL;
318203030Smav	*_proto = proto;
319228200Smav	*_data = data;
320228200Smav	proto[0] = data[0] = '\0';
321199717Smav
322199717Smav	if (xauth_path == NULL ||(stat(xauth_path, &st) == -1)) {
323199717Smav		debug("No xauth program.");
324199717Smav	} else if (!client_x11_display_valid(display)) {
325199322Smav		logit("DISPLAY '%s' invalid, falling back to fake xauth data",
326199322Smav		    display);
327199322Smav	} else {
328199322Smav		if (display == NULL) {
329199322Smav			debug("x11_get_proto: DISPLAY not set");
330199322Smav			return;
331199322Smav		}
332199322Smav		/*
333199322Smav		 * Handle FamilyLocal case where $DISPLAY does
334199322Smav		 * not match an authorization entry.  For this we
335199322Smav		 * just try "xauth list unix:displaynum.screennum".
336199322Smav		 * XXX: "localhost" match to determine FamilyLocal
337199322Smav		 *      is not perfect.
338199322Smav		 */
339199322Smav		if (strncmp(display, "localhost:", 10) == 0) {
340199322Smav			snprintf(xdisplay, sizeof(xdisplay), "unix:%s",
341199176Smav			    display + 10);
342199176Smav			display = xdisplay;
343203030Smav		}
344195534Sscottl		if (trusted == 0) {
345199322Smav			xauthdir = xmalloc(MAXPATHLEN);
346199322Smav			xauthfile = xmalloc(MAXPATHLEN);
347199176Smav			mktemp_proto(xauthdir, MAXPATHLEN);
348199176Smav			if (mkdtemp(xauthdir) != NULL) {
349203030Smav				do_unlink = 1;
350203030Smav				snprintf(xauthfile, MAXPATHLEN, "%s/xauthfile",
351199176Smav				    xauthdir);
352199176Smav				snprintf(cmd, sizeof(cmd),
353199176Smav				    "%s -f %s generate %s " SSH_X11_PROTO
354199176Smav				    " untrusted timeout %u 2>" _PATH_DEVNULL,
355199176Smav				    xauth_path, xauthfile, display, timeout);
356199176Smav				debug2("x11_get_proto: %s", cmd);
357199176Smav				if (system(cmd) == 0)
358195534Sscottl					generated = 1;
359195534Sscottl				if (x11_refuse_time == 0) {
360195534Sscottl					now = time(NULL) + 1;
361195534Sscottl					if (UINT_MAX - timeout < now)
362271146Simp						x11_refuse_time = UINT_MAX;
363195534Sscottl					else
364195534Sscottl						x11_refuse_time = now + timeout;
365271146Simp				}
366199322Smav			}
367203030Smav		}
368195534Sscottl
369199322Smav		/*
370203030Smav		 * When in untrusted mode, we read the cookie only if it was
371203030Smav		 * successfully generated as an untrusted one in the step
372203030Smav		 * above.
373199322Smav		 */
374199322Smav		if (trusted || generated) {
375271146Simp			snprintf(cmd, sizeof(cmd),
376271146Simp			    "%s %s%s list %s 2>" _PATH_DEVNULL,
377271146Simp			    xauth_path,
378271146Simp			    generated ? "-f " : "" ,
379271146Simp			    generated ? xauthfile : "",
380271146Simp			    display);
381195534Sscottl			debug2("x11_get_proto: %s", cmd);
382271146Simp			f = popen(cmd, "r");
383271146Simp			if (f && fgets(line, sizeof(line), f) &&
384271146Simp			    sscanf(line, "%*s %511s %511s", proto, data) == 2)
385271146Simp				got_data = 1;
386195534Sscottl			if (f)
387195534Sscottl				pclose(f);
388195534Sscottl		} else
389195534Sscottl			error("Warning: untrusted X11 forwarding setup failed: "
390207511Smav			    "xauth key data not generated");
391195534Sscottl	}
392271146Simp
393195534Sscottl	if (do_unlink) {
394195534Sscottl		unlink(xauthfile);
395195534Sscottl		rmdir(xauthdir);
396222304Smav	}
397195534Sscottl	if (xauthdir)
398195534Sscottl		xfree(xauthdir);
399271146Simp	if (xauthfile)
400256843Smav		xfree(xauthfile);
401195534Sscottl
402245875Smav	/*
403256843Smav	 * If we didn't get authentication data, just make up some
404195534Sscottl	 * data.  The forwarding code will check the validity of the
405256843Smav	 * response anyway, and substitute this data.  The X11
406256843Smav	 * server, however, will ignore this fake data and use
407256843Smav	 * whatever authentication mechanisms it was using otherwise
408256843Smav	 * for the local connection.
409256843Smav	 */
410256843Smav	if (!got_data) {
411256843Smav		u_int32_t rnd = 0;
412256843Smav
413256843Smav		logit("Warning: No xauth data; "
414256843Smav		    "using fake authentication data for X11 forwarding.");
415195534Sscottl		strlcpy(proto, SSH_X11_PROTO, sizeof proto);
416256843Smav		for (i = 0; i < 16; i++) {
417256843Smav			if (i % 4 == 0)
418195534Sscottl				rnd = arc4random();
419195534Sscottl			snprintf(data + 2 * i, sizeof data - 2 * i, "%02x",
420195534Sscottl			    rnd & 0xff);
421271146Simp			rnd >>= 8;
422271146Simp		}
423271146Simp	}
424271146Simp}
425271146Simp
426195534Sscottl/*
427195534Sscottl * This is called when the interactive is entered.  This checks if there is
428195534Sscottl * an EOF coming on stdin.  We must check this explicitly, as select() does
429271146Simp * not appear to wake up when redirecting from /dev/null.
430195534Sscottl */
431195534Sscottl
432271146Simpstatic void
433271146Simpclient_check_initial_eof_on_stdin(void)
434195534Sscottl{
435195534Sscottl	int len;
436195534Sscottl	char buf[1];
437195534Sscottl
438271146Simp	/*
439195534Sscottl	 * If standard input is to be "redirected from /dev/null", we simply
440195534Sscottl	 * mark that we have seen an EOF and send an EOF message to the
441195534Sscottl	 * server. Otherwise, we try to read a single character; it appears
442271146Simp	 * that for some files, such /dev/null, select() never wakes up for
443271146Simp	 * read for this descriptor, which means that we never get EOF.  This
444271146Simp	 * way we will get the EOF if stdin comes from /dev/null or similar.
445271146Simp	 */
446271146Simp	if (stdin_null_flag) {
447195534Sscottl		/* Fake EOF on stdin. */
448195534Sscottl		debug("Sending eof.");
449195534Sscottl		stdin_eof = 1;
450271146Simp		packet_start(SSH_CMSG_EOF);
451195534Sscottl		packet_send();
452271146Simp	} else {
453195534Sscottl		enter_non_blocking();
454271146Simp
455271146Simp		/* Check for immediate EOF on stdin. */
456271146Simp		len = read(fileno(stdin), buf, 1);
457271146Simp		if (len == 0) {
458195534Sscottl			/*
459195534Sscottl			 * EOF.  Record that we have seen it and send
460195534Sscottl			 * EOF to server.
461195534Sscottl			 */
462195534Sscottl			debug("Sending eof.");
463271146Simp			stdin_eof = 1;
464271146Simp			packet_start(SSH_CMSG_EOF);
465271146Simp			packet_send();
466271146Simp		} else if (len > 0) {
467195534Sscottl			/*
468195534Sscottl			 * Got data.  We must store the data in the buffer,
469195534Sscottl			 * and also process it as an escape character if
470195534Sscottl			 * appropriate.
471195534Sscottl			 */
472208410Smav			if ((u_char) buf[0] == escape_char1)
473249346Smav				escape_pending1 = 1;
474195534Sscottl			else
475195534Sscottl				buffer_append(&stdin_buffer, buf, 1);
476195534Sscottl		}
477195534Sscottl		leave_non_blocking();
478195534Sscottl	}
479195534Sscottl}
480195534Sscottl
481195534Sscottl
482199322Smav/*
483199322Smav * Make packets from buffered stdin data, and buffer them for sending to the
484271146Simp * connection.
485271146Simp */
486271146Simp
487271146Simpstatic void
488199322Smavclient_make_packets_from_stdin_data(void)
489199322Smav{
490199322Smav	u_int len;
491199322Smav
492199322Smav	/* Send buffered stdin data to the server. */
493208410Smav	while (buffer_len(&stdin_buffer) > 0 &&
494199322Smav	    packet_not_very_much_data_to_write()) {
495199322Smav		len = buffer_len(&stdin_buffer);
496199322Smav		/* Keep the packets at reasonable size. */
497199322Smav		if (len > packet_get_maxsize())
498199322Smav			len = packet_get_maxsize();
499199322Smav		packet_start(SSH_CMSG_STDIN_DATA);
500199322Smav		packet_put_string(buffer_ptr(&stdin_buffer), len);
501199322Smav		packet_send();
502		buffer_consume(&stdin_buffer, len);
503		/* If we have a pending EOF, send it now. */
504		if (stdin_eof && buffer_len(&stdin_buffer) == 0) {
505			packet_start(SSH_CMSG_EOF);
506			packet_send();
507		}
508	}
509}
510
511/*
512 * Checks if the client window has changed, and sends a packet about it to
513 * the server if so.  The actual change is detected elsewhere (by a software
514 * interrupt on Unix); this just checks the flag and sends a message if
515 * appropriate.
516 */
517
518static void
519client_check_window_change(void)
520{
521	struct winsize ws;
522
523	if (! received_window_change_signal)
524		return;
525	/** XXX race */
526	received_window_change_signal = 0;
527
528	debug2("client_check_window_change: changed");
529
530	if (compat20) {
531		channel_send_window_changes();
532	} else {
533		if (ioctl(fileno(stdin), TIOCGWINSZ, &ws) < 0)
534			return;
535		packet_start(SSH_CMSG_WINDOW_SIZE);
536		packet_put_int((u_int)ws.ws_row);
537		packet_put_int((u_int)ws.ws_col);
538		packet_put_int((u_int)ws.ws_xpixel);
539		packet_put_int((u_int)ws.ws_ypixel);
540		packet_send();
541	}
542}
543
544static void
545client_global_request_reply(int type, u_int32_t seq, void *ctxt)
546{
547	struct global_confirm *gc;
548
549	if ((gc = TAILQ_FIRST(&global_confirms)) == NULL)
550		return;
551	if (gc->cb != NULL)
552		gc->cb(type, seq, gc->ctx);
553	if (--gc->ref_count <= 0) {
554		TAILQ_REMOVE(&global_confirms, gc, entry);
555		bzero(gc, sizeof(*gc));
556		xfree(gc);
557	}
558
559	packet_set_alive_timeouts(0);
560}
561
562static void
563server_alive_check(void)
564{
565	if (packet_inc_alive_timeouts() > options.server_alive_count_max) {
566		logit("Timeout, server %s not responding.", host);
567		cleanup_exit(255);
568	}
569	packet_start(SSH2_MSG_GLOBAL_REQUEST);
570	packet_put_cstring("keepalive@openssh.com");
571	packet_put_char(1);     /* boolean: want reply */
572	packet_send();
573	/* Insert an empty placeholder to maintain ordering */
574	client_register_global_confirm(NULL, NULL);
575}
576
577/*
578 * Waits until the client can do something (some data becomes available on
579 * one of the file descriptors).
580 */
581static void
582client_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
583    int *maxfdp, u_int *nallocp, int rekeying)
584{
585	struct timeval tv, *tvp;
586	int timeout_secs;
587	time_t minwait_secs = 0;
588	int ret;
589
590	/* Add any selections by the channel mechanism. */
591	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
592	    &minwait_secs, rekeying);
593
594	if (!compat20) {
595		/* Read from the connection, unless our buffers are full. */
596		if (buffer_len(&stdout_buffer) < buffer_high &&
597		    buffer_len(&stderr_buffer) < buffer_high &&
598		    channel_not_very_much_buffered_data())
599			FD_SET(connection_in, *readsetp);
600		/*
601		 * Read from stdin, unless we have seen EOF or have very much
602		 * buffered data to send to the server.
603		 */
604		if (!stdin_eof && packet_not_very_much_data_to_write())
605			FD_SET(fileno(stdin), *readsetp);
606
607		/* Select stdout/stderr if have data in buffer. */
608		if (buffer_len(&stdout_buffer) > 0)
609			FD_SET(fileno(stdout), *writesetp);
610		if (buffer_len(&stderr_buffer) > 0)
611			FD_SET(fileno(stderr), *writesetp);
612	} else {
613		/* channel_prepare_select could have closed the last channel */
614		if (session_closed && !channel_still_open() &&
615		    !packet_have_data_to_write()) {
616			/* clear mask since we did not call select() */
617			memset(*readsetp, 0, *nallocp);
618			memset(*writesetp, 0, *nallocp);
619			return;
620		} else {
621			FD_SET(connection_in, *readsetp);
622		}
623	}
624
625	/* Select server connection if have data to write to the server. */
626	if (packet_have_data_to_write())
627		FD_SET(connection_out, *writesetp);
628
629	/*
630	 * Wait for something to happen.  This will suspend the process until
631	 * some selected descriptor can be read, written, or has some other
632	 * event pending, or a timeout expires.
633	 */
634
635	timeout_secs = INT_MAX; /* we use INT_MAX to mean no timeout */
636	if (options.server_alive_interval > 0 && compat20)
637		timeout_secs = options.server_alive_interval;
638	set_control_persist_exit_time();
639	if (control_persist_exit_time > 0) {
640		timeout_secs = MIN(timeout_secs,
641			control_persist_exit_time - time(NULL));
642		if (timeout_secs < 0)
643			timeout_secs = 0;
644	}
645	if (minwait_secs != 0)
646		timeout_secs = MIN(timeout_secs, (int)minwait_secs);
647	if (timeout_secs == INT_MAX)
648		tvp = NULL;
649	else {
650		tv.tv_sec = timeout_secs;
651		tv.tv_usec = 0;
652		tvp = &tv;
653	}
654
655	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
656	if (ret < 0) {
657		char buf[100];
658
659		/*
660		 * We have to clear the select masks, because we return.
661		 * We have to return, because the mainloop checks for the flags
662		 * set by the signal handlers.
663		 */
664		memset(*readsetp, 0, *nallocp);
665		memset(*writesetp, 0, *nallocp);
666
667		if (errno == EINTR)
668			return;
669		/* Note: we might still have data in the buffers. */
670		snprintf(buf, sizeof buf, "select: %s\r\n", strerror(errno));
671		buffer_append(&stderr_buffer, buf, strlen(buf));
672		quit_pending = 1;
673	} else if (ret == 0)
674		server_alive_check();
675}
676
677static void
678client_suspend_self(Buffer *bin, Buffer *bout, Buffer *berr)
679{
680	/* Flush stdout and stderr buffers. */
681	if (buffer_len(bout) > 0)
682		atomicio(vwrite, fileno(stdout), buffer_ptr(bout),
683		    buffer_len(bout));
684	if (buffer_len(berr) > 0)
685		atomicio(vwrite, fileno(stderr), buffer_ptr(berr),
686		    buffer_len(berr));
687
688	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
689
690	/*
691	 * Free (and clear) the buffer to reduce the amount of data that gets
692	 * written to swap.
693	 */
694	buffer_free(bin);
695	buffer_free(bout);
696	buffer_free(berr);
697
698	/* Send the suspend signal to the program itself. */
699	kill(getpid(), SIGTSTP);
700
701	/* Reset window sizes in case they have changed */
702	received_window_change_signal = 1;
703
704	/* OK, we have been continued by the user. Reinitialize buffers. */
705	buffer_init(bin);
706	buffer_init(bout);
707	buffer_init(berr);
708
709	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
710}
711
712static void
713client_process_net_input(fd_set *readset)
714{
715	int len, cont = 0;
716	char buf[SSH_IOBUFSZ];
717
718	/*
719	 * Read input from the server, and add any such data to the buffer of
720	 * the packet subsystem.
721	 */
722	if (FD_ISSET(connection_in, readset)) {
723		/* Read as much as possible. */
724		len = roaming_read(connection_in, buf, sizeof(buf), &cont);
725		if (len == 0 && cont == 0) {
726			/*
727			 * Received EOF.  The remote host has closed the
728			 * connection.
729			 */
730			snprintf(buf, sizeof buf,
731			    "Connection to %.300s closed by remote host.\r\n",
732			    host);
733			buffer_append(&stderr_buffer, buf, strlen(buf));
734			quit_pending = 1;
735			return;
736		}
737		/*
738		 * There is a kernel bug on Solaris that causes select to
739		 * sometimes wake up even though there is no data available.
740		 */
741		if (len < 0 &&
742		    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
743			len = 0;
744
745		if (len < 0) {
746			/*
747			 * An error has encountered.  Perhaps there is a
748			 * network problem.
749			 */
750			snprintf(buf, sizeof buf,
751			    "Read from remote host %.300s: %.100s\r\n",
752			    host, strerror(errno));
753			buffer_append(&stderr_buffer, buf, strlen(buf));
754			quit_pending = 1;
755			return;
756		}
757		packet_process_incoming(buf, len);
758	}
759}
760
761static void
762client_status_confirm(int type, Channel *c, void *ctx)
763{
764	struct channel_reply_ctx *cr = (struct channel_reply_ctx *)ctx;
765	char errmsg[256];
766	int tochan;
767
768	/*
769	 * If a TTY was explicitly requested, then a failure to allocate
770	 * one is fatal.
771	 */
772	if (cr->action == CONFIRM_TTY &&
773	    (options.request_tty == REQUEST_TTY_FORCE ||
774	    options.request_tty == REQUEST_TTY_YES))
775		cr->action = CONFIRM_CLOSE;
776
777	/* XXX supress on mux _client_ quietmode */
778	tochan = options.log_level >= SYSLOG_LEVEL_ERROR &&
779	    c->ctl_chan != -1 && c->extended_usage == CHAN_EXTENDED_WRITE;
780
781	if (type == SSH2_MSG_CHANNEL_SUCCESS) {
782		debug2("%s request accepted on channel %d",
783		    cr->request_type, c->self);
784	} else if (type == SSH2_MSG_CHANNEL_FAILURE) {
785		if (tochan) {
786			snprintf(errmsg, sizeof(errmsg),
787			    "%s request failed\r\n", cr->request_type);
788		} else {
789			snprintf(errmsg, sizeof(errmsg),
790			    "%s request failed on channel %d",
791			    cr->request_type, c->self);
792		}
793		/* If error occurred on primary session channel, then exit */
794		if (cr->action == CONFIRM_CLOSE && c->self == session_ident)
795			fatal("%s", errmsg);
796		/*
797		 * If error occurred on mux client, append to
798		 * their stderr.
799		 */
800		if (tochan) {
801			buffer_append(&c->extended, errmsg,
802			    strlen(errmsg));
803		} else
804			error("%s", errmsg);
805		if (cr->action == CONFIRM_TTY) {
806			/*
807			 * If a TTY allocation error occurred, then arrange
808			 * for the correct TTY to leave raw mode.
809			 */
810			if (c->self == session_ident)
811				leave_raw_mode(0);
812			else
813				mux_tty_alloc_failed(c);
814		} else if (cr->action == CONFIRM_CLOSE) {
815			chan_read_failed(c);
816			chan_write_failed(c);
817		}
818	}
819	xfree(cr);
820}
821
822static void
823client_abandon_status_confirm(Channel *c, void *ctx)
824{
825	xfree(ctx);
826}
827
828void
829client_expect_confirm(int id, const char *request,
830    enum confirm_action action)
831{
832	struct channel_reply_ctx *cr = xmalloc(sizeof(*cr));
833
834	cr->request_type = request;
835	cr->action = action;
836
837	channel_register_status_confirm(id, client_status_confirm,
838	    client_abandon_status_confirm, cr);
839}
840
841void
842client_register_global_confirm(global_confirm_cb *cb, void *ctx)
843{
844	struct global_confirm *gc, *last_gc;
845
846	/* Coalesce identical callbacks */
847	last_gc = TAILQ_LAST(&global_confirms, global_confirms);
848	if (last_gc && last_gc->cb == cb && last_gc->ctx == ctx) {
849		if (++last_gc->ref_count >= INT_MAX)
850			fatal("%s: last_gc->ref_count = %d",
851			    __func__, last_gc->ref_count);
852		return;
853	}
854
855	gc = xmalloc(sizeof(*gc));
856	gc->cb = cb;
857	gc->ctx = ctx;
858	gc->ref_count = 1;
859	TAILQ_INSERT_TAIL(&global_confirms, gc, entry);
860}
861
862static void
863process_cmdline(void)
864{
865	void (*handler)(int);
866	char *s, *cmd, *cancel_host;
867	int delete = 0, local = 0, remote = 0, dynamic = 0;
868	int cancel_port, ok;
869	Forward fwd;
870
871	bzero(&fwd, sizeof(fwd));
872	fwd.listen_host = fwd.connect_host = NULL;
873
874	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
875	handler = signal(SIGINT, SIG_IGN);
876	cmd = s = read_passphrase("\r\nssh> ", RP_ECHO);
877	if (s == NULL)
878		goto out;
879	while (isspace(*s))
880		s++;
881	if (*s == '-')
882		s++;	/* Skip cmdline '-', if any */
883	if (*s == '\0')
884		goto out;
885
886	if (*s == 'h' || *s == 'H' || *s == '?') {
887		logit("Commands:");
888		logit("      -L[bind_address:]port:host:hostport    "
889		    "Request local forward");
890		logit("      -R[bind_address:]port:host:hostport    "
891		    "Request remote forward");
892		logit("      -D[bind_address:]port                  "
893		    "Request dynamic forward");
894		logit("      -KL[bind_address:]port                 "
895		    "Cancel local forward");
896		logit("      -KR[bind_address:]port                 "
897		    "Cancel remote forward");
898		logit("      -KD[bind_address:]port                 "
899		    "Cancel dynamic forward");
900		if (!options.permit_local_command)
901			goto out;
902		logit("      !args                                  "
903		    "Execute local command");
904		goto out;
905	}
906
907	if (*s == '!' && options.permit_local_command) {
908		s++;
909		ssh_local_cmd(s);
910		goto out;
911	}
912
913	if (*s == 'K') {
914		delete = 1;
915		s++;
916	}
917	if (*s == 'L')
918		local = 1;
919	else if (*s == 'R')
920		remote = 1;
921	else if (*s == 'D')
922		dynamic = 1;
923	else {
924		logit("Invalid command.");
925		goto out;
926	}
927
928	if (delete && !compat20) {
929		logit("Not supported for SSH protocol version 1.");
930		goto out;
931	}
932
933	while (isspace(*++s))
934		;
935
936	/* XXX update list of forwards in options */
937	if (delete) {
938		cancel_port = 0;
939		cancel_host = hpdelim(&s);	/* may be NULL */
940		if (s != NULL) {
941			cancel_port = a2port(s);
942			cancel_host = cleanhostname(cancel_host);
943		} else {
944			cancel_port = a2port(cancel_host);
945			cancel_host = NULL;
946		}
947		if (cancel_port <= 0) {
948			logit("Bad forwarding close port");
949			goto out;
950		}
951		if (remote)
952			ok = channel_request_rforward_cancel(cancel_host,
953			    cancel_port) == 0;
954		else if (dynamic)
955                	ok = channel_cancel_lport_listener(cancel_host,
956			    cancel_port, 0, options.gateway_ports) > 0;
957		else
958                	ok = channel_cancel_lport_listener(cancel_host,
959			    cancel_port, CHANNEL_CANCEL_PORT_STATIC,
960			    options.gateway_ports) > 0;
961		if (!ok) {
962			logit("Unkown port forwarding.");
963			goto out;
964		}
965		logit("Canceled forwarding.");
966	} else {
967		if (!parse_forward(&fwd, s, dynamic, remote)) {
968			logit("Bad forwarding specification.");
969			goto out;
970		}
971		if (local || dynamic) {
972			if (channel_setup_local_fwd_listener(fwd.listen_host,
973			    fwd.listen_port, fwd.connect_host,
974			    fwd.connect_port, options.gateway_ports) < 0) {
975				logit("Port forwarding failed.");
976				goto out;
977			}
978		} else {
979			if (channel_request_remote_forwarding(fwd.listen_host,
980			    fwd.listen_port, fwd.connect_host,
981			    fwd.connect_port) < 0) {
982				logit("Port forwarding failed.");
983				goto out;
984			}
985		}
986		logit("Forwarding port.");
987	}
988
989out:
990	signal(SIGINT, handler);
991	enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
992	if (cmd)
993		xfree(cmd);
994	if (fwd.listen_host != NULL)
995		xfree(fwd.listen_host);
996	if (fwd.connect_host != NULL)
997		xfree(fwd.connect_host);
998}
999
1000/*
1001 * Process the characters one by one, call with c==NULL for proto1 case.
1002 */
1003static int
1004process_escapes(Channel *c, Buffer *bin, Buffer *bout, Buffer *berr,
1005    char *buf, int len)
1006{
1007	char string[1024];
1008	pid_t pid;
1009	int bytes = 0;
1010	u_int i;
1011	u_char ch;
1012	char *s;
1013	int *escape_pendingp, escape_char;
1014	struct escape_filter_ctx *efc;
1015
1016	if (c == NULL) {
1017		escape_pendingp = &escape_pending1;
1018		escape_char = escape_char1;
1019	} else {
1020		if (c->filter_ctx == NULL)
1021			return 0;
1022		efc = (struct escape_filter_ctx *)c->filter_ctx;
1023		escape_pendingp = &efc->escape_pending;
1024		escape_char = efc->escape_char;
1025	}
1026
1027	if (len <= 0)
1028		return (0);
1029
1030	for (i = 0; i < (u_int)len; i++) {
1031		/* Get one character at a time. */
1032		ch = buf[i];
1033
1034		if (*escape_pendingp) {
1035			/* We have previously seen an escape character. */
1036			/* Clear the flag now. */
1037			*escape_pendingp = 0;
1038
1039			/* Process the escaped character. */
1040			switch (ch) {
1041			case '.':
1042				/* Terminate the connection. */
1043				snprintf(string, sizeof string, "%c.\r\n",
1044				    escape_char);
1045				buffer_append(berr, string, strlen(string));
1046
1047				if (c && c->ctl_chan != -1) {
1048					chan_read_failed(c);
1049					chan_write_failed(c);
1050					return 0;
1051				} else
1052					quit_pending = 1;
1053				return -1;
1054
1055			case 'Z' - 64:
1056				/* XXX support this for mux clients */
1057				if (c && c->ctl_chan != -1) {
1058 noescape:
1059					snprintf(string, sizeof string,
1060					    "%c%c escape not available to "
1061					    "multiplexed sessions\r\n",
1062					    escape_char, ch);
1063					buffer_append(berr, string,
1064					    strlen(string));
1065					continue;
1066				}
1067				/* Suspend the program. Inform the user */
1068				snprintf(string, sizeof string,
1069				    "%c^Z [suspend ssh]\r\n", escape_char);
1070				buffer_append(berr, string, strlen(string));
1071
1072				/* Restore terminal modes and suspend. */
1073				client_suspend_self(bin, bout, berr);
1074
1075				/* We have been continued. */
1076				continue;
1077
1078			case 'B':
1079				if (compat20) {
1080					snprintf(string, sizeof string,
1081					    "%cB\r\n", escape_char);
1082					buffer_append(berr, string,
1083					    strlen(string));
1084					channel_request_start(session_ident,
1085					    "break", 0);
1086					packet_put_int(1000);
1087					packet_send();
1088				}
1089				continue;
1090
1091			case 'R':
1092				if (compat20) {
1093					if (datafellows & SSH_BUG_NOREKEY)
1094						logit("Server does not "
1095						    "support re-keying");
1096					else
1097						need_rekeying = 1;
1098				}
1099				continue;
1100
1101			case '&':
1102				if (c && c->ctl_chan != -1)
1103					goto noescape;
1104				/*
1105				 * Detach the program (continue to serve
1106				 * connections, but put in background and no
1107				 * more new connections).
1108				 */
1109				/* Restore tty modes. */
1110				leave_raw_mode(
1111				    options.request_tty == REQUEST_TTY_FORCE);
1112
1113				/* Stop listening for new connections. */
1114				channel_stop_listening();
1115
1116				snprintf(string, sizeof string,
1117				    "%c& [backgrounded]\n", escape_char);
1118				buffer_append(berr, string, strlen(string));
1119
1120				/* Fork into background. */
1121				pid = fork();
1122				if (pid < 0) {
1123					error("fork: %.100s", strerror(errno));
1124					continue;
1125				}
1126				if (pid != 0) {	/* This is the parent. */
1127					/* The parent just exits. */
1128					exit(0);
1129				}
1130				/* The child continues serving connections. */
1131				if (compat20) {
1132					buffer_append(bin, "\004", 1);
1133					/* fake EOF on stdin */
1134					return -1;
1135				} else if (!stdin_eof) {
1136					/*
1137					 * Sending SSH_CMSG_EOF alone does not
1138					 * always appear to be enough.  So we
1139					 * try to send an EOF character first.
1140					 */
1141					packet_start(SSH_CMSG_STDIN_DATA);
1142					packet_put_string("\004", 1);
1143					packet_send();
1144					/* Close stdin. */
1145					stdin_eof = 1;
1146					if (buffer_len(bin) == 0) {
1147						packet_start(SSH_CMSG_EOF);
1148						packet_send();
1149					}
1150				}
1151				continue;
1152
1153			case '?':
1154				if (c && c->ctl_chan != -1) {
1155					snprintf(string, sizeof string,
1156"%c?\r\n\
1157Supported escape sequences:\r\n\
1158  %c.  - terminate session\r\n\
1159  %cB  - send a BREAK to the remote system\r\n\
1160  %cR  - Request rekey (SSH protocol 2 only)\r\n\
1161  %c#  - list forwarded connections\r\n\
1162  %c?  - this message\r\n\
1163  %c%c  - send the escape character by typing it twice\r\n\
1164(Note that escapes are only recognized immediately after newline.)\r\n",
1165					    escape_char, escape_char,
1166					    escape_char, escape_char,
1167					    escape_char, escape_char,
1168					    escape_char, escape_char);
1169				} else {
1170					snprintf(string, sizeof string,
1171"%c?\r\n\
1172Supported escape sequences:\r\n\
1173  %c.  - terminate connection (and any multiplexed sessions)\r\n\
1174  %cB  - send a BREAK to the remote system\r\n\
1175  %cC  - open a command line\r\n\
1176  %cR  - Request rekey (SSH protocol 2 only)\r\n\
1177  %c^Z - suspend ssh\r\n\
1178  %c#  - list forwarded connections\r\n\
1179  %c&  - background ssh (when waiting for connections to terminate)\r\n\
1180  %c?  - this message\r\n\
1181  %c%c  - send the escape character by typing it twice\r\n\
1182(Note that escapes are only recognized immediately after newline.)\r\n",
1183					    escape_char, escape_char,
1184					    escape_char, escape_char,
1185					    escape_char, escape_char,
1186					    escape_char, escape_char,
1187					    escape_char, escape_char,
1188					    escape_char);
1189				}
1190				buffer_append(berr, string, strlen(string));
1191				continue;
1192
1193			case '#':
1194				snprintf(string, sizeof string, "%c#\r\n",
1195				    escape_char);
1196				buffer_append(berr, string, strlen(string));
1197				s = channel_open_message();
1198				buffer_append(berr, s, strlen(s));
1199				xfree(s);
1200				continue;
1201
1202			case 'C':
1203				if (c && c->ctl_chan != -1)
1204					goto noescape;
1205				process_cmdline();
1206				continue;
1207
1208			default:
1209				if (ch != escape_char) {
1210					buffer_put_char(bin, escape_char);
1211					bytes++;
1212				}
1213				/* Escaped characters fall through here */
1214				break;
1215			}
1216		} else {
1217			/*
1218			 * The previous character was not an escape char.
1219			 * Check if this is an escape.
1220			 */
1221			if (last_was_cr && ch == escape_char) {
1222				/*
1223				 * It is. Set the flag and continue to
1224				 * next character.
1225				 */
1226				*escape_pendingp = 1;
1227				continue;
1228			}
1229		}
1230
1231		/*
1232		 * Normal character.  Record whether it was a newline,
1233		 * and append it to the buffer.
1234		 */
1235		last_was_cr = (ch == '\r' || ch == '\n');
1236		buffer_put_char(bin, ch);
1237		bytes++;
1238	}
1239	return bytes;
1240}
1241
1242static void
1243client_process_input(fd_set *readset)
1244{
1245	int len;
1246	char buf[SSH_IOBUFSZ];
1247
1248	/* Read input from stdin. */
1249	if (FD_ISSET(fileno(stdin), readset)) {
1250		/* Read as much as possible. */
1251		len = read(fileno(stdin), buf, sizeof(buf));
1252		if (len < 0 &&
1253		    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
1254			return;		/* we'll try again later */
1255		if (len <= 0) {
1256			/*
1257			 * Received EOF or error.  They are treated
1258			 * similarly, except that an error message is printed
1259			 * if it was an error condition.
1260			 */
1261			if (len < 0) {
1262				snprintf(buf, sizeof buf, "read: %.100s\r\n",
1263				    strerror(errno));
1264				buffer_append(&stderr_buffer, buf, strlen(buf));
1265			}
1266			/* Mark that we have seen EOF. */
1267			stdin_eof = 1;
1268			/*
1269			 * Send an EOF message to the server unless there is
1270			 * data in the buffer.  If there is data in the
1271			 * buffer, no message will be sent now.  Code
1272			 * elsewhere will send the EOF when the buffer
1273			 * becomes empty if stdin_eof is set.
1274			 */
1275			if (buffer_len(&stdin_buffer) == 0) {
1276				packet_start(SSH_CMSG_EOF);
1277				packet_send();
1278			}
1279		} else if (escape_char1 == SSH_ESCAPECHAR_NONE) {
1280			/*
1281			 * Normal successful read, and no escape character.
1282			 * Just append the data to buffer.
1283			 */
1284			buffer_append(&stdin_buffer, buf, len);
1285		} else {
1286			/*
1287			 * Normal, successful read.  But we have an escape
1288			 * character and have to process the characters one
1289			 * by one.
1290			 */
1291			if (process_escapes(NULL, &stdin_buffer,
1292			    &stdout_buffer, &stderr_buffer, buf, len) == -1)
1293				return;
1294		}
1295	}
1296}
1297
1298static void
1299client_process_output(fd_set *writeset)
1300{
1301	int len;
1302	char buf[100];
1303
1304	/* Write buffered output to stdout. */
1305	if (FD_ISSET(fileno(stdout), writeset)) {
1306		/* Write as much data as possible. */
1307		len = write(fileno(stdout), buffer_ptr(&stdout_buffer),
1308		    buffer_len(&stdout_buffer));
1309		if (len <= 0) {
1310			if (errno == EINTR || errno == EAGAIN ||
1311			    errno == EWOULDBLOCK)
1312				len = 0;
1313			else {
1314				/*
1315				 * An error or EOF was encountered.  Put an
1316				 * error message to stderr buffer.
1317				 */
1318				snprintf(buf, sizeof buf,
1319				    "write stdout: %.50s\r\n", strerror(errno));
1320				buffer_append(&stderr_buffer, buf, strlen(buf));
1321				quit_pending = 1;
1322				return;
1323			}
1324		}
1325		/* Consume printed data from the buffer. */
1326		buffer_consume(&stdout_buffer, len);
1327	}
1328	/* Write buffered output to stderr. */
1329	if (FD_ISSET(fileno(stderr), writeset)) {
1330		/* Write as much data as possible. */
1331		len = write(fileno(stderr), buffer_ptr(&stderr_buffer),
1332		    buffer_len(&stderr_buffer));
1333		if (len <= 0) {
1334			if (errno == EINTR || errno == EAGAIN ||
1335			    errno == EWOULDBLOCK)
1336				len = 0;
1337			else {
1338				/*
1339				 * EOF or error, but can't even print
1340				 * error message.
1341				 */
1342				quit_pending = 1;
1343				return;
1344			}
1345		}
1346		/* Consume printed characters from the buffer. */
1347		buffer_consume(&stderr_buffer, len);
1348	}
1349}
1350
1351/*
1352 * Get packets from the connection input buffer, and process them as long as
1353 * there are packets available.
1354 *
1355 * Any unknown packets received during the actual
1356 * session cause the session to terminate.  This is
1357 * intended to make debugging easier since no
1358 * confirmations are sent.  Any compatible protocol
1359 * extensions must be negotiated during the
1360 * preparatory phase.
1361 */
1362
1363static void
1364client_process_buffered_input_packets(void)
1365{
1366	dispatch_run(DISPATCH_NONBLOCK, &quit_pending,
1367	    compat20 ? xxx_kex : NULL);
1368}
1369
1370/* scan buf[] for '~' before sending data to the peer */
1371
1372/* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1373void *
1374client_new_escape_filter_ctx(int escape_char)
1375{
1376	struct escape_filter_ctx *ret;
1377
1378	ret = xmalloc(sizeof(*ret));
1379	ret->escape_pending = 0;
1380	ret->escape_char = escape_char;
1381	return (void *)ret;
1382}
1383
1384/* Free the escape filter context on channel free */
1385void
1386client_filter_cleanup(int cid, void *ctx)
1387{
1388	xfree(ctx);
1389}
1390
1391int
1392client_simple_escape_filter(Channel *c, char *buf, int len)
1393{
1394	if (c->extended_usage != CHAN_EXTENDED_WRITE)
1395		return 0;
1396
1397	return process_escapes(c, &c->input, &c->output, &c->extended,
1398	    buf, len);
1399}
1400
1401static void
1402client_channel_closed(int id, void *arg)
1403{
1404	channel_cancel_cleanup(id);
1405	session_closed = 1;
1406	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1407}
1408
1409/*
1410 * Implements the interactive session with the server.  This is called after
1411 * the user has been authenticated, and a command has been started on the
1412 * remote host.  If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1413 * used as an escape character for terminating or suspending the session.
1414 */
1415
1416int
1417client_loop(int have_pty, int escape_char_arg, int ssh2_chan_id)
1418{
1419	fd_set *readset = NULL, *writeset = NULL;
1420	double start_time, total_time;
1421	int max_fd = 0, max_fd2 = 0, len, rekeying = 0;
1422	u_int64_t ibytes, obytes;
1423	u_int nalloc = 0;
1424	char buf[100];
1425
1426	debug("Entering interactive session.");
1427
1428	start_time = get_current_time();
1429
1430	/* Initialize variables. */
1431	escape_pending1 = 0;
1432	last_was_cr = 1;
1433	exit_status = -1;
1434	stdin_eof = 0;
1435	buffer_high = 64 * 1024;
1436	connection_in = packet_get_connection_in();
1437	connection_out = packet_get_connection_out();
1438	max_fd = MAX(connection_in, connection_out);
1439
1440	if (!compat20) {
1441		/* enable nonblocking unless tty */
1442		if (!isatty(fileno(stdin)))
1443			set_nonblock(fileno(stdin));
1444		if (!isatty(fileno(stdout)))
1445			set_nonblock(fileno(stdout));
1446		if (!isatty(fileno(stderr)))
1447			set_nonblock(fileno(stderr));
1448		max_fd = MAX(max_fd, fileno(stdin));
1449		max_fd = MAX(max_fd, fileno(stdout));
1450		max_fd = MAX(max_fd, fileno(stderr));
1451	}
1452	quit_pending = 0;
1453	escape_char1 = escape_char_arg;
1454
1455	/* Initialize buffers. */
1456	buffer_init(&stdin_buffer);
1457	buffer_init(&stdout_buffer);
1458	buffer_init(&stderr_buffer);
1459
1460	client_init_dispatch();
1461
1462	/*
1463	 * Set signal handlers, (e.g. to restore non-blocking mode)
1464	 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1465	 */
1466	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1467		signal(SIGHUP, signal_handler);
1468	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1469		signal(SIGINT, signal_handler);
1470	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1471		signal(SIGQUIT, signal_handler);
1472	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
1473		signal(SIGTERM, signal_handler);
1474	signal(SIGWINCH, window_change_handler);
1475
1476	if (have_pty)
1477		enter_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1478
1479	if (compat20) {
1480		session_ident = ssh2_chan_id;
1481		if (session_ident != -1) {
1482			if (escape_char_arg != SSH_ESCAPECHAR_NONE) {
1483				channel_register_filter(session_ident,
1484				    client_simple_escape_filter, NULL,
1485				    client_filter_cleanup,
1486				    client_new_escape_filter_ctx(
1487				    escape_char_arg));
1488			}
1489			channel_register_cleanup(session_ident,
1490			    client_channel_closed, 0);
1491		}
1492	} else {
1493		/* Check if we should immediately send eof on stdin. */
1494		client_check_initial_eof_on_stdin();
1495	}
1496
1497	/* Main loop of the client for the interactive session mode. */
1498	while (!quit_pending) {
1499
1500		/* Process buffered packets sent by the server. */
1501		client_process_buffered_input_packets();
1502
1503		if (compat20 && session_closed && !channel_still_open())
1504			break;
1505
1506		rekeying = (xxx_kex != NULL && !xxx_kex->done);
1507
1508		if (rekeying) {
1509			debug("rekeying in progress");
1510		} else {
1511			/*
1512			 * Make packets of buffered stdin data, and buffer
1513			 * them for sending to the server.
1514			 */
1515			if (!compat20)
1516				client_make_packets_from_stdin_data();
1517
1518			/*
1519			 * Make packets from buffered channel data, and
1520			 * enqueue them for sending to the server.
1521			 */
1522			if (packet_not_very_much_data_to_write())
1523				channel_output_poll();
1524
1525			/*
1526			 * Check if the window size has changed, and buffer a
1527			 * message about it to the server if so.
1528			 */
1529			client_check_window_change();
1530
1531			if (quit_pending)
1532				break;
1533		}
1534		/*
1535		 * Wait until we have something to do (something becomes
1536		 * available on one of the descriptors).
1537		 */
1538		max_fd2 = max_fd;
1539		client_wait_until_can_do_something(&readset, &writeset,
1540		    &max_fd2, &nalloc, rekeying);
1541
1542		if (quit_pending)
1543			break;
1544
1545		/* Do channel operations unless rekeying in progress. */
1546		if (!rekeying) {
1547			channel_after_select(readset, writeset);
1548			if (need_rekeying || packet_need_rekeying()) {
1549				debug("need rekeying");
1550				xxx_kex->done = 0;
1551				kex_send_kexinit(xxx_kex);
1552				need_rekeying = 0;
1553			}
1554		}
1555
1556		/* Buffer input from the connection.  */
1557		client_process_net_input(readset);
1558
1559		if (quit_pending)
1560			break;
1561
1562		if (!compat20) {
1563			/* Buffer data from stdin */
1564			client_process_input(readset);
1565			/*
1566			 * Process output to stdout and stderr.  Output to
1567			 * the connection is processed elsewhere (above).
1568			 */
1569			client_process_output(writeset);
1570		}
1571
1572		if (session_resumed) {
1573			connection_in = packet_get_connection_in();
1574			connection_out = packet_get_connection_out();
1575			max_fd = MAX(max_fd, connection_out);
1576			max_fd = MAX(max_fd, connection_in);
1577			session_resumed = 0;
1578		}
1579
1580		/*
1581		 * Send as much buffered packet data as possible to the
1582		 * sender.
1583		 */
1584		if (FD_ISSET(connection_out, writeset))
1585			packet_write_poll();
1586
1587		/*
1588		 * If we are a backgrounded control master, and the
1589		 * timeout has expired without any active client
1590		 * connections, then quit.
1591		 */
1592		if (control_persist_exit_time > 0) {
1593			if (time(NULL) >= control_persist_exit_time) {
1594				debug("ControlPersist timeout expired");
1595				break;
1596			}
1597		}
1598	}
1599	if (readset)
1600		xfree(readset);
1601	if (writeset)
1602		xfree(writeset);
1603
1604	/* Terminate the session. */
1605
1606	/* Stop watching for window change. */
1607	signal(SIGWINCH, SIG_DFL);
1608
1609	if (compat20) {
1610		packet_start(SSH2_MSG_DISCONNECT);
1611		packet_put_int(SSH2_DISCONNECT_BY_APPLICATION);
1612		packet_put_cstring("disconnected by user");
1613		packet_put_cstring(""); /* language tag */
1614		packet_send();
1615		packet_write_wait();
1616	}
1617
1618	channel_free_all();
1619
1620	if (have_pty)
1621		leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
1622
1623	/* restore blocking io */
1624	if (!isatty(fileno(stdin)))
1625		unset_nonblock(fileno(stdin));
1626	if (!isatty(fileno(stdout)))
1627		unset_nonblock(fileno(stdout));
1628	if (!isatty(fileno(stderr)))
1629		unset_nonblock(fileno(stderr));
1630
1631	/*
1632	 * If there was no shell or command requested, there will be no remote
1633	 * exit status to be returned.  In that case, clear error code if the
1634	 * connection was deliberately terminated at this end.
1635	 */
1636	if (no_shell_flag && received_signal == SIGTERM) {
1637		received_signal = 0;
1638		exit_status = 0;
1639	}
1640
1641	if (received_signal)
1642		fatal("Killed by signal %d.", (int) received_signal);
1643
1644	/*
1645	 * In interactive mode (with pseudo tty) display a message indicating
1646	 * that the connection has been closed.
1647	 */
1648	if (have_pty && options.log_level != SYSLOG_LEVEL_QUIET) {
1649		snprintf(buf, sizeof buf,
1650		    "Connection to %.64s closed.\r\n", host);
1651		buffer_append(&stderr_buffer, buf, strlen(buf));
1652	}
1653
1654	/* Output any buffered data for stdout. */
1655	if (buffer_len(&stdout_buffer) > 0) {
1656		len = atomicio(vwrite, fileno(stdout),
1657		    buffer_ptr(&stdout_buffer), buffer_len(&stdout_buffer));
1658		if (len < 0 || (u_int)len != buffer_len(&stdout_buffer))
1659			error("Write failed flushing stdout buffer.");
1660		else
1661			buffer_consume(&stdout_buffer, len);
1662	}
1663
1664	/* Output any buffered data for stderr. */
1665	if (buffer_len(&stderr_buffer) > 0) {
1666		len = atomicio(vwrite, fileno(stderr),
1667		    buffer_ptr(&stderr_buffer), buffer_len(&stderr_buffer));
1668		if (len < 0 || (u_int)len != buffer_len(&stderr_buffer))
1669			error("Write failed flushing stderr buffer.");
1670		else
1671			buffer_consume(&stderr_buffer, len);
1672	}
1673
1674	/* Clear and free any buffers. */
1675	memset(buf, 0, sizeof(buf));
1676	buffer_free(&stdin_buffer);
1677	buffer_free(&stdout_buffer);
1678	buffer_free(&stderr_buffer);
1679
1680	/* Report bytes transferred, and transfer rates. */
1681	total_time = get_current_time() - start_time;
1682	packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1683	packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1684	verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1685	    (unsigned long long)obytes, (unsigned long long)ibytes, total_time);
1686	if (total_time > 0)
1687		verbose("Bytes per second: sent %.1f, received %.1f",
1688		    obytes / total_time, ibytes / total_time);
1689	/* Return the exit status of the program. */
1690	debug("Exit status %d", exit_status);
1691	return exit_status;
1692}
1693
1694/*********/
1695
1696static void
1697client_input_stdout_data(int type, u_int32_t seq, void *ctxt)
1698{
1699	u_int data_len;
1700	char *data = packet_get_string(&data_len);
1701	packet_check_eom();
1702	buffer_append(&stdout_buffer, data, data_len);
1703	memset(data, 0, data_len);
1704	xfree(data);
1705}
1706static void
1707client_input_stderr_data(int type, u_int32_t seq, void *ctxt)
1708{
1709	u_int data_len;
1710	char *data = packet_get_string(&data_len);
1711	packet_check_eom();
1712	buffer_append(&stderr_buffer, data, data_len);
1713	memset(data, 0, data_len);
1714	xfree(data);
1715}
1716static void
1717client_input_exit_status(int type, u_int32_t seq, void *ctxt)
1718{
1719	exit_status = packet_get_int();
1720	packet_check_eom();
1721	/* Acknowledge the exit. */
1722	packet_start(SSH_CMSG_EXIT_CONFIRMATION);
1723	packet_send();
1724	/*
1725	 * Must wait for packet to be sent since we are
1726	 * exiting the loop.
1727	 */
1728	packet_write_wait();
1729	/* Flag that we want to exit. */
1730	quit_pending = 1;
1731}
1732static void
1733client_input_agent_open(int type, u_int32_t seq, void *ctxt)
1734{
1735	Channel *c = NULL;
1736	int remote_id, sock;
1737
1738	/* Read the remote channel number from the message. */
1739	remote_id = packet_get_int();
1740	packet_check_eom();
1741
1742	/*
1743	 * Get a connection to the local authentication agent (this may again
1744	 * get forwarded).
1745	 */
1746	sock = ssh_get_authentication_socket();
1747
1748	/*
1749	 * If we could not connect the agent, send an error message back to
1750	 * the server. This should never happen unless the agent dies,
1751	 * because authentication forwarding is only enabled if we have an
1752	 * agent.
1753	 */
1754	if (sock >= 0) {
1755		c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
1756		    -1, 0, 0, 0, "authentication agent connection", 1);
1757		c->remote_id = remote_id;
1758		c->force_drain = 1;
1759	}
1760	if (c == NULL) {
1761		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1762		packet_put_int(remote_id);
1763	} else {
1764		/* Send a confirmation to the remote host. */
1765		debug("Forwarding authentication connection.");
1766		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1767		packet_put_int(remote_id);
1768		packet_put_int(c->self);
1769	}
1770	packet_send();
1771}
1772
1773static Channel *
1774client_request_forwarded_tcpip(const char *request_type, int rchan)
1775{
1776	Channel *c = NULL;
1777	char *listen_address, *originator_address;
1778	u_short listen_port, originator_port;
1779
1780	/* Get rest of the packet */
1781	listen_address = packet_get_string(NULL);
1782	listen_port = packet_get_int();
1783	originator_address = packet_get_string(NULL);
1784	originator_port = packet_get_int();
1785	packet_check_eom();
1786
1787	debug("client_request_forwarded_tcpip: listen %s port %d, "
1788	    "originator %s port %d", listen_address, listen_port,
1789	    originator_address, originator_port);
1790
1791	c = channel_connect_by_listen_address(listen_port,
1792	    "forwarded-tcpip", originator_address);
1793
1794	xfree(originator_address);
1795	xfree(listen_address);
1796	return c;
1797}
1798
1799static Channel *
1800client_request_x11(const char *request_type, int rchan)
1801{
1802	Channel *c = NULL;
1803	char *originator;
1804	u_short originator_port;
1805	int sock;
1806
1807	if (!options.forward_x11) {
1808		error("Warning: ssh server tried X11 forwarding.");
1809		error("Warning: this is probably a break-in attempt by a "
1810		    "malicious server.");
1811		return NULL;
1812	}
1813	if (x11_refuse_time != 0 && time(NULL) >= x11_refuse_time) {
1814		verbose("Rejected X11 connection after ForwardX11Timeout "
1815		    "expired");
1816		return NULL;
1817	}
1818	originator = packet_get_string(NULL);
1819	if (datafellows & SSH_BUG_X11FWD) {
1820		debug2("buggy server: x11 request w/o originator_port");
1821		originator_port = 0;
1822	} else {
1823		originator_port = packet_get_int();
1824	}
1825	packet_check_eom();
1826	/* XXX check permission */
1827	debug("client_request_x11: request from %s %d", originator,
1828	    originator_port);
1829	xfree(originator);
1830	sock = x11_connect_display();
1831	if (sock < 0)
1832		return NULL;
1833	if (options.hpn_disabled)
1834		c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1835		    CHAN_TCP_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
1836		    0, "x11", 1);
1837	else
1838		c = channel_new("x11", SSH_CHANNEL_X11_OPEN, sock, sock, -1,
1839		    options.hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
1840		    0, "x11", 1);
1841	c->force_drain = 1;
1842	return c;
1843}
1844
1845static Channel *
1846client_request_agent(const char *request_type, int rchan)
1847{
1848	Channel *c = NULL;
1849	int sock;
1850
1851	if (!options.forward_agent) {
1852		error("Warning: ssh server tried agent forwarding.");
1853		error("Warning: this is probably a break-in attempt by a "
1854		    "malicious server.");
1855		return NULL;
1856	}
1857	sock = ssh_get_authentication_socket();
1858	if (sock < 0)
1859		return NULL;
1860	if (options.hpn_disabled)
1861		c = channel_new("authentication agent connection",
1862		    SSH_CHANNEL_OPEN, sock, sock, -1,
1863		    CHAN_X11_WINDOW_DEFAULT, CHAN_TCP_WINDOW_DEFAULT, 0,
1864		    "authentication agent connection", 1);
1865	else
1866		c = channel_new("authentication agent connection",
1867		    SSH_CHANNEL_OPEN, sock, sock, -1,
1868		    options.hpn_buffer_size, options.hpn_buffer_size, 0,
1869		    "authentication agent connection", 1);
1870	c->force_drain = 1;
1871	return c;
1872}
1873
1874int
1875client_request_tun_fwd(int tun_mode, int local_tun, int remote_tun)
1876{
1877	Channel *c;
1878	int fd;
1879
1880	if (tun_mode == SSH_TUNMODE_NO)
1881		return 0;
1882
1883	if (!compat20) {
1884		error("Tunnel forwarding is not supported for protocol 1");
1885		return -1;
1886	}
1887
1888	debug("Requesting tun unit %d in mode %d", local_tun, tun_mode);
1889
1890	/* Open local tunnel device */
1891	if ((fd = tun_open(local_tun, tun_mode)) == -1) {
1892		error("Tunnel device open failed.");
1893		return -1;
1894	}
1895
1896	if (options.hpn_disabled)
1897		c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1898		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1899		    0, "tun", 1);
1900	else
1901		c = channel_new("tun", SSH_CHANNEL_OPENING, fd, fd, -1,
1902		    options.hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
1903		    0, "tun", 1);
1904	c->datagram = 1;
1905
1906#if defined(SSH_TUN_FILTER)
1907	if (options.tun_open == SSH_TUNMODE_POINTOPOINT)
1908		channel_register_filter(c->self, sys_tun_infilter,
1909		    sys_tun_outfilter, NULL, NULL);
1910#endif
1911
1912	packet_start(SSH2_MSG_CHANNEL_OPEN);
1913	packet_put_cstring("tun@openssh.com");
1914	packet_put_int(c->self);
1915	packet_put_int(c->local_window_max);
1916	packet_put_int(c->local_maxpacket);
1917	packet_put_int(tun_mode);
1918	packet_put_int(remote_tun);
1919	packet_send();
1920
1921	return 0;
1922}
1923
1924/* XXXX move to generic input handler */
1925static void
1926client_input_channel_open(int type, u_int32_t seq, void *ctxt)
1927{
1928	Channel *c = NULL;
1929	char *ctype;
1930	int rchan;
1931	u_int rmaxpack, rwindow, len;
1932
1933	ctype = packet_get_string(&len);
1934	rchan = packet_get_int();
1935	rwindow = packet_get_int();
1936	rmaxpack = packet_get_int();
1937
1938	debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1939	    ctype, rchan, rwindow, rmaxpack);
1940
1941	if (strcmp(ctype, "forwarded-tcpip") == 0) {
1942		c = client_request_forwarded_tcpip(ctype, rchan);
1943	} else if (strcmp(ctype, "x11") == 0) {
1944		c = client_request_x11(ctype, rchan);
1945	} else if (strcmp(ctype, "auth-agent@openssh.com") == 0) {
1946		c = client_request_agent(ctype, rchan);
1947	}
1948/* XXX duplicate : */
1949	if (c != NULL) {
1950		debug("confirm %s", ctype);
1951		c->remote_id = rchan;
1952		c->remote_window = rwindow;
1953		c->remote_maxpacket = rmaxpack;
1954		if (c->type != SSH_CHANNEL_CONNECTING) {
1955			packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1956			packet_put_int(c->remote_id);
1957			packet_put_int(c->self);
1958			packet_put_int(c->local_window);
1959			packet_put_int(c->local_maxpacket);
1960			packet_send();
1961		}
1962	} else {
1963		debug("failure %s", ctype);
1964		packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1965		packet_put_int(rchan);
1966		packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED);
1967		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1968			packet_put_cstring("open failed");
1969			packet_put_cstring("");
1970		}
1971		packet_send();
1972	}
1973	xfree(ctype);
1974}
1975static void
1976client_input_channel_req(int type, u_int32_t seq, void *ctxt)
1977{
1978	Channel *c = NULL;
1979	int exitval, id, reply, success = 0;
1980	char *rtype;
1981
1982	id = packet_get_int();
1983	rtype = packet_get_string(NULL);
1984	reply = packet_get_char();
1985
1986	debug("client_input_channel_req: channel %d rtype %s reply %d",
1987	    id, rtype, reply);
1988
1989	if (id == -1) {
1990		error("client_input_channel_req: request for channel -1");
1991	} else if ((c = channel_lookup(id)) == NULL) {
1992		error("client_input_channel_req: channel %d: "
1993		    "unknown channel", id);
1994	} else if (strcmp(rtype, "eow@openssh.com") == 0) {
1995		packet_check_eom();
1996		chan_rcvd_eow(c);
1997	} else if (strcmp(rtype, "exit-status") == 0) {
1998		exitval = packet_get_int();
1999		if (c->ctl_chan != -1) {
2000			mux_exit_message(c, exitval);
2001			success = 1;
2002		} else if (id == session_ident) {
2003			/* Record exit value of local session */
2004			success = 1;
2005			exit_status = exitval;
2006		} else {
2007			/* Probably for a mux channel that has already closed */
2008			debug("%s: no sink for exit-status on channel %d",
2009			    __func__, id);
2010		}
2011		packet_check_eom();
2012	}
2013	if (reply && c != NULL) {
2014		packet_start(success ?
2015		    SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
2016		packet_put_int(c->remote_id);
2017		packet_send();
2018	}
2019	xfree(rtype);
2020}
2021static void
2022client_input_global_request(int type, u_int32_t seq, void *ctxt)
2023{
2024	char *rtype;
2025	int want_reply;
2026	int success = 0;
2027
2028	rtype = packet_get_string(NULL);
2029	want_reply = packet_get_char();
2030	debug("client_input_global_request: rtype %s want_reply %d",
2031	    rtype, want_reply);
2032	if (want_reply) {
2033		packet_start(success ?
2034		    SSH2_MSG_REQUEST_SUCCESS : SSH2_MSG_REQUEST_FAILURE);
2035		packet_send();
2036		packet_write_wait();
2037	}
2038	xfree(rtype);
2039}
2040
2041void
2042client_session2_setup(int id, int want_tty, int want_subsystem,
2043    const char *term, struct termios *tiop, int in_fd, Buffer *cmd, char **env)
2044{
2045	int len;
2046	Channel *c = NULL;
2047
2048	debug2("%s: id %d", __func__, id);
2049
2050	if ((c = channel_lookup(id)) == NULL)
2051		fatal("client_session2_setup: channel %d: unknown channel", id);
2052
2053	packet_set_interactive(want_tty,
2054	    options.ip_qos_interactive, options.ip_qos_bulk);
2055
2056	if (want_tty) {
2057		struct winsize ws;
2058
2059		/* Store window size in the packet. */
2060		if (ioctl(in_fd, TIOCGWINSZ, &ws) < 0)
2061			memset(&ws, 0, sizeof(ws));
2062
2063		channel_request_start(id, "pty-req", 1);
2064		client_expect_confirm(id, "PTY allocation", CONFIRM_TTY);
2065		packet_put_cstring(term != NULL ? term : "");
2066		packet_put_int((u_int)ws.ws_col);
2067		packet_put_int((u_int)ws.ws_row);
2068		packet_put_int((u_int)ws.ws_xpixel);
2069		packet_put_int((u_int)ws.ws_ypixel);
2070		if (tiop == NULL)
2071			tiop = get_saved_tio();
2072		tty_make_modes(-1, tiop);
2073		packet_send();
2074		/* XXX wait for reply */
2075		c->client_tty = 1;
2076	}
2077
2078	/* Transfer any environment variables from client to server */
2079	if (options.num_send_env != 0 && env != NULL) {
2080		int i, j, matched;
2081		char *name, *val;
2082
2083		debug("Sending environment.");
2084		for (i = 0; env[i] != NULL; i++) {
2085			/* Split */
2086			name = xstrdup(env[i]);
2087			if ((val = strchr(name, '=')) == NULL) {
2088				xfree(name);
2089				continue;
2090			}
2091			*val++ = '\0';
2092
2093			matched = 0;
2094			for (j = 0; j < options.num_send_env; j++) {
2095				if (match_pattern(name, options.send_env[j])) {
2096					matched = 1;
2097					break;
2098				}
2099			}
2100			if (!matched) {
2101				debug3("Ignored env %s", name);
2102				xfree(name);
2103				continue;
2104			}
2105
2106			debug("Sending env %s = %s", name, val);
2107			channel_request_start(id, "env", 0);
2108			packet_put_cstring(name);
2109			packet_put_cstring(val);
2110			packet_send();
2111			xfree(name);
2112		}
2113	}
2114
2115	len = buffer_len(cmd);
2116	if (len > 0) {
2117		if (len > 900)
2118			len = 900;
2119		if (want_subsystem) {
2120			debug("Sending subsystem: %.*s",
2121			    len, (u_char*)buffer_ptr(cmd));
2122			channel_request_start(id, "subsystem", 1);
2123			client_expect_confirm(id, "subsystem", CONFIRM_CLOSE);
2124		} else {
2125			debug("Sending command: %.*s",
2126			    len, (u_char*)buffer_ptr(cmd));
2127			channel_request_start(id, "exec", 1);
2128			client_expect_confirm(id, "exec", CONFIRM_CLOSE);
2129		}
2130		packet_put_string(buffer_ptr(cmd), buffer_len(cmd));
2131		packet_send();
2132	} else {
2133		channel_request_start(id, "shell", 1);
2134		client_expect_confirm(id, "shell", CONFIRM_CLOSE);
2135		packet_send();
2136	}
2137}
2138
2139static void
2140client_init_dispatch_20(void)
2141{
2142	dispatch_init(&dispatch_protocol_error);
2143
2144	dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
2145	dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
2146	dispatch_set(SSH2_MSG_CHANNEL_EOF, &channel_input_ieof);
2147	dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA, &channel_input_extended_data);
2148	dispatch_set(SSH2_MSG_CHANNEL_OPEN, &client_input_channel_open);
2149	dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2150	dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2151	dispatch_set(SSH2_MSG_CHANNEL_REQUEST, &client_input_channel_req);
2152	dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST, &channel_input_window_adjust);
2153	dispatch_set(SSH2_MSG_CHANNEL_SUCCESS, &channel_input_status_confirm);
2154	dispatch_set(SSH2_MSG_CHANNEL_FAILURE, &channel_input_status_confirm);
2155	dispatch_set(SSH2_MSG_GLOBAL_REQUEST, &client_input_global_request);
2156
2157	/* rekeying */
2158	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
2159
2160	/* global request reply messages */
2161	dispatch_set(SSH2_MSG_REQUEST_FAILURE, &client_global_request_reply);
2162	dispatch_set(SSH2_MSG_REQUEST_SUCCESS, &client_global_request_reply);
2163}
2164
2165static void
2166client_init_dispatch_13(void)
2167{
2168	dispatch_init(NULL);
2169	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
2170	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
2171	dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
2172	dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
2173	dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
2174	dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
2175	dispatch_set(SSH_SMSG_EXITSTATUS, &client_input_exit_status);
2176	dispatch_set(SSH_SMSG_STDERR_DATA, &client_input_stderr_data);
2177	dispatch_set(SSH_SMSG_STDOUT_DATA, &client_input_stdout_data);
2178
2179	dispatch_set(SSH_SMSG_AGENT_OPEN, options.forward_agent ?
2180	    &client_input_agent_open : &deny_input_open);
2181	dispatch_set(SSH_SMSG_X11_OPEN, options.forward_x11 ?
2182	    &x11_input_open : &deny_input_open);
2183}
2184
2185static void
2186client_init_dispatch_15(void)
2187{
2188	client_init_dispatch_13();
2189	dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
2190	dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, & channel_input_oclose);
2191}
2192
2193static void
2194client_init_dispatch(void)
2195{
2196	if (compat20)
2197		client_init_dispatch_20();
2198	else if (compat13)
2199		client_init_dispatch_13();
2200	else
2201		client_init_dispatch_15();
2202}
2203
2204void
2205client_stop_mux(void)
2206{
2207	if (options.control_path != NULL && muxserver_sock != -1)
2208		unlink(options.control_path);
2209	/*
2210	 * If we are in persist mode, signal that we should close when all
2211	 * active channels are closed.
2212	 */
2213	if (options.control_persist) {
2214		session_closed = 1;
2215		setproctitle("[stopped mux]");
2216	}
2217}
2218
2219/* client specific fatal cleanup */
2220void
2221cleanup_exit(int i)
2222{
2223	leave_raw_mode(options.request_tty == REQUEST_TTY_FORCE);
2224	leave_non_blocking();
2225	if (options.control_path != NULL && muxserver_sock != -1)
2226		unlink(options.control_path);
2227	ssh_kill_proxy_command();
2228	_exit(i);
2229}
2230