Home | History | Annotate | Download | only in sshd
      1 /*
      2  * Author: Tatu Ylonen <ylo (at) cs.hut.fi>
      3  * Copyright (c) 1995 Tatu Ylonen <ylo (at) cs.hut.fi>, Espoo, Finland
      4  *                    All rights reserved
      5  * Server main loop for handling the interactive session.
      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  * SSH2 support by Markus Friedl.
     14  * Copyright (c) 2000, 2001 Markus Friedl.  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  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
     38  * Use is subject to license terms.
     39  */
     40 
     41 #include "includes.h"
     42 RCSID("$OpenBSD: serverloop.c,v 1.104 2002/09/19 16:03:15 stevesk Exp $");
     43 
     44 #include "xmalloc.h"
     45 #include "packet.h"
     46 #include "buffer.h"
     47 #include "log.h"
     48 #include "servconf.h"
     49 #include "canohost.h"
     50 #include "sshpty.h"
     51 #include "channels.h"
     52 #include "compat.h"
     53 #include "ssh1.h"
     54 #include "ssh2.h"
     55 #include "auth.h"
     56 #include "session.h"
     57 #include "dispatch.h"
     58 #include "auth-options.h"
     59 #include "serverloop.h"
     60 #include "misc.h"
     61 #include "kex.h"
     62 
     63 #ifdef ALTPRIVSEP
     64 #include "altprivsep.h"
     65 #endif /* ALTPRIVSEP*/
     66 
     67 extern ServerOptions options;
     68 
     69 /* XXX */
     70 extern Kex *xxx_kex;
     71 static Authctxt *xxx_authctxt;
     72 
     73 static Buffer stdin_buffer;	/* Buffer for stdin data. */
     74 static Buffer stdout_buffer;	/* Buffer for stdout data. */
     75 static Buffer stderr_buffer;	/* Buffer for stderr data. */
     76 static int fdin;		/* Descriptor for stdin (for writing) */
     77 static int fdout;		/* Descriptor for stdout (for reading);
     78 				   May be same number as fdin. */
     79 static int fderr;		/* Descriptor for stderr.  May be -1. */
     80 static long stdin_bytes = 0;	/* Number of bytes written to stdin. */
     81 static long stdout_bytes = 0;	/* Number of stdout bytes sent to client. */
     82 static long stderr_bytes = 0;	/* Number of stderr bytes sent to client. */
     83 static long fdout_bytes = 0;	/* Number of stdout bytes read from program. */
     84 static int stdin_eof = 0;	/* EOF message received from client. */
     85 static int fdout_eof = 0;	/* EOF encountered reading from fdout. */
     86 static int fderr_eof = 0;	/* EOF encountered readung from fderr. */
     87 static int fdin_is_tty = 0;	/* fdin points to a tty. */
     88 static int connection_in;	/* Connection to client (input). */
     89 static int connection_out;	/* Connection to client (output). */
     90 static int connection_closed = 0;	/* Connection to client closed. */
     91 static u_int buffer_high;	/* "Soft" max buffer size. */
     92 static int client_alive_timeouts = 0;
     93 
     94 /*
     95  * This SIGCHLD kludge is used to detect when the child exits.  The server
     96  * will exit after that, as soon as forwarded connections have terminated.
     97  */
     98 
     99 static volatile sig_atomic_t child_terminated = 0;	/* The child has terminated. */
    100 
    101 /* prototypes */
    102 static void server_init_dispatch(void);
    103 
    104 /*
    105  * we write to this pipe if a SIGCHLD is caught in order to avoid
    106  * the race between select() and child_terminated
    107  */
    108 static int notify_pipe[2];
    109 static void
    110 notify_setup(void)
    111 {
    112 	if (pipe(notify_pipe) < 0) {
    113 		error("pipe(notify_pipe) failed %s", strerror(errno));
    114 	} else if ((fcntl(notify_pipe[0], F_SETFD, 1) == -1) ||
    115 	    (fcntl(notify_pipe[1], F_SETFD, 1) == -1)) {
    116 		error("fcntl(notify_pipe, F_SETFD) failed %s", strerror(errno));
    117 		(void) close(notify_pipe[0]);
    118 		(void) close(notify_pipe[1]);
    119 	} else {
    120 		set_nonblock(notify_pipe[0]);
    121 		set_nonblock(notify_pipe[1]);
    122 		return;
    123 	}
    124 	notify_pipe[0] = -1;	/* read end */
    125 	notify_pipe[1] = -1;	/* write end */
    126 }
    127 static void
    128 notify_parent(void)
    129 {
    130 	if (notify_pipe[1] != -1)
    131 		(void) write(notify_pipe[1], "", 1);
    132 }
    133 static void
    134 notify_prepare(fd_set *readset)
    135 {
    136 	if (notify_pipe[0] != -1)
    137 		FD_SET(notify_pipe[0], readset);
    138 }
    139 static void
    140 notify_done(fd_set *readset)
    141 {
    142 	char c;
    143 
    144 	if (notify_pipe[0] != -1 && FD_ISSET(notify_pipe[0], readset))
    145 		while (read(notify_pipe[0], &c, 1) != -1)
    146 			debug2("notify_done: reading");
    147 }
    148 
    149 static void
    150 sigchld_handler(int sig)
    151 {
    152 	int save_errno = errno;
    153 	debug("Received SIGCHLD.");
    154 	child_terminated = 1;
    155 #ifndef _UNICOS
    156 	mysignal(SIGCHLD, sigchld_handler);
    157 #endif
    158 	notify_parent();
    159 	errno = save_errno;
    160 }
    161 
    162 /*
    163  * Make packets from buffered stderr data, and buffer it for sending
    164  * to the client.
    165  */
    166 static void
    167 make_packets_from_stderr_data(void)
    168 {
    169 	int len;
    170 
    171 	/* Send buffered stderr data to the client. */
    172 	while (buffer_len(&stderr_buffer) > 0 &&
    173 	    packet_not_very_much_data_to_write()) {
    174 		len = buffer_len(&stderr_buffer);
    175 		if (packet_is_interactive()) {
    176 			if (len > 512)
    177 				len = 512;
    178 		} else {
    179 			/* Keep the packets at reasonable size. */
    180 			if (len > packet_get_maxsize())
    181 				len = packet_get_maxsize();
    182 		}
    183 		packet_start(SSH_SMSG_STDERR_DATA);
    184 		packet_put_string(buffer_ptr(&stderr_buffer), len);
    185 		packet_send();
    186 		buffer_consume(&stderr_buffer, len);
    187 		stderr_bytes += len;
    188 	}
    189 }
    190 
    191 /*
    192  * Make packets from buffered stdout data, and buffer it for sending to the
    193  * client.
    194  */
    195 static void
    196 make_packets_from_stdout_data(void)
    197 {
    198 	int len;
    199 
    200 	/* Send buffered stdout data to the client. */
    201 	while (buffer_len(&stdout_buffer) > 0 &&
    202 	    packet_not_very_much_data_to_write()) {
    203 		len = buffer_len(&stdout_buffer);
    204 		if (packet_is_interactive()) {
    205 			if (len > 512)
    206 				len = 512;
    207 		} else {
    208 			/* Keep the packets at reasonable size. */
    209 			if (len > packet_get_maxsize())
    210 				len = packet_get_maxsize();
    211 		}
    212 		packet_start(SSH_SMSG_STDOUT_DATA);
    213 		packet_put_string(buffer_ptr(&stdout_buffer), len);
    214 		packet_send();
    215 		buffer_consume(&stdout_buffer, len);
    216 		stdout_bytes += len;
    217 	}
    218 }
    219 
    220 static void
    221 client_alive_check(void)
    222 {
    223 	static int had_channel = 0;
    224 	int id;
    225 
    226 	id = channel_find_open();
    227 	if (id == -1) {
    228 		if (!had_channel)
    229 			return;
    230 		packet_disconnect("No open channels after timeout!");
    231 	}
    232 	had_channel = 1;
    233 
    234 	/* timeout, check to see how many we have had */
    235 	if (++client_alive_timeouts > options.client_alive_count_max)
    236 		packet_disconnect("Timeout, your session not responding.");
    237 
    238 	/*
    239 	 * send a bogus channel request with "wantreply",
    240 	 * we should get back a failure
    241 	 */
    242 	channel_request_start(id, "keepalive (at) openssh.com", 1);
    243 	packet_send();
    244 }
    245 
    246 /*
    247  * Sleep in select() until we can do something.  This will initialize the
    248  * select masks.  Upon return, the masks will indicate which descriptors
    249  * have data or can accept data.  Optionally, a maximum time can be specified
    250  * for the duration of the wait (0 = infinite).
    251  */
    252 static void
    253 wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
    254     int *nallocp, u_int max_time_milliseconds)
    255 {
    256 	struct timeval tv, *tvp;
    257 	int ret;
    258 	int client_alive_scheduled = 0;
    259 
    260 	/*
    261 	 * if using client_alive, set the max timeout accordingly,
    262 	 * and indicate that this particular timeout was for client
    263 	 * alive by setting the client_alive_scheduled flag.
    264 	 *
    265 	 * this could be randomized somewhat to make traffic
    266 	 * analysis more difficult, but we're not doing it yet.
    267 	 */
    268 	if (compat20 &&
    269 	    max_time_milliseconds == 0 && options.client_alive_interval) {
    270 		client_alive_scheduled = 1;
    271 		max_time_milliseconds = options.client_alive_interval * 1000;
    272 	}
    273 
    274 	/* Allocate and update select() masks for channel descriptors. */
    275 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 0);
    276 
    277 	if (compat20) {
    278 #ifdef ALTPRIVSEP
    279 		int pipe_fd;
    280 
    281 		if ((pipe_fd = altprivsep_get_pipe_fd()) != -1) {
    282 			*maxfdp = MAX(*maxfdp, pipe_fd);
    283 			FD_SET(altprivsep_get_pipe_fd(), *readsetp);
    284 		}
    285 #endif /* ALTPRIVSEP */
    286 #if 0
    287 		/* wrong: bad condition XXX */
    288 		if (channel_not_very_much_buffered_data())
    289 #endif
    290 		FD_SET(connection_in, *readsetp);
    291 	} else {
    292 		/*
    293 		 * Read packets from the client unless we have too much
    294 		 * buffered stdin or channel data.
    295 		 */
    296 		if (buffer_len(&stdin_buffer) < buffer_high &&
    297 		    channel_not_very_much_buffered_data())
    298 			FD_SET(connection_in, *readsetp);
    299 		/*
    300 		 * If there is not too much data already buffered going to
    301 		 * the client, try to get some more data from the program.
    302 		 */
    303 		if (packet_not_very_much_data_to_write()) {
    304 			if (!fdout_eof)
    305 				FD_SET(fdout, *readsetp);
    306 			if (!fderr_eof)
    307 				FD_SET(fderr, *readsetp);
    308 		}
    309 		/*
    310 		 * If we have buffered data, try to write some of that data
    311 		 * to the program.
    312 		 */
    313 		if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
    314 			FD_SET(fdin, *writesetp);
    315 	}
    316 	notify_prepare(*readsetp);
    317 
    318 	/*
    319 	 * If we have buffered packet data going to the client, mark that
    320 	 * descriptor.
    321 	 */
    322 	if (packet_have_data_to_write())
    323 		FD_SET(connection_out, *writesetp);
    324 
    325 	/*
    326 	 * If child has terminated and there is enough buffer space to read
    327 	 * from it, then read as much as is available and exit.
    328 	 */
    329 	if (child_terminated && packet_not_very_much_data_to_write())
    330 		if (max_time_milliseconds == 0 || client_alive_scheduled)
    331 			max_time_milliseconds = 100;
    332 
    333 	if (max_time_milliseconds == 0)
    334 		tvp = NULL;
    335 	else {
    336 		tv.tv_sec = max_time_milliseconds / 1000;
    337 		tv.tv_usec = 1000 * (max_time_milliseconds % 1000);
    338 		tvp = &tv;
    339 	}
    340 
    341 	/* Wait for something to happen, or the timeout to expire. */
    342 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, tvp);
    343 
    344 	if (ret == -1) {
    345 		memset(*readsetp, 0, *nallocp);
    346 		memset(*writesetp, 0, *nallocp);
    347 		if (errno != EINTR)
    348 			error("select: %.100s", strerror(errno));
    349 	} else if (ret == 0 && client_alive_scheduled)
    350 		client_alive_check();
    351 
    352 	notify_done(*readsetp);
    353 }
    354 
    355 /*
    356  * Processes input from the client and the program.  Input data is stored
    357  * in buffers and processed later.
    358  */
    359 static void
    360 process_input(fd_set * readset)
    361 {
    362 	int len;
    363 	char buf[16384];
    364 
    365 	/* Read and buffer any input data from the client. */
    366 	if (FD_ISSET(connection_in, readset)) {
    367 		len = read(connection_in, buf, sizeof(buf));
    368 		if (len == 0) {
    369 			if (packet_is_monitor()) {
    370 				debug("child closed the communication pipe");
    371 			} else {
    372 				verbose("Connection closed by %.100s",
    373 				    get_remote_ipaddr());
    374 			}
    375 			connection_closed = 1;
    376 			if (compat20)
    377 				return;
    378 			fatal_cleanup();
    379 		} else if (len < 0) {
    380 			if (errno != EINTR && errno != EAGAIN) {
    381 				verbose("Read error from remote host "
    382 				    "%.100s: %.100s",
    383 				    get_remote_ipaddr(), strerror(errno));
    384 				fatal_cleanup();
    385 			}
    386 		} else {
    387 			/* Buffer any received data. */
    388 			packet_process_incoming(buf, len);
    389 		}
    390 	}
    391 	if (compat20)
    392 		return;
    393 
    394 	/* Read and buffer any available stdout data from the program. */
    395 	if (!fdout_eof && FD_ISSET(fdout, readset)) {
    396 		len = read(fdout, buf, sizeof(buf));
    397 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    398 			/* EMPTY */
    399 		} else if (len <= 0) {
    400 			fdout_eof = 1;
    401 		} else {
    402 			buffer_append(&stdout_buffer, buf, len);
    403 			fdout_bytes += len;
    404 		}
    405 	}
    406 	/* Read and buffer any available stderr data from the program. */
    407 	if (!fderr_eof && FD_ISSET(fderr, readset)) {
    408 		len = read(fderr, buf, sizeof(buf));
    409 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    410 			/* EMPTY */
    411 		} else if (len <= 0) {
    412 			fderr_eof = 1;
    413 		} else {
    414 			buffer_append(&stderr_buffer, buf, len);
    415 		}
    416 	}
    417 }
    418 
    419 /*
    420  * Sends data from internal buffers to client program stdin.
    421  */
    422 static void
    423 process_output(fd_set * writeset)
    424 {
    425 	struct termios tio;
    426 	u_char *data;
    427 	u_int dlen;
    428 	int len;
    429 
    430 	/* Write buffered data to program stdin. */
    431 	if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
    432 		data = buffer_ptr(&stdin_buffer);
    433 		dlen = buffer_len(&stdin_buffer);
    434 		len = write(fdin, data, dlen);
    435 		if (len < 0 && (errno == EINTR || errno == EAGAIN)) {
    436 			/* EMPTY */
    437 		} else if (len <= 0) {
    438 			if (fdin != fdout)
    439 				(void) close(fdin);
    440 			else
    441 				(void) shutdown(fdin, SHUT_WR); /* We will no longer send. */
    442 			fdin = -1;
    443 		} else {
    444 			/* Successful write. */
    445 			if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
    446 			    tcgetattr(fdin, &tio) == 0 &&
    447 			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
    448 				/*
    449 				 * Simulate echo to reduce the impact of
    450 				 * traffic analysis
    451 				 */
    452 				packet_send_ignore(len);
    453 				packet_send();
    454 			}
    455 			/* Consume the data from the buffer. */
    456 			buffer_consume(&stdin_buffer, len);
    457 			/* Update the count of bytes written to the program. */
    458 			stdin_bytes += len;
    459 		}
    460 	}
    461 	/* Send any buffered packet data to the client. */
    462 	if (FD_ISSET(connection_out, writeset))
    463 		packet_write_poll();
    464 }
    465 
    466 /*
    467  * Wait until all buffered output has been sent to the client.
    468  * This is used when the program terminates.
    469  */
    470 static void
    471 drain_output(void)
    472 {
    473 	/* Send any buffered stdout data to the client. */
    474 	if (buffer_len(&stdout_buffer) > 0) {
    475 		packet_start(SSH_SMSG_STDOUT_DATA);
    476 		packet_put_string(buffer_ptr(&stdout_buffer),
    477 				  buffer_len(&stdout_buffer));
    478 		packet_send();
    479 		/* Update the count of sent bytes. */
    480 		stdout_bytes += buffer_len(&stdout_buffer);
    481 	}
    482 	/* Send any buffered stderr data to the client. */
    483 	if (buffer_len(&stderr_buffer) > 0) {
    484 		packet_start(SSH_SMSG_STDERR_DATA);
    485 		packet_put_string(buffer_ptr(&stderr_buffer),
    486 				  buffer_len(&stderr_buffer));
    487 		packet_send();
    488 		/* Update the count of sent bytes. */
    489 		stderr_bytes += buffer_len(&stderr_buffer);
    490 	}
    491 	/* Wait until all buffered data has been written to the client. */
    492 	packet_write_wait();
    493 }
    494 
    495 static void
    496 process_buffered_input_packets(void)
    497 {
    498 	dispatch_run(DISPATCH_NONBLOCK, NULL, compat20 ? xxx_kex : NULL);
    499 }
    500 
    501 /*
    502  * Performs the interactive session.  This handles data transmission between
    503  * the client and the program.  Note that the notion of stdin, stdout, and
    504  * stderr in this function is sort of reversed: this function writes to
    505  * stdin (of the child program), and reads from stdout and stderr (of the
    506  * child program).
    507  */
    508 void
    509 server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
    510 {
    511 	fd_set *readset = NULL, *writeset = NULL;
    512 	int max_fd = 0, nalloc = 0;
    513 	int wait_status;	/* Status returned by wait(). */
    514 	pid_t wait_pid;		/* pid returned by wait(). */
    515 	int waiting_termination = 0;	/* Have displayed waiting close message. */
    516 	u_int max_time_milliseconds;
    517 	u_int previous_stdout_buffer_bytes;
    518 	u_int stdout_buffer_bytes;
    519 	int type;
    520 
    521 	debug("Entering interactive session.");
    522 
    523 	/* Initialize the SIGCHLD kludge. */
    524 	child_terminated = 0;
    525 	mysignal(SIGCHLD, sigchld_handler);
    526 
    527 	/* Initialize our global variables. */
    528 	fdin = fdin_arg;
    529 	fdout = fdout_arg;
    530 	fderr = fderr_arg;
    531 
    532 	/* nonblocking IO */
    533 	set_nonblock(fdin);
    534 	set_nonblock(fdout);
    535 	/* we don't have stderr for interactive terminal sessions, see below */
    536 	if (fderr != -1)
    537 		set_nonblock(fderr);
    538 
    539 	if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
    540 		fdin_is_tty = 1;
    541 
    542 	connection_in = packet_get_connection_in();
    543 	connection_out = packet_get_connection_out();
    544 
    545 	notify_setup();
    546 
    547 	previous_stdout_buffer_bytes = 0;
    548 
    549 	/* Set approximate I/O buffer size. */
    550 	if (packet_is_interactive())
    551 		buffer_high = 4096;
    552 	else
    553 		buffer_high = 64 * 1024;
    554 
    555 #if 0
    556 	/* Initialize max_fd to the maximum of the known file descriptors. */
    557 	max_fd = MAX(connection_in, connection_out);
    558 	max_fd = MAX(max_fd, fdin);
    559 	max_fd = MAX(max_fd, fdout);
    560 	if (fderr != -1)
    561 		max_fd = MAX(max_fd, fderr);
    562 #endif
    563 
    564 	/* Initialize Initialize buffers. */
    565 	buffer_init(&stdin_buffer);
    566 	buffer_init(&stdout_buffer);
    567 	buffer_init(&stderr_buffer);
    568 
    569 	/*
    570 	 * If we have no separate fderr (which is the case when we have a pty
    571 	 * - there we cannot make difference between data sent to stdout and
    572 	 * stderr), indicate that we have seen an EOF from stderr.  This way
    573 	 * we don\'t need to check the descriptor everywhere.
    574 	 */
    575 	if (fderr == -1)
    576 		fderr_eof = 1;
    577 
    578 	server_init_dispatch();
    579 
    580 	/* Main loop of the server for the interactive session mode. */
    581 	for (;;) {
    582 
    583 		/* Process buffered packets from the client. */
    584 		process_buffered_input_packets();
    585 
    586 		/*
    587 		 * If we have received eof, and there is no more pending
    588 		 * input data, cause a real eof by closing fdin.
    589 		 */
    590 		if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
    591 			if (fdin != fdout)
    592 				(void) close(fdin);
    593 			else
    594 				(void) shutdown(fdin, SHUT_WR); /* We will no longer send. */
    595 			fdin = -1;
    596 		}
    597 		/* Make packets from buffered stderr data to send to the client. */
    598 		make_packets_from_stderr_data();
    599 
    600 		/*
    601 		 * Make packets from buffered stdout data to send to the
    602 		 * client. If there is very little to send, this arranges to
    603 		 * not send them now, but to wait a short while to see if we
    604 		 * are getting more data. This is necessary, as some systems
    605 		 * wake up readers from a pty after each separate character.
    606 		 */
    607 		max_time_milliseconds = 0;
    608 		stdout_buffer_bytes = buffer_len(&stdout_buffer);
    609 		if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
    610 		    stdout_buffer_bytes != previous_stdout_buffer_bytes) {
    611 			/* try again after a while */
    612 			max_time_milliseconds = 10;
    613 		} else {
    614 			/* Send it now. */
    615 			make_packets_from_stdout_data();
    616 		}
    617 		previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
    618 
    619 		/* Send channel data to the client. */
    620 		if (packet_not_very_much_data_to_write())
    621 			channel_output_poll();
    622 
    623 		/*
    624 		 * Bail out of the loop if the program has closed its output
    625 		 * descriptors, and we have no more data to send to the
    626 		 * client, and there is no pending buffered data.
    627 		 */
    628 		if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
    629 		    buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
    630 			if (!channel_still_open())
    631 				break;
    632 			if (!waiting_termination) {
    633 				const char *s = "Waiting for forwarded connections to terminate...\r\n";
    634 				char *cp;
    635 				waiting_termination = 1;
    636 				buffer_append(&stderr_buffer, s, strlen(s));
    637 
    638 				/* Display list of open channels. */
    639 				cp = channel_open_message();
    640 				buffer_append(&stderr_buffer, cp, strlen(cp));
    641 				xfree(cp);
    642 			}
    643 		}
    644 		max_fd = MAX(connection_in, connection_out);
    645 		max_fd = MAX(max_fd, fdin);
    646 		max_fd = MAX(max_fd, fdout);
    647 		max_fd = MAX(max_fd, fderr);
    648 		max_fd = MAX(max_fd, notify_pipe[0]);
    649 
    650 		/* Sleep in select() until we can do something. */
    651 		wait_until_can_do_something(&readset, &writeset, &max_fd,
    652 		    &nalloc, max_time_milliseconds);
    653 
    654 		/* Process any channel events. */
    655 		channel_after_select(readset, writeset);
    656 
    657 		/* Process input from the client and from program stdout/stderr. */
    658 		process_input(readset);
    659 
    660 		/* Process output to the client and to program stdin. */
    661 		process_output(writeset);
    662 	}
    663 	if (readset)
    664 		xfree(readset);
    665 	if (writeset)
    666 		xfree(writeset);
    667 
    668 	/* Cleanup and termination code. */
    669 
    670 	/* Wait until all output has been sent to the client. */
    671 	drain_output();
    672 
    673 	debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
    674 	    stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
    675 
    676 	/* Free and clear the buffers. */
    677 	buffer_free(&stdin_buffer);
    678 	buffer_free(&stdout_buffer);
    679 	buffer_free(&stderr_buffer);
    680 
    681 	/* Close the file descriptors. */
    682 	if (fdout != -1)
    683 		(void) close(fdout);
    684 	fdout = -1;
    685 	fdout_eof = 1;
    686 	if (fderr != -1)
    687 		(void) close(fderr);
    688 	fderr = -1;
    689 	fderr_eof = 1;
    690 	if (fdin != -1)
    691 		(void) close(fdin);
    692 	fdin = -1;
    693 
    694 	channel_free_all();
    695 
    696 	/* We no longer want our SIGCHLD handler to be called. */
    697 	mysignal(SIGCHLD, SIG_DFL);
    698 
    699 	while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
    700 		if (errno != EINTR)
    701 			packet_disconnect("wait: %.100s", strerror(errno));
    702 	if (wait_pid != pid)
    703 		error("Strange, wait returned pid %ld, expected %ld",
    704 		    (long)wait_pid, (long)pid);
    705 
    706 	/* Check if it exited normally. */
    707 	if (WIFEXITED(wait_status)) {
    708 		/* Yes, normal exit.  Get exit status and send it to the client. */
    709 		debug("Command exited with status %d.", WEXITSTATUS(wait_status));
    710 		packet_start(SSH_SMSG_EXITSTATUS);
    711 		packet_put_int(WEXITSTATUS(wait_status));
    712 		packet_send();
    713 		packet_write_wait();
    714 
    715 		/*
    716 		 * Wait for exit confirmation.  Note that there might be
    717 		 * other packets coming before it; however, the program has
    718 		 * already died so we just ignore them.  The client is
    719 		 * supposed to respond with the confirmation when it receives
    720 		 * the exit status.
    721 		 */
    722 		do {
    723 			type = packet_read();
    724 		}
    725 		while (type != SSH_CMSG_EXIT_CONFIRMATION);
    726 
    727 		debug("Received exit confirmation.");
    728 		return;
    729 	}
    730 	/* Check if the program terminated due to a signal. */
    731 	if (WIFSIGNALED(wait_status))
    732 		packet_disconnect("Command terminated on signal %d.",
    733 				  WTERMSIG(wait_status));
    734 
    735 	/* Some weird exit cause.  Just exit. */
    736 	packet_disconnect("wait returned status %04x.", wait_status);
    737 	/* NOTREACHED */
    738 }
    739 
    740 static void
    741 collect_children(void)
    742 {
    743 	pid_t pid;
    744 	sigset_t oset, nset;
    745 	int status;
    746 
    747 	/* block SIGCHLD while we check for dead children */
    748 	(void) sigemptyset(&nset);
    749 	(void) sigaddset(&nset, SIGCHLD);
    750 	(void) sigprocmask(SIG_BLOCK, &nset, &oset);
    751 	if (child_terminated) {
    752 		while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
    753 		    (pid < 0 && errno == EINTR))
    754 			if (pid > 0)
    755 				session_close_by_pid(pid, status);
    756 		child_terminated = 0;
    757 	}
    758 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
    759 }
    760 
    761 #ifdef ALTPRIVSEP
    762 /*
    763  * For ALTPRIVSEP the wait_until_can_do_something function is very
    764  * simple: select() on the read side of the pipe, and if there's packets
    765  * to send, on the write side, and on the read side of the SIGCHLD
    766  * handler pipe.  That's it.
    767  */
    768 static void
    769 aps_wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp,
    770 	int *maxfdp, int *nallocp, u_int max_time_milliseconds)
    771 {
    772 	int ret;
    773 
    774 	/*
    775 	 * Use channel_prepare_select() to make the fd sets.
    776 	 *
    777 	 * This is cheating, really, since because the last argument in
    778 	 * this call is '1' nothing related to channels will be done --
    779 	 * we're using this function only to callocate the fd sets.
    780 	 */
    781 	channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 1);
    782 
    783 	if ((connection_in = packet_get_connection_in()) >= 0 &&
    784 	    !connection_closed)
    785 		FD_SET(connection_in, *readsetp);
    786 
    787 	notify_prepare(*readsetp);
    788 
    789 	if ((connection_out = packet_get_connection_out()) >= 0 &&
    790 	    packet_have_data_to_write() && !connection_closed)
    791 		FD_SET(connection_out, *writesetp);
    792 
    793 	/* Wait for something to happen, or the timeout to expire. */
    794 	ret = select((*maxfdp)+1, *readsetp, *writesetp, NULL, NULL);
    795 
    796 	if (ret == -1) {
    797 		memset(*readsetp, 0, *nallocp);
    798 		memset(*writesetp, 0, *nallocp);
    799 		if (errno != EINTR)
    800 			error("select: %.100s", strerror(errno));
    801 	}
    802 
    803 	notify_done(*readsetp);
    804 }
    805 
    806 /*
    807  * Slightly different than collect_children, aps_collect_child() has
    808  * only the unprivileged sshd to wait for, no sessions, no channells,
    809  * just one process.
    810  */
    811 static int
    812 aps_collect_child(pid_t child)
    813 {
    814 	pid_t pid;
    815 	sigset_t oset, nset;
    816 	int status;
    817 
    818 	/* block SIGCHLD while we check for dead children */
    819 	(void) sigemptyset(&nset);
    820 	(void) sigaddset(&nset, SIGCHLD);
    821 	(void) sigprocmask(SIG_BLOCK, &nset, &oset);
    822 	if (child_terminated) {
    823 		while ((pid = waitpid(child, &status, WNOHANG)) > 0 ||
    824 		    (pid < 0 && errno == EINTR))
    825 			if (pid == child) {
    826 				(void) sigprocmask(SIG_SETMASK, &oset, NULL);
    827 				return (1);
    828 			}
    829 		child_terminated = 0;
    830 	}
    831 	(void) sigprocmask(SIG_SETMASK, &oset, NULL);
    832 	return (0);
    833 }
    834 
    835 static int killed = 0;
    836 
    837 static void
    838 aps_monitor_kill_handler(int sig)
    839 {
    840 	int save_errno = errno;
    841 	killed = 1;
    842 	notify_parent();
    843 	mysignal(sig, aps_monitor_kill_handler);
    844 	errno = save_errno;
    845 }
    846 
    847 static void
    848 aps_monitor_sigchld_handler(int sig)
    849 {
    850 	int save_errno = errno;
    851 	debug("Monitor received SIGCHLD.");
    852 	child_terminated = 1;
    853 	mysignal(SIGCHLD, aps_monitor_sigchld_handler);
    854 	notify_parent();
    855 	errno = save_errno;
    856 }
    857 
    858 void
    859 aps_monitor_loop(Authctxt *authctxt, pid_t child_pid)
    860 {
    861 	fd_set *readset = NULL, *writeset = NULL;
    862 	int max_fd, nalloc = 0;
    863 
    864 	debug("Entering monitor loop.");
    865 
    866 	/*
    867 	 * Awful hack follows: fake compat20 == 1 to cause process_input()
    868 	 * and process_output() to behave as they would for SSHv2 because that's
    869 	 * the behaviour we need in SSHv2.
    870 	 *
    871 	 * This same hack is done in packet.c
    872 	 */
    873 	compat20 = 1; /* causes process_input/output() to ignore stdio */
    874 
    875 	mysignal(SIGHUP, aps_monitor_kill_handler);
    876 	mysignal(SIGINT, aps_monitor_kill_handler);
    877 	mysignal(SIGTERM, aps_monitor_kill_handler);
    878 
    879 	child_terminated = 0;
    880 	mysignal(SIGCHLD, aps_monitor_sigchld_handler);
    881 
    882 	connection_in = packet_get_connection_in();
    883 	connection_out = packet_get_connection_out();
    884 
    885 	notify_setup();
    886 
    887 	max_fd = MAX(connection_in, connection_out);
    888 	max_fd = MAX(max_fd, notify_pipe[0]);
    889 
    890 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
    891 	dispatch_range(SSH2_MSG_USERAUTH_MIN, SSH2_MSG_MAX,
    892 		&dispatch_protocol_error);
    893 	dispatch_set(SSH2_PRIV_MSG_ALTPRIVSEP, &aps_input_altpriv_msg);
    894 
    895 	for (;;) {
    896 		process_buffered_input_packets();
    897 
    898 		aps_wait_until_can_do_something(&readset, &writeset, &max_fd,
    899 		    &nalloc, 0);
    900 
    901 		if (aps_collect_child(child_pid))
    902 			break;
    903 
    904 		if (killed) {
    905 			/* fatal cleanups will kill child, audit logout */
    906 			log("Monitor killed; exiting");
    907 			fatal_cleanup();
    908 		}
    909 
    910 		/*
    911 		 * Unlike server_loop2() we don't care if connection_closed
    912 		 * since we still want to wait for the monitor's child.
    913 		 */
    914 		process_input(readset);
    915 		process_output(writeset);
    916 	}
    917 
    918 	packet_close();
    919 }
    920 #endif /* ALTPRIVSEP */
    921 
    922 /*
    923  * This server loop is for unprivileged child only. Our monitor runs its own
    924  * aps_monitor_loop() funtion.
    925  */
    926 void
    927 server_loop2(Authctxt *authctxt)
    928 {
    929 	fd_set *readset = NULL, *writeset = NULL;
    930 	int rekeying = 0, max_fd, nalloc = 0;
    931 
    932 	debug("Entering interactive session for SSH2.");
    933 
    934 	mysignal(SIGCHLD, sigchld_handler);
    935 	child_terminated = 0;
    936 	connection_in = packet_get_connection_in();
    937 	connection_out = packet_get_connection_out();
    938 
    939 	notify_setup();
    940 
    941 	max_fd = MAX(connection_in, connection_out);
    942 	max_fd = MAX(max_fd, notify_pipe[0]);
    943 
    944 	xxx_authctxt = authctxt;
    945 
    946 	server_init_dispatch();
    947 
    948 	for (;;) {
    949 		process_buffered_input_packets();
    950 
    951 		rekeying = (xxx_kex != NULL && !xxx_kex->done);
    952 
    953 		if (!rekeying && packet_not_very_much_data_to_write())
    954 			channel_output_poll();
    955 		wait_until_can_do_something(&readset, &writeset, &max_fd,
    956 		    &nalloc, 0);
    957 
    958 		collect_children();
    959 
    960 		if (!rekeying) {
    961 			channel_after_select(readset, writeset);
    962 			if (packet_need_rekeying()) {
    963 				debug("rekey limit reached, need rekeying");
    964 				xxx_kex->done = 0;
    965 				debug("poking the monitor to start "
    966 				    "key re-exchange");
    967 				altprivsep_start_rekex();
    968 			}
    969 		}
    970 #ifdef ALTPRIVSEP
    971 		else
    972 			altprivsep_process_input(readset);
    973 #endif /* ALTPRIVSEP */
    974 
    975 		process_input(readset);
    976 		if (connection_closed)
    977 			break;
    978 		process_output(writeset);
    979 	}
    980 	collect_children();
    981 
    982 	if (readset)
    983 		xfree(readset);
    984 	if (writeset)
    985 		xfree(writeset);
    986 
    987 	/* free all channels, no more reads and writes */
    988 	channel_free_all();
    989 
    990 	/* free remaining sessions, e.g. remove wtmp entries */
    991 	session_destroy_all(NULL);
    992 }
    993 
    994 static void
    995 server_input_channel_failure(int type, u_int32_t seq, void *ctxt)
    996 {
    997 	debug("Got CHANNEL_FAILURE for keepalive");
    998 	/*
    999 	 * reset timeout, since we got a sane answer from the client.
   1000 	 * even if this was generated by something other than
   1001 	 * the bogus CHANNEL_REQUEST we send for keepalives.
   1002 	 */
   1003 	client_alive_timeouts = 0;
   1004 }
   1005 
   1006 static void
   1007 server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
   1008 {
   1009 	char *data;
   1010 	u_int data_len;
   1011 
   1012 	/* Stdin data from the client.  Append it to the buffer. */
   1013 	/* Ignore any data if the client has closed stdin. */
   1014 	if (fdin == -1)
   1015 		return;
   1016 	data = packet_get_string(&data_len);
   1017 	packet_check_eom();
   1018 	buffer_append(&stdin_buffer, data, data_len);
   1019 	memset(data, 0, data_len);
   1020 	xfree(data);
   1021 }
   1022 
   1023 static void
   1024 server_input_eof(int type, u_int32_t seq, void *ctxt)
   1025 {
   1026 	/*
   1027 	 * Eof from the client.  The stdin descriptor to the
   1028 	 * program will be closed when all buffered data has
   1029 	 * drained.
   1030 	 */
   1031 	debug("EOF received for stdin.");
   1032 	packet_check_eom();
   1033 	stdin_eof = 1;
   1034 }
   1035 
   1036 static void
   1037 server_input_window_size(int type, u_int32_t seq, void *ctxt)
   1038 {
   1039 	int row = packet_get_int();
   1040 	int col = packet_get_int();
   1041 	int xpixel = packet_get_int();
   1042 	int ypixel = packet_get_int();
   1043 
   1044 	debug("Window change received.");
   1045 	packet_check_eom();
   1046 	if (fdin != -1)
   1047 		pty_change_window_size(fdin, row, col, xpixel, ypixel);
   1048 }
   1049 
   1050 static Channel *
   1051 server_request_direct_tcpip(char *ctype)
   1052 {
   1053 	Channel *c;
   1054 	int sock;
   1055 	char *target, *originator;
   1056 	int target_port, originator_port;
   1057 
   1058 	target = packet_get_string(NULL);
   1059 	target_port = packet_get_int();
   1060 	originator = packet_get_string(NULL);
   1061 	originator_port = packet_get_int();
   1062 	packet_check_eom();
   1063 
   1064 	debug("server_request_direct_tcpip: originator %s port %d, target %s port %d",
   1065 	   originator, originator_port, target, target_port);
   1066 
   1067 	/* XXX check permission */
   1068 	sock = channel_connect_to(target, target_port);
   1069 
   1070 	xfree(target);
   1071 	xfree(originator);
   1072 	if (sock < 0)
   1073 		return NULL;
   1074 	c = channel_new(ctype, SSH_CHANNEL_CONNECTING,
   1075 	    sock, sock, -1, CHAN_TCP_WINDOW_DEFAULT,
   1076 	    CHAN_TCP_PACKET_DEFAULT, 0, xstrdup("direct-tcpip"), 1);
   1077 	return c;
   1078 }
   1079 
   1080 static Channel *
   1081 server_request_session(char *ctype)
   1082 {
   1083 	Channel *c;
   1084 
   1085 	debug("input_session_request");
   1086 	packet_check_eom();
   1087 	/*
   1088 	 * A server session has no fd to read or write until a
   1089 	 * CHANNEL_REQUEST for a shell is made, so we set the type to
   1090 	 * SSH_CHANNEL_LARVAL.  Additionally, a callback for handling all
   1091 	 * CHANNEL_REQUEST messages is registered.
   1092 	 */
   1093 	c = channel_new(ctype, SSH_CHANNEL_LARVAL,
   1094 	    -1, -1, -1, /*window size*/0,