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